@getstrata/core 2.2.47 → 2.2.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/core/audit/exportStore.d.ts +17 -0
  3. package/dist/core/auth/membershipService.d.ts +3 -23
  4. package/dist/core/auth/membershipServiceImplementation.d.ts +22 -0
  5. package/dist/core/auth/resolveMembershipService.d.ts +1 -1
  6. package/dist/core/cache/redisCacheScript.d.ts +2 -0
  7. package/dist/core/contracts/container.d.ts +2 -0
  8. package/dist/core/database/baseRepository.d.ts +3 -21
  9. package/dist/core/database/boundConnection.d.ts +1 -1
  10. package/dist/core/database/bunSql.d.ts +1 -1
  11. package/dist/core/database/connection.d.ts +1 -1
  12. package/dist/core/database/connectionContracts.d.ts +21 -0
  13. package/dist/core/database/defaultConnection.d.ts +1 -1
  14. package/dist/core/database/index.d.ts +1 -1
  15. package/dist/core/database/isolatedReadOnlyObservation.d.ts +1 -1
  16. package/dist/core/database/model.d.ts +6 -113
  17. package/dist/core/database/modelAttributes.d.ts +17 -0
  18. package/dist/core/database/modelQuery.d.ts +139 -0
  19. package/dist/core/database/modelRegistry.d.ts +34 -0
  20. package/dist/core/database/mysqlConnection.d.ts +1 -1
  21. package/dist/core/database/queryProxy.d.ts +1 -1
  22. package/dist/core/database/relationQueries.d.ts +20 -0
  23. package/dist/core/database/repositoryConnection.d.ts +1 -1
  24. package/dist/core/database/sqliteConnection.d.ts +1 -1
  25. package/dist/core/database/transaction.d.ts +1 -1
  26. package/dist/core/http/middleware.d.ts +2 -2
  27. package/dist/core/http/routeMiddleware.d.ts +1 -1
  28. package/dist/core/mail/mailer.d.ts +1 -4
  29. package/dist/core/mail/smtpMessage.d.ts +7 -0
  30. package/dist/core/queue/redisListScripts.d.ts +5 -0
  31. package/dist/core/queue/redisStreamsScripts.d.ts +11 -0
  32. package/dist/core/scheduler/leaseScript.d.ts +2 -0
  33. package/dist/entries/audit/exportAuditLogs.js +63 -58
  34. package/dist/entries/auth/basicAuthGuard.js +14 -2
  35. package/dist/entries/auth/jwtGuard.js +14 -2
  36. package/dist/entries/auth/membershipService.js +13 -14
  37. package/dist/entries/auth/scimAuthMiddleware.js +34 -20
  38. package/dist/entries/auth/sessionGuard.js +14 -2
  39. package/dist/entries/cache/createCacheStore.js +2 -1
  40. package/dist/entries/config/envSchema.js +2 -1
  41. package/dist/entries/contracts/container.js +14 -2
  42. package/dist/entries/contracts/serviceTokens.js +14 -2
  43. package/dist/entries/facades.js +103 -101
  44. package/dist/entries/http/routeMiddleware.js +3 -3
  45. package/dist/entries/jobs/exportAuditLogsJob.js +63 -58
  46. package/dist/entries/mail/mailer.js +103 -101
  47. package/dist/entries/queue/createAppQueue.js +277 -271
  48. package/dist/entries/queue/publicQueue.js +277 -271
  49. package/dist/entries/queue/queueMetrics.js +277 -271
  50. package/dist/entries/queue/redisQueue.js +277 -271
  51. package/dist/framework/public-api.d.ts +1 -1
  52. package/dist/index.js +1603 -1535
  53. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1235,6 +1235,7 @@ class ServiceContainer {
1235
1235
  services = new Map;
1236
1236
  singletonFactories = new Map;
1237
1237
  bindings = new Map;
1238
+ resolutionPath = [];
1238
1239
  set(key, value) {
1239
1240
  this.singletonFactories.delete(key);
1240
1241
  this.bindings.delete(key);
@@ -1257,16 +1258,27 @@ class ServiceContainer {
1257
1258
  }
1258
1259
  const singletonFactory = this.singletonFactories.get(key);
1259
1260
  if (singletonFactory) {
1260
- const value = singletonFactory(this);
1261
+ const value = this.resolveFactory(key, singletonFactory);
1261
1262
  this.services.set(key, value);
1262
1263
  return value;
1263
1264
  }
1264
1265
  const binding = this.bindings.get(key);
1265
1266
  if (binding) {
1266
- return binding(this);
1267
+ return this.resolveFactory(key, binding);
1267
1268
  }
1268
1269
  throw new Error(`Service "${key}" is not registered.`);
1269
1270
  }
1271
+ resolveFactory(key, factory) {
1272
+ if (this.resolutionPath.includes(key)) {
1273
+ throw new Error(`Circular service dependency: ${[...this.resolutionPath, key].join(" -> ")}.`);
1274
+ }
1275
+ this.resolutionPath.push(key);
1276
+ try {
1277
+ return factory(this);
1278
+ } finally {
1279
+ this.resolutionPath.pop();
1280
+ }
1281
+ }
1270
1282
  resolve(key) {
1271
1283
  return this.get(key);
1272
1284
  }
@@ -2504,6 +2516,64 @@ function assertOrganizationReadable(organizationId) {
2504
2516
  throw new NotFoundError(`Organization ${organizationId} not found.`);
2505
2517
  }
2506
2518
  }
2519
+ // ../../src/core/auth/membershipServiceImplementation.ts
2520
+ class MembershipService {
2521
+ members;
2522
+ constructor(members = resolveMembershipLookup()) {
2523
+ this.members = members;
2524
+ }
2525
+ async listOrganizationIdsForUser(userId) {
2526
+ const memberships = await this.members.listForUser(userId);
2527
+ return memberships.map((membership) => membership.organization_id);
2528
+ }
2529
+ async getOrgRole(userId, organizationId) {
2530
+ const membership = await this.members.findMembership(userId, organizationId);
2531
+ return membership?.role ?? null;
2532
+ }
2533
+ async requireOrgAccess(organizationId, minimumRole = "member", user = currentAuthUser()) {
2534
+ if (!user) {
2535
+ throw new ForbiddenError("Authentication required.");
2536
+ }
2537
+ if (isGlobalAdmin(user)) {
2538
+ return "owner";
2539
+ }
2540
+ const role = await this.getOrgRole(resolveUserId(user), organizationId);
2541
+ if (!role || !hasMinimumOrgRole(role, minimumRole)) {
2542
+ throw new ForbiddenError("Organization membership required.");
2543
+ }
2544
+ return role;
2545
+ }
2546
+ async filterAccessibleOrganizationIds(organizationIds, user = currentAuthUser()) {
2547
+ if (!user) {
2548
+ return [];
2549
+ }
2550
+ if (isGlobalAdmin(user)) {
2551
+ return organizationIds;
2552
+ }
2553
+ const allowed = new Set(await this.listOrganizationIdsForUser(resolveUserId(user)));
2554
+ return organizationIds.filter((organizationId) => allowed.has(organizationId));
2555
+ }
2556
+ async addOwnerOnOrganizationCreate(organizationId, userId) {
2557
+ await this.members.addMember({
2558
+ organizationId,
2559
+ userId,
2560
+ role: "owner"
2561
+ });
2562
+ }
2563
+ listMembersForOrganization(organizationId) {
2564
+ return this.members.listForOrganization(organizationId);
2565
+ }
2566
+ addMember(input) {
2567
+ return this.members.addMember(input);
2568
+ }
2569
+ removeMember(organizationId, userId) {
2570
+ return this.members.removeMember(organizationId, userId);
2571
+ }
2572
+ updateMemberRole(organizationId, userId, role) {
2573
+ return this.members.updateMemberRole(organizationId, userId, role);
2574
+ }
2575
+ }
2576
+ var membershipServiceImplementation_default = MembershipService;
2507
2577
  // ../../src/core/contracts/di.ts
2508
2578
  function getRequiredDependency(dependencies, key) {
2509
2579
  const dependency = dependencies[key];
@@ -2611,67 +2681,8 @@ function resolveMembershipService() {
2611
2681
  if (dependencies.container.has("core.membership")) {
2612
2682
  return dependencies.container.resolve("core.membership");
2613
2683
  }
2614
- return new membershipService_default;
2615
- }
2616
-
2617
- // ../../src/core/auth/membershipService.ts
2618
- class MembershipService {
2619
- members;
2620
- constructor(members = resolveMembershipLookup()) {
2621
- this.members = members;
2622
- }
2623
- async listOrganizationIdsForUser(userId) {
2624
- const memberships = await this.members.listForUser(userId);
2625
- return memberships.map((membership) => membership.organization_id);
2626
- }
2627
- async getOrgRole(userId, organizationId) {
2628
- const membership = await this.members.findMembership(userId, organizationId);
2629
- return membership?.role ?? null;
2630
- }
2631
- async requireOrgAccess(organizationId, minimumRole = "member", user = currentAuthUser()) {
2632
- if (!user) {
2633
- throw new ForbiddenError("Authentication required.");
2634
- }
2635
- if (isGlobalAdmin(user)) {
2636
- return "owner";
2637
- }
2638
- const role = await this.getOrgRole(resolveUserId(user), organizationId);
2639
- if (!role || !hasMinimumOrgRole(role, minimumRole)) {
2640
- throw new ForbiddenError("Organization membership required.");
2641
- }
2642
- return role;
2643
- }
2644
- async filterAccessibleOrganizationIds(organizationIds, user = currentAuthUser()) {
2645
- if (!user) {
2646
- return [];
2647
- }
2648
- if (isGlobalAdmin(user)) {
2649
- return organizationIds;
2650
- }
2651
- const allowed = new Set(await this.listOrganizationIdsForUser(resolveUserId(user)));
2652
- return organizationIds.filter((organizationId) => allowed.has(organizationId));
2653
- }
2654
- async addOwnerOnOrganizationCreate(organizationId, userId) {
2655
- await this.members.addMember({
2656
- organizationId,
2657
- userId,
2658
- role: "owner"
2659
- });
2660
- }
2661
- listMembersForOrganization(organizationId) {
2662
- return this.members.listForOrganization(organizationId);
2663
- }
2664
- addMember(input) {
2665
- return this.members.addMember(input);
2666
- }
2667
- removeMember(organizationId, userId) {
2668
- return this.members.removeMember(organizationId, userId);
2669
- }
2670
- updateMemberRole(organizationId, userId, role) {
2671
- return this.members.updateMemberRole(organizationId, userId, role);
2672
- }
2684
+ return new membershipServiceImplementation_default;
2673
2685
  }
2674
- var membershipService_default = MembershipService;
2675
2686
  // ../../src/core/auth/oauth/oidcProvider.ts
2676
2687
  import { createHash as createHash2, randomBytes as randomBytes3 } from "crypto";
2677
2688
 
@@ -4492,6 +4503,33 @@ function buildConditionalWriteQuery(table, operation, changes, options, returnin
4492
4503
  };
4493
4504
  }
4494
4505
 
4506
+ // ../../src/core/database/relationQueries.ts
4507
+ init_dialect();
4508
+ function buildThroughWhere(table, options, parentIds) {
4509
+ const parameters = [...parentIds];
4510
+ const { clause } = buildQueryWhereClause(table, options, options.whereNodes, parameters);
4511
+ return {
4512
+ text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
4513
+ params: parameters.slice(parentIds.length)
4514
+ };
4515
+ }
4516
+ function buildHasManyThroughQuery(table, relation, parentIds, options) {
4517
+ const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
4518
+ const farTable = table.name;
4519
+ const columns = table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
4520
+ const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
4521
+ const { text: extraWhere, params: extraParams } = buildThroughWhere(table, options, parentIds);
4522
+ const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
4523
+ return { text: sql, params: [...parentIds, ...extraParams] };
4524
+ }
4525
+ function buildPivotLookupQuery(relation, parentIds) {
4526
+ const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
4527
+ return {
4528
+ text: `SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} IN (${placeholders})`,
4529
+ params: parentIds
4530
+ };
4531
+ }
4532
+
4495
4533
  // ../../src/core/database/relationships.ts
4496
4534
  function hasMany(definition) {
4497
4535
  return {
@@ -5700,6 +5738,9 @@ class BaseRepository {
5700
5738
  return order.direction;
5701
5739
  }
5702
5740
  withConnection(connection) {
5741
+ return this.cloneWithConnection(connection);
5742
+ }
5743
+ cloneWithConnection(connection) {
5703
5744
  const clone = Object.create(Object.getPrototypeOf(this));
5704
5745
  Object.assign(clone, this);
5705
5746
  clone.connection = connection;
@@ -5795,26 +5836,10 @@ class BaseRepository {
5795
5836
  throw new Error("A related model scope joins the through table twice; use an explicitly aliased correlated predicate instead.");
5796
5837
  }
5797
5838
  const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
5798
- const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
5799
- const farTable = this.table.name;
5800
- const columns = this.table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
5801
- const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
5802
- const { text: extraWhere, params: extraParams } = this.buildThroughWhere(options, parentIds);
5803
- const sql = `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${throughParentKey} FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(relation.throughTable)} ON ${qualifyColumn(relation.throughTable, relation.secondLocalKey)} = ${qualifyColumn(farTable, relation.secondKey)}${buildJoinClause(options.joins)} WHERE ${qualifyColumn(relation.throughTable, relation.firstKey)} IN (${placeholders})${extraWhere}`;
5804
- const children = await this.connection.unsafe(sql, [
5805
- ...parentIds,
5806
- ...extraParams
5807
- ]);
5839
+ const { text, params } = buildHasManyThroughQuery(this.table, relation, parentIds, options);
5840
+ const children = await this.connection.unsafe(text, params);
5808
5841
  return indexHasManyThroughRelation(parents, children, relation);
5809
5842
  }
5810
- buildThroughWhere(options, parentIds) {
5811
- const parameters = [...parentIds];
5812
- const { clause } = buildQueryWhereClause(this.table, options, options.whereNodes, parameters);
5813
- return {
5814
- text: clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "",
5815
- params: parameters.slice(parentIds.length)
5816
- };
5817
- }
5818
5843
  async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
5819
5844
  if (children.length === 0) {
5820
5845
  return new Map;
@@ -5880,8 +5905,8 @@ class BaseRepository {
5880
5905
  return indexBelongsToManyRelation(parents, [], [], relation);
5881
5906
  }
5882
5907
  const parentIds = [...new Set(parents.map((parent) => parent[relation.parentKey]))];
5883
- const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
5884
- const pivotRows = await this.connection.unsafe(`SELECT * FROM ${relation.pivotTable} WHERE ${String(relation.foreignPivotKey)} IN (${placeholders})`, parentIds);
5908
+ const { text, params } = buildPivotLookupQuery(relation, parentIds);
5909
+ const pivotRows = await this.connection.unsafe(text, params);
5885
5910
  if (pivotRows.length === 0) {
5886
5911
  return indexBelongsToManyRelation(parents, [], [], relation);
5887
5912
  }
@@ -5976,6 +6001,8 @@ function createTokenAbilityChecker() {
5976
6001
  }
5977
6002
  // ../../src/core/cache/redisCacheStore.ts
5978
6003
  var {RedisClient } = globalThis.Bun;
6004
+
6005
+ // ../../src/core/cache/redisCacheScript.ts
5979
6006
  var CACHE_SCRIPT = `
5980
6007
  local expected = {'hash', 'zset', 'zset', 'hash', 'zset'}
5981
6008
  for i, key in ipairs(KEYS) do
@@ -6175,6 +6202,7 @@ end
6175
6202
  return redis.error_reply('Unknown cache operation')
6176
6203
  `;
6177
6204
 
6205
+ // ../../src/core/cache/redisCacheStore.ts
6178
6206
  class RedisCacheStore {
6179
6207
  redisUrl;
6180
6208
  ttlMs;
@@ -8022,563 +8050,766 @@ async function freshDatabase(db, migrations, options = {}) {
8022
8050
  await runFresh();
8023
8051
  }
8024
8052
  // ../../src/core/database/model.ts
8025
- import { isDeepStrictEqual } from "util";
8026
8053
  init_deferredModelEvents();
8027
8054
 
8028
- // ../../src/core/database/relationQuery.ts
8029
- init_boundConnection();
8030
- init_connectionContext();
8031
- init_defaultConnection();
8032
- init_dialect();
8033
- init_repositoryConnection();
8034
- init_transaction();
8035
- function asWhere(where) {
8036
- return where;
8037
- }
8038
- function ownerId(owner, ownerKey) {
8039
- if (typeof owner.get === "function") {
8040
- return owner.get(ownerKey);
8041
- }
8042
- if (owner && typeof owner === "object" && "id" in owner && owner.id !== undefined) {
8043
- return owner.id;
8044
- }
8045
- throw new Error("belongsTo.associate() requires a related model or { id }.");
8046
- }
8047
- function thenGet(get, onfulfilled, onrejected) {
8048
- return get().then(onfulfilled ?? undefined, onrejected ?? undefined);
8049
- }
8050
- function pluckFromQuery(query, column, keyBy) {
8051
- if (!query) {
8052
- return Promise.resolve(keyBy === undefined ? [] : new Map);
8053
- }
8054
- return keyBy === undefined ? query.pluck(column) : query.pluck(column, keyBy);
8055
- }
8056
- function scopedRelatedQuery(model, repository = model.repository()) {
8057
- const query = repository.query();
8058
- const scopedModel = model;
8059
- return scopedModel.scopeQuery?.(query) ?? query;
8055
+ // ../../src/core/database/modelAttributes.ts
8056
+ import { isDeepStrictEqual } from "util";
8057
+ function snapshotAttributes(values) {
8058
+ return Object.fromEntries(Object.entries(values).map(([key, value]) => [
8059
+ key,
8060
+ Buffer.isBuffer(value) ? Buffer.from(value) : structuredClone(value)
8061
+ ]));
8060
8062
  }
8061
- function relatedOptions(model, filters, options = {}) {
8062
- const query = scopedRelatedQuery(model);
8063
- for (const filter of filters)
8064
- query.where(filter);
8065
- return { ...query.getOptions(), ...options };
8063
+ function changedAttributes(values, original) {
8064
+ return Object.fromEntries(Object.entries(values).filter(([key, value]) => !(key in original) || !isDeepStrictEqual(value, original[key])));
8066
8065
  }
8067
- function relatedRead(model, connection, binding, filters, options = {}) {
8068
- const query = scopedRelatedQuery(model, model.repository().withConnection(connection));
8069
- query.where(binding).protectWhere();
8070
- for (const filter of filters)
8071
- query.where(filter);
8072
- if (options.orderBy)
8073
- query.orderBy(options.orderBy);
8074
- if (options.limit !== undefined)
8075
- query.limit(options.limit);
8076
- return query;
8066
+ var PASSWORD_HASH_PATTERN = /^\$(?:2[aby]?|argon2(?:i|d|id)?)\$/;
8067
+ function isAlreadyHashed(value) {
8068
+ return PASSWORD_HASH_PATTERN.test(value);
8077
8069
  }
8078
- function relatedConditions(model, filters, options = {}, parameters = [], reservedTables = []) {
8079
- const compiled = relatedOptions(model, filters, options);
8080
- if (compiled.joins?.some((join) => reservedTables.includes(join.table))) {
8081
- throw new Error("A related model scope joins a reserved relation table; use an explicitly aliased correlated predicate instead.");
8070
+ async function hashCastValue(value) {
8071
+ if (value === null || value === undefined)
8072
+ return value;
8073
+ const plain = String(value);
8074
+ if (isAlreadyHashed(plain)) {
8075
+ return plain;
8082
8076
  }
8083
- const extra = buildQueryWhereClause(model.repository().getTable(), compiled, compiled.whereNodes, parameters);
8084
- const predicate = extra.clause.replace(/^ WHERE /, "");
8085
- return {
8086
- sql: predicate ? ` AND (${predicate})` : "",
8087
- joins: buildJoinClause(compiled.joins),
8088
- params: extra.params
8089
- };
8077
+ return await hashPassword(plain);
8090
8078
  }
8091
-
8092
- class HasManyRelationQuery {
8093
- parent;
8094
- related;
8095
- relation;
8096
- kind = "hasMany";
8097
- extraWhere = [];
8098
- extraOptions = {};
8099
- constructor(parent, related, relation) {
8100
- this.parent = parent;
8101
- this.related = related;
8102
- this.relation = relation;
8079
+ function hydrateValue(value, cast) {
8080
+ if (value === null || value === undefined) {
8081
+ return value;
8103
8082
  }
8104
- where(where) {
8105
- this.extraWhere.push({ ...where });
8106
- return this;
8083
+ switch (cast) {
8084
+ case "date":
8085
+ case "datetime":
8086
+ return value instanceof Date ? value : new Date(String(value));
8087
+ case "json":
8088
+ return typeof value === "string" ? JSON.parse(value) : value;
8089
+ case "bool":
8090
+ case "boolean":
8091
+ return value === true || value === 1 || value === "1" || value === "true";
8092
+ case "integer":
8093
+ case "int":
8094
+ return value === "" ? null : Number(value);
8095
+ case "hashed":
8096
+ return value;
8097
+ default:
8098
+ return value;
8107
8099
  }
8108
- orderBy(orderBy) {
8109
- this.extraOptions = { ...this.extraOptions, orderBy };
8110
- return this;
8100
+ }
8101
+ function dehydrateValue(value, cast) {
8102
+ if (cast === "hashed")
8103
+ return hashCastValue(value);
8104
+ if (value === null || value === undefined) {
8105
+ return value;
8111
8106
  }
8112
- limit(limit) {
8113
- this.extraOptions = { ...this.extraOptions, limit };
8114
- return this;
8115
- }
8116
- applyEagerLoad(query, alias) {
8117
- query.withHasMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
8107
+ switch (cast) {
8108
+ case "date":
8109
+ case "datetime":
8110
+ return value instanceof Date ? value : new Date(String(value));
8111
+ case "json":
8112
+ return typeof value === "string" ? value : JSON.stringify(value);
8113
+ case "bool":
8114
+ case "boolean":
8115
+ return Boolean(value);
8116
+ case "integer":
8117
+ case "int":
8118
+ return value === "" ? null : Number(value);
8119
+ default:
8120
+ return value;
8118
8121
  }
8119
- hydrateEager(row, alias) {
8120
- const value = row[alias] ?? [];
8121
- const rows = Array.isArray(value) ? value : [];
8122
- return rows.map((item) => this.related.newFromRecord(item));
8122
+ }
8123
+ function filterMassAssignable(fillable, guarded, input) {
8124
+ if (fillable === undefined && guarded === undefined && Object.keys(input).length > 0) {
8125
+ throw new Error("Mass assignment is not configured for this model. Declare static $fillable = [...] to allow specific columns, or static $guarded = [] to allow all of them.");
8123
8126
  }
8124
- toExistsClause(parentTable) {
8125
- const childTable = this.related.repository().getTable().name;
8126
- const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable]);
8127
- const sql = `SELECT 1 FROM ${quoteIdentifier(childTable)}${extra.joins} WHERE ${qualifyColumn(childTable, this.relation.foreignKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
8128
- return { sql, params: extra.params };
8127
+ const resolvedGuarded = guarded ?? true;
8128
+ if (fillable && fillable.length > 0) {
8129
+ const allowed = new Set(fillable);
8130
+ return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
8129
8131
  }
8130
- scopedQuery() {
8131
- return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({ [this.relation.foreignKey]: this.parent.get(this.relation.localKey) }), this.extraWhere, this.extraOptions);
8132
+ if (resolvedGuarded === true || resolvedGuarded.includes("*")) {
8133
+ return {};
8132
8134
  }
8133
- async get() {
8134
- const rows = await this.scopedQuery().get();
8135
- return rows.map((row) => this.related.newFromRecord(row));
8135
+ const blocked = new Set(resolvedGuarded);
8136
+ return Object.fromEntries(Object.entries(input).filter(([key]) => !blocked.has(key)));
8137
+ }
8138
+ function applyCasts(values, casts, direction) {
8139
+ const entries = Object.entries(casts);
8140
+ if (entries.length === 0) {
8141
+ return direction === "hydrate" ? values : Promise.resolve(values);
8136
8142
  }
8137
- async first() {
8138
- const rows = await this.limit(1).get();
8139
- return rows[0] ?? null;
8143
+ const result = { ...values };
8144
+ if (direction === "hydrate") {
8145
+ for (const [key, cast] of entries) {
8146
+ if (key in result && cast)
8147
+ result[key] = hydrateValue(result[key], cast);
8148
+ }
8149
+ return result;
8140
8150
  }
8141
- async count() {
8142
- return this.scopedQuery().count();
8151
+ return (async () => {
8152
+ const hashes = [];
8153
+ for (const [key, cast] of entries) {
8154
+ if (!(key in result) || !cast)
8155
+ continue;
8156
+ if (cast === "hashed") {
8157
+ const current = result[key];
8158
+ hashes.push(hashCastValue(current).then((hashed) => {
8159
+ result[key] = hashed;
8160
+ }));
8161
+ continue;
8162
+ }
8163
+ result[key] = dehydrateValue(result[key], cast);
8164
+ }
8165
+ await Promise.all(hashes);
8166
+ return result;
8167
+ })();
8168
+ }
8169
+ function applyTimestampsOnCreate(columns, values, enabled) {
8170
+ if (!enabled) {
8171
+ return values;
8143
8172
  }
8144
- async pluck(column, keyBy) {
8145
- return pluckFromQuery(this.scopedQuery(), column, keyBy);
8173
+ const now = new Date;
8174
+ const result = { ...values };
8175
+ if (columns.includes("created_at")) {
8176
+ result.created_at = now;
8146
8177
  }
8147
- async value(column) {
8148
- return this.scopedQuery().value(column);
8178
+ if (columns.includes("updated_at")) {
8179
+ result.updated_at = now;
8149
8180
  }
8150
- then(onfulfilled, onrejected) {
8151
- return thenGet(() => this.get(), onfulfilled, onrejected);
8181
+ return result;
8182
+ }
8183
+ function applyTimestampsOnUpdate(columns, values, enabled) {
8184
+ if (!enabled) {
8185
+ return values;
8152
8186
  }
8153
- async create(attributes = {}) {
8154
- return this.related.create(attributes, {
8155
- [this.relation.foreignKey]: this.parent.get(this.relation.localKey)
8156
- });
8187
+ const result = { ...values };
8188
+ if (columns.includes("updated_at")) {
8189
+ result.updated_at = new Date;
8157
8190
  }
8158
- async save(related) {
8159
- const forced = {
8160
- [this.relation.foreignKey]: this.parent.get(this.relation.localKey)
8161
- };
8162
- const savable = related;
8163
- if (typeof savable.save === "function") {
8164
- savable.mergeAttributes?.(forced);
8165
- await savable.save();
8166
- return related;
8191
+ return result;
8192
+ }
8193
+
8194
+ // ../../src/core/database/modelRegistry.ts
8195
+ var modelGlobalScopes = new WeakMap;
8196
+ var modelBooted = new WeakSet;
8197
+ var modelRepositories = new WeakMap;
8198
+ var modelRepositoryFactories = new WeakMap;
8199
+ var namedModels = new Map;
8200
+ var modelObservers = new WeakMap;
8201
+ async function runObservers(model, hook) {
8202
+ const observers = modelObservers.get(model.constructor) ?? [];
8203
+ for (const observer of observers) {
8204
+ const handler = observer[hook];
8205
+ if (handler && await handler(model) === false) {
8206
+ return false;
8167
8207
  }
8168
- return this.create(related);
8169
8208
  }
8170
- async createMany(records) {
8171
- return Promise.all(records.map((attributes) => this.create(attributes)));
8209
+ return true;
8210
+ }
8211
+ function nameModel(model) {
8212
+ const { name, $morphClass } = model;
8213
+ if (name)
8214
+ namedModels.set(name, model);
8215
+ if ($morphClass)
8216
+ namedModels.set($morphClass, model);
8217
+ }
8218
+ function resolveModelRepository(model) {
8219
+ const existing = modelRepositories.get(model);
8220
+ if (existing)
8221
+ return existing;
8222
+ for (let current = model;current; current = Object.getPrototypeOf(current)) {
8223
+ const factory = modelRepositoryFactories.get(current);
8224
+ if (!factory)
8225
+ continue;
8226
+ const repository = factory();
8227
+ modelRepositories.set(model, repository);
8228
+ nameModel(model);
8229
+ return repository;
8172
8230
  }
8231
+ throw new Error(`${model.name}.repository() is not implemented.`);
8173
8232
  }
8174
-
8175
- class HasOneRelationQuery {
8176
- relation;
8177
- kind = "hasOne";
8178
- inner;
8179
- constructor(parent, related, relation) {
8180
- this.relation = relation;
8181
- this.inner = new HasManyRelationQuery(parent, related, {
8182
- type: "hasMany",
8183
- name: relation.name,
8184
- localKey: relation.localKey,
8185
- foreignKey: relation.foreignKey
8186
- });
8233
+ function registerModelClass(name, model) {
8234
+ namedModels.set(name, model);
8235
+ }
8236
+ function registerModelRepositoryFactory(model, factory) {
8237
+ modelRepositoryFactories.set(model, factory);
8238
+ }
8239
+ function bindModelRepository(model, repository) {
8240
+ modelRepositories.set(model, repository);
8241
+ }
8242
+ function findNamedModel(name) {
8243
+ return namedModels.get(name);
8244
+ }
8245
+ function getModelObservers(model) {
8246
+ return modelObservers.get(model);
8247
+ }
8248
+ function restoreModelObservers(model, observers) {
8249
+ if (observers)
8250
+ modelObservers.set(model, observers);
8251
+ else
8252
+ modelObservers.delete(model);
8253
+ }
8254
+ function observeModel(model, observer) {
8255
+ const existing = modelObservers.get(model) ?? [];
8256
+ modelObservers.set(model, [...existing, observer]);
8257
+ }
8258
+ function ensureBooted(model) {
8259
+ if (modelBooted.has(model)) {
8260
+ return;
8187
8261
  }
8188
- where(where) {
8189
- this.inner.where(where);
8190
- return this;
8262
+ nameModel(model);
8263
+ modelBooted.add(model);
8264
+ const scopes = modelGlobalScopes.get(model);
8265
+ const observers = getModelObservers(model);
8266
+ const boot = model.boot;
8267
+ if (typeof boot === "function") {
8268
+ try {
8269
+ boot.call(model);
8270
+ } catch (error) {
8271
+ modelBooted.delete(model);
8272
+ if (scopes)
8273
+ modelGlobalScopes.set(model, scopes);
8274
+ else
8275
+ modelGlobalScopes.delete(model);
8276
+ restoreModelObservers(model, observers);
8277
+ throw error;
8278
+ }
8191
8279
  }
8192
- orderBy(orderBy) {
8193
- this.inner.orderBy(orderBy);
8194
- return this;
8280
+ }
8281
+ function getGlobalScopes(model) {
8282
+ return modelGlobalScopes.get(model) ?? [];
8283
+ }
8284
+ function addModelGlobalScope(model, scope) {
8285
+ ensureBooted(model);
8286
+ const existing = modelGlobalScopes.get(model) ?? [];
8287
+ modelGlobalScopes.set(model, [
8288
+ ...existing,
8289
+ scope
8290
+ ]);
8291
+ }
8292
+
8293
+ // ../../src/core/database/modelQuery.ts
8294
+ function modelStatics(model) {
8295
+ return model;
8296
+ }
8297
+ function flattenRelationNames(relations) {
8298
+ const names = [];
8299
+ for (const item of relations) {
8300
+ if (typeof item === "string") {
8301
+ if (item.length > 0) {
8302
+ names.push(item);
8303
+ }
8304
+ continue;
8305
+ }
8306
+ if (Array.isArray(item)) {
8307
+ for (const nested of item) {
8308
+ if (typeof nested === "string" && nested.length > 0) {
8309
+ names.push(nested);
8310
+ }
8311
+ }
8312
+ }
8195
8313
  }
8196
- applyEagerLoad(query, alias) {
8197
- this.inner.applyEagerLoad(query, alias);
8314
+ return names;
8315
+ }
8316
+ function isLoadableModel(value) {
8317
+ return Boolean(value && typeof value === "object" && typeof value.load === "function" && typeof value.loaded === "function" && typeof value.setLoaded === "function");
8318
+ }
8319
+ async function eagerLoadOnModels(models, paths) {
8320
+ if (models.length === 0 || paths.length === 0) {
8321
+ return;
8198
8322
  }
8199
- hydrateEager(row, alias) {
8200
- const hydrated = this.inner.hydrateEager(row, alias);
8201
- return hydrated[0];
8323
+ const grouped = new Map;
8324
+ for (const path of paths) {
8325
+ const [head, ...rest] = path.split(".");
8326
+ if (!head) {
8327
+ continue;
8328
+ }
8329
+ const nested = rest.join(".");
8330
+ const existing = grouped.get(head) ?? [];
8331
+ if (nested) {
8332
+ existing.push(nested);
8333
+ }
8334
+ grouped.set(head, existing);
8202
8335
  }
8203
- toExistsClause(parentTable) {
8204
- return this.inner.toExistsClause(parentTable);
8336
+ await Promise.all([...grouped.entries()].map(async ([head, nested]) => {
8337
+ const unloaded = models.filter((model) => model.loaded(head) === undefined);
8338
+ if (unloaded.length > 0) {
8339
+ const first = unloaded[0];
8340
+ if (!first) {
8341
+ return;
8342
+ }
8343
+ const method = first[head];
8344
+ if (typeof method !== "function") {
8345
+ throw new Error(`${first.constructor.name} has no relation method ${head}().`);
8346
+ }
8347
+ const relationQuery = method.call(first);
8348
+ const query = first.getRepository().query();
8349
+ relationQuery.applyEagerLoad(query, head);
8350
+ const attached = await query.attachToRows(unloaded.map((model) => model.toObject()));
8351
+ for (const [index, model] of unloaded.entries()) {
8352
+ const row = attached[index] ?? model.toObject();
8353
+ model.setLoaded(head, relationQuery.hydrateEager(row, head));
8354
+ }
8355
+ }
8356
+ if (nested.length === 0) {
8357
+ return;
8358
+ }
8359
+ const children = models.flatMap((model) => {
8360
+ const loaded = model.loaded(head);
8361
+ return Array.isArray(loaded) ? loaded : loaded ? [loaded] : [];
8362
+ });
8363
+ await eagerLoadOnModels(children.filter(isLoadableModel), nested);
8364
+ }));
8365
+ }
8366
+ async function loadNested(model, path) {
8367
+ await eagerLoadOnModels([model], [path]);
8368
+ }
8369
+ function castPluckedValue(modelClass, column, value) {
8370
+ const cast = modelStatics(modelClass).$casts?.[column];
8371
+ return cast ? hydrateValue(value, cast) : value;
8372
+ }
8373
+
8374
+ class ModelProjection {
8375
+ load;
8376
+ page;
8377
+ constructor(load, page) {
8378
+ this.load = load;
8379
+ this.page = page;
8205
8380
  }
8206
- async get() {
8207
- return this.inner.limit(1).first();
8381
+ keysetPaginate(options) {
8382
+ return this.page(options);
8383
+ }
8384
+ get() {
8385
+ return this.load();
8208
8386
  }
8209
8387
  async first() {
8210
- return this.get();
8388
+ return (await this.load(1))[0] ?? null;
8211
8389
  }
8212
- async count() {
8213
- return this.inner.count();
8390
+ }
8391
+
8392
+ class ModelQuery {
8393
+ modelClass;
8394
+ query;
8395
+ eager = [];
8396
+ constructor(modelClass, query) {
8397
+ this.modelClass = modelClass;
8398
+ this.query = query;
8214
8399
  }
8215
- async pluck(column, keyBy) {
8216
- const query = this.inner.limit(1);
8217
- return keyBy === undefined ? query.pluck(column) : query.pluck(column, keyBy);
8400
+ with(...relations) {
8401
+ const statics = modelStatics(this.modelClass);
8402
+ ensureBooted(this.modelClass);
8403
+ const dummy = statics.newFromRecord({}, false);
8404
+ for (const path of flattenRelationNames(relations)) {
8405
+ const name = path.split(".")[0] ?? path;
8406
+ const method = dummy[name];
8407
+ if (typeof method !== "function") {
8408
+ throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
8409
+ }
8410
+ const relationQuery = method.call(dummy);
8411
+ this.eager.push({ name, path, relationQuery });
8412
+ relationQuery.applyEagerLoad(this.query, name);
8413
+ }
8414
+ return this;
8218
8415
  }
8219
- async value(column) {
8220
- return this.inner.limit(1).value(column);
8416
+ where(input) {
8417
+ this.query.where(input);
8418
+ return this;
8221
8419
  }
8222
- then(onfulfilled, onrejected) {
8223
- return thenGet(() => this.get(), onfulfilled, onrejected);
8420
+ orWhere(input) {
8421
+ this.query.orWhere(input);
8422
+ return this;
8224
8423
  }
8225
- async create(attributes = {}) {
8226
- return this.inner.create(attributes);
8424
+ whereDynamic(input) {
8425
+ this.query.where(input);
8426
+ return this;
8227
8427
  }
8228
- async save(related) {
8229
- return this.inner.save(related);
8428
+ select(...columns) {
8429
+ return new ModelProjection(async (limit) => {
8430
+ const rows = await this.query.project(columns, limit);
8431
+ return rows.map((row) => applyCasts(row, modelStatics(this.modelClass).$casts, "hydrate"));
8432
+ }, async (options) => {
8433
+ const page = await this.query.projectKeyset(columns, options);
8434
+ return {
8435
+ ...page,
8436
+ data: page.data.map((row) => applyCasts(row, modelStatics(this.modelClass).$casts, "hydrate"))
8437
+ };
8438
+ });
8230
8439
  }
8231
- }
8232
-
8233
- class BelongsToRelationQuery {
8234
- parent;
8235
- related;
8236
- relation;
8237
- kind = "belongsTo";
8238
- extraWhere = [];
8239
- extraOptions = {};
8240
- constructor(parent, related, relation) {
8241
- this.parent = parent;
8242
- this.related = related;
8243
- this.relation = relation;
8440
+ lockForUpdate(options = {}) {
8441
+ this.query.lockForUpdate(options);
8442
+ return this;
8244
8443
  }
8245
- where(where) {
8246
- this.extraWhere.push({ ...where });
8444
+ sharedLock(options = {}) {
8445
+ this.query.sharedLock(options);
8247
8446
  return this;
8248
8447
  }
8249
8448
  orderBy(orderBy) {
8250
- this.extraOptions = { ...this.extraOptions, orderBy };
8449
+ this.query.orderBy(orderBy);
8251
8450
  return this;
8252
8451
  }
8253
- applyEagerLoad(query, alias) {
8254
- query.withBelongsTo(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
8255
- }
8256
- hydrateEager(row, alias) {
8257
- const value = row[alias];
8258
- return value ? this.related.newFromRecord(value) : value;
8259
- }
8260
- toExistsClause(parentTable) {
8261
- const relatedTable = this.related.repository().getTable().name;
8262
- const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable]);
8263
- const sql = `SELECT 1 FROM ${quoteIdentifier(relatedTable)}${extra.joins} WHERE ${qualifyColumn(relatedTable, this.relation.ownerKey)} = ${qualifyColumn(parentTable, this.relation.foreignKey)}${extra.sql}`;
8264
- return { sql, params: extra.params };
8452
+ limit(limit) {
8453
+ this.query.limit(limit);
8454
+ return this;
8265
8455
  }
8266
- async get() {
8267
- const query = this.relatedQuery();
8268
- if (!query) {
8269
- return null;
8270
- }
8271
- const row = await query.first();
8272
- return row ? this.related.newFromRecord(row) : null;
8456
+ offset(offset) {
8457
+ this.query.offset(offset);
8458
+ return this;
8273
8459
  }
8274
- async first() {
8275
- return this.get();
8460
+ whereNull(column) {
8461
+ this.query.whereNull(column);
8462
+ return this;
8276
8463
  }
8277
- async pluck(column, keyBy) {
8278
- return pluckFromQuery(this.relatedQuery(), column, keyBy);
8464
+ whereNotNull(column) {
8465
+ this.query.whereNotNull(column);
8466
+ return this;
8279
8467
  }
8280
- async value(column) {
8281
- return this.relatedQuery()?.value(column) ?? null;
8468
+ whereIn(column, values) {
8469
+ this.query.whereIn(column, values);
8470
+ return this;
8282
8471
  }
8283
- relatedQuery() {
8284
- const foreign = this.parent.get(this.relation.foreignKey);
8285
- if (foreign === null || foreign === undefined) {
8286
- return null;
8287
- }
8288
- return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({ [this.relation.ownerKey]: foreign }), this.extraWhere, this.extraOptions);
8472
+ whereNotIn(column, values) {
8473
+ this.query.whereNotIn(column, values);
8474
+ return this;
8289
8475
  }
8290
- then(onfulfilled, onrejected) {
8291
- return thenGet(() => this.get(), onfulfilled, onrejected);
8476
+ groupBy(groupBy) {
8477
+ this.query.groupBy(groupBy);
8478
+ return this;
8292
8479
  }
8293
- async associate(owner) {
8294
- await this.parent.getRepository().updateById(this.parent.id, {
8295
- [this.relation.foreignKey]: ownerId(owner, this.relation.ownerKey)
8296
- });
8480
+ having(having) {
8481
+ this.query.having(having);
8482
+ return this;
8297
8483
  }
8298
- async dissociate() {
8299
- await this.parent.getRepository().updateById(this.parent.id, {
8300
- [this.relation.foreignKey]: null
8301
- });
8484
+ join(left, right) {
8485
+ this.query.join(left, right);
8486
+ return this;
8302
8487
  }
8303
- }
8304
- function pivotIdKey(id) {
8305
- return typeof id === "number" || typeof id === "bigint" ? String(id) : id;
8306
- }
8307
- function hasRepeatedId(ids) {
8308
- const seen = new Set;
8309
- for (const id of ids) {
8310
- const key = pivotIdKey(id);
8311
- if (seen.has(key))
8312
- return true;
8313
- seen.add(key);
8488
+ leftJoin(left, right) {
8489
+ this.query.leftJoin(left, right);
8490
+ return this;
8314
8491
  }
8315
- return false;
8316
- }
8317
- function canBatchPivotToggle(ids) {
8318
- return ids.every((id) => typeof id === "bigint" && id >= BigInt(Number.MIN_SAFE_INTEGER) && id <= BigInt(Number.MAX_SAFE_INTEGER) || typeof id === "number" && Number.isSafeInteger(id) || typeof id === "string" && /^(?:0|-?[1-9]\d*)$/.test(id) && Number.isSafeInteger(Number(id)));
8319
- }
8320
- function isConfiguredConnection(connection) {
8321
- const bound = getBoundDatabaseConnection();
8322
- return connection === repositoryConnection || (bound ? connection === bound : isDefaultDatabaseConnection(connection));
8323
- }
8324
-
8325
- class BelongsToManyRelationQuery {
8326
- parent;
8327
- related;
8328
- relation;
8329
- kind = "belongsToMany";
8330
- extraWhere = [];
8331
- extraOptions = {};
8332
- pivotValues = {};
8333
- constructor(parent, related, relation) {
8334
- this.parent = parent;
8335
- this.related = related;
8336
- this.relation = relation;
8492
+ async paginate(options) {
8493
+ const { data, meta } = await this.query.paginate(options);
8494
+ return { data: await this.hydrateRows(data), meta };
8337
8495
  }
8338
- where(where) {
8339
- this.extraWhere.push({ ...where });
8496
+ whereExists(sql, params = []) {
8497
+ this.query.whereExists(sql, params);
8340
8498
  return this;
8341
8499
  }
8342
- orderBy(orderBy) {
8343
- this.extraOptions = { ...this.extraOptions, orderBy };
8500
+ whereNotExists(sql, params = []) {
8501
+ this.query.whereNotExists(sql, params);
8344
8502
  return this;
8345
8503
  }
8346
- applyEagerLoad(query, alias) {
8347
- query.withBelongsToMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
8504
+ whereHas(name, constrain) {
8505
+ return this.constrainExists(name, constrain, false);
8348
8506
  }
8349
- withPivotValues(values) {
8350
- this.pivotValues = { ...this.pivotValues, ...values };
8351
- return this;
8507
+ has(name) {
8508
+ return this.constrainExists(name, undefined, false);
8352
8509
  }
8353
- hydrateEager(row, alias) {
8354
- const value = row[alias] ?? [];
8355
- const rows = Array.isArray(value) ? value : [];
8356
- return rows.map((item) => this.related.newFromRecord(item));
8357
- }
8358
- toExistsClause(parentTable) {
8359
- const relatedTable = this.related.repository().getTable().name;
8360
- const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable, this.relation.pivotTable]);
8361
- const sql = `SELECT 1 FROM ${quoteIdentifier(relatedTable)} INNER JOIN ${quoteIdentifier(this.relation.pivotTable)} ON ${qualifyColumn(this.relation.pivotTable, this.relation.relatedPivotKey)} = ${qualifyColumn(relatedTable, this.relation.relatedKey)}${extra.joins} WHERE ${qualifyColumn(this.relation.pivotTable, this.relation.foreignPivotKey)} = ${qualifyColumn(parentTable, this.relation.parentKey)}${extra.sql}`;
8362
- return { sql, params: extra.params };
8363
- }
8364
- connection() {
8365
- const connection = this.parent.getRepository().getConnection();
8366
- return isConfiguredConnection(connection) ? getActiveDatabaseConnection(connection) : connection;
8367
- }
8368
- async atomically(work) {
8369
- const connection = this.connection();
8370
- if (isConfiguredConnection(connection) || hasActiveDatabaseConnection() && connection === getActiveDatabaseConnection(connection)) {
8371
- await runInTransaction(work);
8372
- return;
8373
- }
8374
- if (typeof connection.begin !== "function") {
8375
- await work(connection);
8376
- return;
8377
- }
8378
- await connection.begin(work);
8379
- }
8380
- async get() {
8381
- const query = await this.relatedQuery();
8382
- const rows = query ? await query.get() : [];
8383
- return rows.map((row) => this.related.newFromRecord(row));
8384
- }
8385
- async first() {
8386
- const rows = await this.get();
8387
- return rows[0] ?? null;
8388
- }
8389
- async count() {
8390
- const query = await this.relatedQuery();
8391
- return query ? query.count() : 0;
8392
- }
8393
- async pluck(column, keyBy) {
8394
- return pluckFromQuery(await this.relatedQuery(), column, keyBy);
8395
- }
8396
- async value(column) {
8397
- const query = await this.relatedQuery();
8398
- return query ? query.value(column) : null;
8399
- }
8400
- async relatedQuery() {
8401
- const parentId = this.parent.get(this.relation.parentKey);
8402
- const pivotRows = await this.connection().unsafe(`SELECT * FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)}`, [parentId]);
8403
- if (pivotRows.length === 0) {
8404
- return null;
8405
- }
8406
- const relatedIds = [
8407
- ...new Set(pivotRows.map((row) => row[this.relation.relatedPivotKey]))
8408
- ];
8409
- return relatedRead(this.related, this.connection(), asWhere({ [this.relation.relatedKey]: relatedIds }), this.extraWhere, this.extraOptions);
8410
- }
8411
- then(onfulfilled, onrejected) {
8412
- return thenGet(() => this.get(), onfulfilled, onrejected);
8413
- }
8414
- async attach(ids) {
8415
- const list = Array.isArray(ids) ? ids : [ids];
8416
- if (list.length === 0)
8417
- return;
8418
- await this.atomically((connection) => this.insertPivotRows(connection, list));
8419
- }
8420
- async toggle(ids) {
8421
- const list = Array.isArray(ids) ? ids : [ids];
8422
- if (list.length === 0)
8423
- return;
8424
- await this.atomically(async (connection) => {
8425
- if (!canBatchPivotToggle(list) || hasRepeatedId(list)) {
8426
- for (const id of list)
8427
- await this.toggleOne(connection, id);
8428
- return;
8429
- }
8430
- const parentId = this.parent.get(this.relation.parentKey);
8431
- const relatedColumn = quoteIdentifier(String(this.relation.relatedPivotKey));
8432
- const parentColumn = quoteIdentifier(String(this.relation.foreignPivotKey));
8433
- const placeholders = list.map((_, index) => currentSqlDialect().placeholder(index + 2));
8434
- const existing = await connection.unsafe(`SELECT ${relatedColumn} FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${parentColumn} = ${currentSqlDialect().placeholder(1)} AND ${relatedColumn} IN (${placeholders.join(", ")})`, [parentId, ...list]);
8435
- const existingIds = new Set(existing.map((row) => pivotIdKey(row[String(this.relation.relatedPivotKey)])));
8436
- const present = list.filter((id) => existingIds.has(pivotIdKey(id)));
8437
- const missing = list.filter((id) => !existingIds.has(pivotIdKey(id)));
8438
- if (present.length > 0)
8439
- await this.deletePivotRows(connection, present);
8440
- if (missing.length > 0)
8441
- await this.insertPivotRows(connection, missing);
8442
- });
8510
+ doesntHave(name) {
8511
+ return this.constrainExists(name, undefined, true);
8443
8512
  }
8444
- async detach(ids) {
8445
- const parentId = this.parent.get(this.relation.parentKey);
8446
- if (ids === undefined) {
8447
- await this.connection().unsafe(`DELETE FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)}`, [parentId]);
8448
- return;
8449
- }
8450
- const list = Array.isArray(ids) ? ids : [ids];
8451
- if (list.length === 0)
8452
- return;
8453
- await this.deletePivotRows(this.connection(), list);
8513
+ whereDoesntHave(name, constrain) {
8514
+ return this.constrainExists(name, constrain, true);
8454
8515
  }
8455
- async toggleOne(connection, id) {
8456
- const parentId = this.parent.get(this.relation.parentKey);
8457
- const existing = await connection.unsafe(`SELECT 1 FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)} AND ${quoteIdentifier(String(this.relation.relatedPivotKey))} = ${currentSqlDialect().placeholder(2)} LIMIT 1`, [parentId, id]);
8458
- if (existing.length > 0)
8459
- await this.deletePivotRows(connection, [id]);
8460
- else
8461
- await this.insertPivotRows(connection, [id]);
8516
+ withHasMany(...args) {
8517
+ this.query.withHasMany(...args);
8518
+ return this;
8462
8519
  }
8463
- async insertPivotRows(connection, list) {
8464
- const parentId = this.parent.get(this.relation.parentKey);
8465
- const extraKeys = Object.keys(this.pivotValues);
8466
- const extraColumns = extraKeys.length > 0 ? `, ${extraKeys.map((key) => quoteIdentifier(key)).join(", ")}` : "";
8467
- const extraValues = extraKeys.map((key) => this.pivotValues[key]);
8468
- const width = 2 + extraKeys.length;
8469
- const tuples = list.map((_, row) => {
8470
- const slots = Array.from({ length: width }, (__, column) => currentSqlDialect().placeholder(row * width + column + 1));
8471
- return `(${slots.join(", ")})`;
8472
- });
8473
- const params = [];
8474
- for (const id of list)
8475
- params.push(parentId, id, ...extraValues);
8476
- await connection.unsafe(`INSERT INTO ${quoteIdentifier(this.relation.pivotTable)} (${quoteIdentifier(String(this.relation.foreignPivotKey))}, ${quoteIdentifier(String(this.relation.relatedPivotKey))}${extraColumns}) VALUES ${tuples.join(", ")}`, params);
8520
+ withBelongsTo(...args) {
8521
+ this.query.withBelongsTo(...args);
8522
+ return this;
8477
8523
  }
8478
- async deletePivotRows(connection, list) {
8479
- const parentId = this.parent.get(this.relation.parentKey);
8480
- const placeholders = list.map((_, index) => currentSqlDialect().placeholder(index + 2));
8481
- await connection.unsafe(`DELETE FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)} AND ${quoteIdentifier(String(this.relation.relatedPivotKey))} IN (${placeholders.join(", ")})`, [parentId, ...list]);
8524
+ withBelongsToMany(...args) {
8525
+ this.query.withBelongsToMany(...args);
8526
+ return this;
8482
8527
  }
8483
- async sync(ids) {
8484
- await this.detach();
8485
- if (ids.length > 0) {
8486
- await this.attach(ids);
8487
- }
8528
+ withMorphMany(...args) {
8529
+ this.query.withMorphMany(...args);
8530
+ return this;
8488
8531
  }
8489
- async create(attributes = {}) {
8490
- const related = await this.related.create(attributes);
8491
- await this.attach(related.id);
8492
- return related;
8532
+ withMorphOne(...args) {
8533
+ this.query.withMorphOne(...args);
8534
+ return this;
8493
8535
  }
8494
- }
8495
-
8496
- class MorphManyRelationQuery {
8497
- parent;
8498
- related;
8499
- relation;
8500
- kind = "morphMany";
8501
- extraWhere = [];
8502
- extraOptions = {};
8503
- constructor(parent, related, relation) {
8504
- this.parent = parent;
8505
- this.related = related;
8506
- this.relation = relation;
8536
+ withMorphTo(...args) {
8537
+ this.query.withMorphTo(...args);
8538
+ return this;
8507
8539
  }
8508
- where(where) {
8509
- this.extraWhere.push({ ...where });
8540
+ withHasManyThrough(...args) {
8541
+ this.query.withHasManyThrough(...args);
8510
8542
  return this;
8511
8543
  }
8512
- applyEagerLoad(query, alias) {
8513
- query.withMorphMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
8544
+ withTrashed() {
8545
+ this.query.withTrashed();
8546
+ return this;
8514
8547
  }
8515
- hydrateEager(row, alias) {
8516
- const value = row[alias] ?? [];
8517
- const rows = Array.isArray(value) ? value : [];
8518
- return rows.map((item) => this.related.newFromRecord(item));
8548
+ onlyTrashed() {
8549
+ this.query.onlyTrashed();
8550
+ return this;
8519
8551
  }
8520
- toExistsClause(parentTable) {
8521
- const childTable = this.related.repository().getTable().name;
8522
- const extra = relatedConditions(this.related, [
8523
- asWhere({ [this.relation.morphTypeKey]: this.relation.morphType }),
8524
- ...this.extraWhere
8525
- ], this.extraOptions, [], [parentTable]);
8526
- const sql = `SELECT 1 FROM ${quoteIdentifier(childTable)}${extra.joins} WHERE ${qualifyColumn(childTable, this.relation.morphIdKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
8527
- return { sql, params: extra.params };
8552
+ async get() {
8553
+ return await this.hydrateRows(await this.query.get());
8528
8554
  }
8529
- scopedQuery() {
8530
- return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({
8531
- [this.relation.morphTypeKey]: this.relation.morphType,
8532
- [this.relation.morphIdKey]: this.parent.get(this.relation.localKey)
8533
- }), this.extraWhere);
8555
+ async keysetPaginate(options) {
8556
+ const page = await this.query.keysetPaginate(options);
8557
+ return { ...page, data: await this.hydrateRows(page.data) };
8534
8558
  }
8535
- async get() {
8536
- const rows = await this.scopedQuery().get();
8537
- return rows.map((row) => this.related.newFromRecord(row));
8559
+ async hydrateRows(rows) {
8560
+ const statics = modelStatics(this.modelClass);
8561
+ const models = [];
8562
+ for (const row of rows) {
8563
+ const model = statics.newFromRecord(row, true);
8564
+ for (const { name, relationQuery } of this.eager) {
8565
+ model.setLoaded(name, relationQuery.hydrateEager(row, name));
8566
+ }
8567
+ models.push(model);
8568
+ }
8569
+ await Promise.all(models.map((model) => runObservers(model, "retrieved")));
8570
+ const nested = this.eager.filter((item) => item.path.includes(".")).map((item) => item.path);
8571
+ await eagerLoadOnModels(models.filter(isLoadableModel), nested);
8572
+ return models;
8538
8573
  }
8539
8574
  async first() {
8540
- const rows = await this.get();
8541
- return rows[0] ?? null;
8575
+ this.query.limit(1);
8576
+ const models = await this.get();
8577
+ return models[0] ?? null;
8542
8578
  }
8543
8579
  async count() {
8544
- return this.scopedQuery().count();
8580
+ return this.query.count();
8545
8581
  }
8546
8582
  async pluck(column, keyBy) {
8547
- return pluckFromQuery(this.scopedQuery(), column, keyBy);
8583
+ if (keyBy === undefined) {
8584
+ const values = await this.query.pluck(column);
8585
+ return values.map((value) => castPluckedValue(this.modelClass, column, value));
8586
+ }
8587
+ const keyed = await this.query.pluck(column, keyBy);
8588
+ const result = new Map;
8589
+ for (const [key, value] of keyed) {
8590
+ result.set(castPluckedValue(this.modelClass, keyBy, key), castPluckedValue(this.modelClass, column, value));
8591
+ }
8592
+ return result;
8548
8593
  }
8549
8594
  async value(column) {
8550
- return this.scopedQuery().value(column);
8595
+ const value = await this.query.value(column);
8596
+ return castPluckedValue(this.modelClass, column, value);
8597
+ }
8598
+ async find(id) {
8599
+ const primaryKey = resolveModelRepository(this.modelClass).getTable().primaryKey;
8600
+ return this.whereDynamic({ [primaryKey]: id }).first();
8601
+ }
8602
+ async findOrFail(id, errorFactory) {
8603
+ const model = await this.find(id);
8604
+ if (model) {
8605
+ return model;
8606
+ }
8607
+ throw errorFactory?.(id) ?? new NotFoundError(`${this.modelClass.name} ${String(id)} not found.`);
8551
8608
  }
8552
8609
  then(onfulfilled, onrejected) {
8553
- return thenGet(() => this.get(), onfulfilled, onrejected);
8610
+ return this.get().then(onfulfilled ?? undefined, onrejected ?? undefined);
8554
8611
  }
8555
- async create(attributes = {}) {
8556
- return this.related.create(attributes, {
8557
- [this.relation.morphTypeKey]: this.relation.morphType,
8558
- [this.relation.morphIdKey]: this.parent.get(this.relation.localKey)
8612
+ withCount(name, alias = `${name}_count`) {
8613
+ const statics = modelStatics(this.modelClass);
8614
+ ensureBooted(this.modelClass);
8615
+ const repository = resolveModelRepository(this.modelClass);
8616
+ const dummy = statics.newFromRecord({});
8617
+ const method = dummy[name];
8618
+ if (typeof method !== "function") {
8619
+ throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
8620
+ }
8621
+ const relationQuery = method.call(dummy);
8622
+ const exists = relationQuery.toExistsClause(repository.getTable().name);
8623
+ if (!exists.sql.startsWith("SELECT 1 ")) {
8624
+ throw new Error(`Cannot count relation ${name}: unexpected subquery shape.`);
8625
+ }
8626
+ this.query.withSubqueryCount(alias, `SELECT COUNT(*) ${exists.sql.slice("SELECT 1 ".length)}`, exists.params);
8627
+ return this;
8628
+ }
8629
+ constrainExists(name, constrain, not) {
8630
+ const statics = modelStatics(this.modelClass);
8631
+ ensureBooted(this.modelClass);
8632
+ const repository = resolveModelRepository(this.modelClass);
8633
+ const dummy = statics.newFromRecord({});
8634
+ const method = dummy[name];
8635
+ if (typeof method !== "function") {
8636
+ throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
8637
+ }
8638
+ const relationQuery = method.call(dummy);
8639
+ constrain?.(relationQuery);
8640
+ const exists = relationQuery.toExistsClause(repository.getTable().name);
8641
+ return not ? this.whereNotExists(exists.sql, exists.params) : this.whereExists(exists.sql, exists.params);
8642
+ }
8643
+ }
8644
+
8645
+ // ../../src/core/database/relationQuery.ts
8646
+ init_boundConnection();
8647
+ init_connectionContext();
8648
+ init_defaultConnection();
8649
+ init_dialect();
8650
+ init_repositoryConnection();
8651
+ init_transaction();
8652
+ function asWhere(where) {
8653
+ return where;
8654
+ }
8655
+ function ownerId(owner, ownerKey) {
8656
+ if (typeof owner.get === "function") {
8657
+ return owner.get(ownerKey);
8658
+ }
8659
+ if (owner && typeof owner === "object" && "id" in owner && owner.id !== undefined) {
8660
+ return owner.id;
8661
+ }
8662
+ throw new Error("belongsTo.associate() requires a related model or { id }.");
8663
+ }
8664
+ function thenGet(get, onfulfilled, onrejected) {
8665
+ return get().then(onfulfilled ?? undefined, onrejected ?? undefined);
8666
+ }
8667
+ function pluckFromQuery(query, column, keyBy) {
8668
+ if (!query) {
8669
+ return Promise.resolve(keyBy === undefined ? [] : new Map);
8670
+ }
8671
+ return keyBy === undefined ? query.pluck(column) : query.pluck(column, keyBy);
8672
+ }
8673
+ function scopedRelatedQuery(model, repository = model.repository()) {
8674
+ const query = repository.query();
8675
+ const scopedModel = model;
8676
+ return scopedModel.scopeQuery?.(query) ?? query;
8677
+ }
8678
+ function relatedOptions(model, filters, options = {}) {
8679
+ const query = scopedRelatedQuery(model);
8680
+ for (const filter of filters)
8681
+ query.where(filter);
8682
+ return { ...query.getOptions(), ...options };
8683
+ }
8684
+ function relatedRead(model, connection, binding, filters, options = {}) {
8685
+ const query = scopedRelatedQuery(model, model.repository().withConnection(connection));
8686
+ query.where(binding).protectWhere();
8687
+ for (const filter of filters)
8688
+ query.where(filter);
8689
+ if (options.orderBy)
8690
+ query.orderBy(options.orderBy);
8691
+ if (options.limit !== undefined)
8692
+ query.limit(options.limit);
8693
+ return query;
8694
+ }
8695
+ function relatedConditions(model, filters, options = {}, parameters = [], reservedTables = []) {
8696
+ const compiled = relatedOptions(model, filters, options);
8697
+ if (compiled.joins?.some((join) => reservedTables.includes(join.table))) {
8698
+ throw new Error("A related model scope joins a reserved relation table; use an explicitly aliased correlated predicate instead.");
8699
+ }
8700
+ const extra = buildQueryWhereClause(model.repository().getTable(), compiled, compiled.whereNodes, parameters);
8701
+ const predicate = extra.clause.replace(/^ WHERE /, "");
8702
+ return {
8703
+ sql: predicate ? ` AND (${predicate})` : "",
8704
+ joins: buildJoinClause(compiled.joins),
8705
+ params: extra.params
8706
+ };
8707
+ }
8708
+
8709
+ class HasManyRelationQuery {
8710
+ parent;
8711
+ related;
8712
+ relation;
8713
+ kind = "hasMany";
8714
+ extraWhere = [];
8715
+ extraOptions = {};
8716
+ constructor(parent, related, relation) {
8717
+ this.parent = parent;
8718
+ this.related = related;
8719
+ this.relation = relation;
8720
+ }
8721
+ where(where) {
8722
+ this.extraWhere.push({ ...where });
8723
+ return this;
8724
+ }
8725
+ orderBy(orderBy) {
8726
+ this.extraOptions = { ...this.extraOptions, orderBy };
8727
+ return this;
8728
+ }
8729
+ limit(limit) {
8730
+ this.extraOptions = { ...this.extraOptions, limit };
8731
+ return this;
8732
+ }
8733
+ applyEagerLoad(query, alias) {
8734
+ query.withHasMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
8735
+ }
8736
+ hydrateEager(row, alias) {
8737
+ const value = row[alias] ?? [];
8738
+ const rows = Array.isArray(value) ? value : [];
8739
+ return rows.map((item) => this.related.newFromRecord(item));
8740
+ }
8741
+ toExistsClause(parentTable) {
8742
+ const childTable = this.related.repository().getTable().name;
8743
+ const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable]);
8744
+ const sql = `SELECT 1 FROM ${quoteIdentifier(childTable)}${extra.joins} WHERE ${qualifyColumn(childTable, this.relation.foreignKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
8745
+ return { sql, params: extra.params };
8746
+ }
8747
+ scopedQuery() {
8748
+ return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({ [this.relation.foreignKey]: this.parent.get(this.relation.localKey) }), this.extraWhere, this.extraOptions);
8749
+ }
8750
+ async get() {
8751
+ const rows = await this.scopedQuery().get();
8752
+ return rows.map((row) => this.related.newFromRecord(row));
8753
+ }
8754
+ async first() {
8755
+ const rows = await this.limit(1).get();
8756
+ return rows[0] ?? null;
8757
+ }
8758
+ async count() {
8759
+ return this.scopedQuery().count();
8760
+ }
8761
+ async pluck(column, keyBy) {
8762
+ return pluckFromQuery(this.scopedQuery(), column, keyBy);
8763
+ }
8764
+ async value(column) {
8765
+ return this.scopedQuery().value(column);
8766
+ }
8767
+ then(onfulfilled, onrejected) {
8768
+ return thenGet(() => this.get(), onfulfilled, onrejected);
8769
+ }
8770
+ async create(attributes = {}) {
8771
+ return this.related.create(attributes, {
8772
+ [this.relation.foreignKey]: this.parent.get(this.relation.localKey)
8559
8773
  });
8560
8774
  }
8775
+ async save(related) {
8776
+ const forced = {
8777
+ [this.relation.foreignKey]: this.parent.get(this.relation.localKey)
8778
+ };
8779
+ const savable = related;
8780
+ if (typeof savable.save === "function") {
8781
+ savable.mergeAttributes?.(forced);
8782
+ await savable.save();
8783
+ return related;
8784
+ }
8785
+ return this.create(related);
8786
+ }
8787
+ async createMany(records) {
8788
+ return Promise.all(records.map((attributes) => this.create(attributes)));
8789
+ }
8561
8790
  }
8562
8791
 
8563
- class MorphOneRelationQuery {
8792
+ class HasOneRelationQuery {
8564
8793
  relation;
8565
- kind = "morphOne";
8794
+ kind = "hasOne";
8566
8795
  inner;
8567
8796
  constructor(parent, related, relation) {
8568
8797
  this.relation = relation;
8569
- this.inner = new MorphManyRelationQuery(parent, related, {
8570
- type: "morphMany",
8798
+ this.inner = new HasManyRelationQuery(parent, related, {
8799
+ type: "hasMany",
8571
8800
  name: relation.name,
8572
8801
  localKey: relation.localKey,
8573
- morphTypeKey: relation.morphTypeKey,
8574
- morphIdKey: relation.morphIdKey,
8575
- morphType: relation.morphType
8802
+ foreignKey: relation.foreignKey
8576
8803
  });
8577
8804
  }
8578
8805
  where(where) {
8579
8806
  this.inner.where(where);
8580
8807
  return this;
8581
8808
  }
8809
+ orderBy(orderBy) {
8810
+ this.inner.orderBy(orderBy);
8811
+ return this;
8812
+ }
8582
8813
  applyEagerLoad(query, alias) {
8583
8814
  this.inner.applyEagerLoad(query, alias);
8584
8815
  }
@@ -8590,7 +8821,7 @@ class MorphOneRelationQuery {
8590
8821
  return this.inner.toExistsClause(parentTable);
8591
8822
  }
8592
8823
  async get() {
8593
- return this.inner.first();
8824
+ return this.inner.limit(1).first();
8594
8825
  }
8595
8826
  async first() {
8596
8827
  return this.get();
@@ -8599,10 +8830,11 @@ class MorphOneRelationQuery {
8599
8830
  return this.inner.count();
8600
8831
  }
8601
8832
  async pluck(column, keyBy) {
8602
- return keyBy === undefined ? this.inner.pluck(column) : this.inner.pluck(column, keyBy);
8833
+ const query = this.inner.limit(1);
8834
+ return keyBy === undefined ? query.pluck(column) : query.pluck(column, keyBy);
8603
8835
  }
8604
8836
  async value(column) {
8605
- return this.inner.value(column);
8837
+ return this.inner.limit(1).value(column);
8606
8838
  }
8607
8839
  then(onfulfilled, onrejected) {
8608
8840
  return thenGet(() => this.get(), onfulfilled, onrejected);
@@ -8610,53 +8842,43 @@ class MorphOneRelationQuery {
8610
8842
  async create(attributes = {}) {
8611
8843
  return this.inner.create(attributes);
8612
8844
  }
8845
+ async save(related) {
8846
+ return this.inner.save(related);
8847
+ }
8613
8848
  }
8614
8849
 
8615
- class MorphToRelationQuery {
8850
+ class BelongsToRelationQuery {
8616
8851
  parent;
8617
- relatedByType;
8852
+ related;
8618
8853
  relation;
8619
- kind = "morphTo";
8854
+ kind = "belongsTo";
8620
8855
  extraWhere = [];
8621
- constructor(parent, relatedByType, relation) {
8856
+ extraOptions = {};
8857
+ constructor(parent, related, relation) {
8622
8858
  this.parent = parent;
8623
- this.relatedByType = relatedByType;
8859
+ this.related = related;
8624
8860
  this.relation = relation;
8625
8861
  }
8626
8862
  where(where) {
8627
8863
  this.extraWhere.push({ ...where });
8628
8864
  return this;
8629
8865
  }
8866
+ orderBy(orderBy) {
8867
+ this.extraOptions = { ...this.extraOptions, orderBy };
8868
+ return this;
8869
+ }
8630
8870
  applyEagerLoad(query, alias) {
8631
- const repositories = new Map(Object.entries(this.relatedByType).map(([type, model]) => [
8632
- type,
8633
- model.repository()
8634
- ]));
8635
- query.withMorphTo(alias, this.relation, repositories, {}, new Map(Object.entries(this.relatedByType).map(([type, model]) => [
8636
- type,
8637
- relatedOptions(model, this.extraWhere)
8638
- ])));
8871
+ query.withBelongsTo(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
8639
8872
  }
8640
8873
  hydrateEager(row, alias) {
8641
- return row[alias];
8874
+ const value = row[alias];
8875
+ return value ? this.related.newFromRecord(value) : value;
8642
8876
  }
8643
8877
  toExistsClause(parentTable) {
8644
- const params = [];
8645
- const type = this.parent.get(this.relation.morphTypeKey);
8646
- if (type !== undefined && type !== null && !this.relatedByType[String(type)]) {
8647
- return { sql: "SELECT 1 WHERE 1 = 0", params };
8648
- }
8649
- const branches = Object.entries(this.relatedByType).map(([type, related]) => {
8650
- params.push(type);
8651
- const discriminator = currentSqlDialect().placeholder(params.length);
8652
- const table = related.repository().getTable();
8653
- const extra = relatedConditions(related, this.extraWhere, {}, params, [parentTable]);
8654
- return `(${qualifyColumn(parentTable, this.relation.morphTypeKey)} = ${discriminator} AND EXISTS (SELECT 1 FROM ${quoteIdentifier(table.name)}${extra.joins} WHERE ${qualifyColumn(table.name, table.primaryKey)} = ${qualifyColumn(parentTable, this.relation.morphIdKey)}${extra.sql}))`;
8655
- });
8656
- return {
8657
- sql: `SELECT 1 WHERE ${branches.length > 0 ? branches.join(" OR ") : "1 = 0"}`,
8658
- params
8659
- };
8878
+ const relatedTable = this.related.repository().getTable().name;
8879
+ const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable]);
8880
+ const sql = `SELECT 1 FROM ${quoteIdentifier(relatedTable)}${extra.joins} WHERE ${qualifyColumn(relatedTable, this.relation.ownerKey)} = ${qualifyColumn(parentTable, this.relation.foreignKey)}${extra.sql}`;
8881
+ return { sql, params: extra.params };
8660
8882
  }
8661
8883
  async get() {
8662
8884
  const query = this.relatedQuery();
@@ -8664,7 +8886,10 @@ class MorphToRelationQuery {
8664
8886
  return null;
8665
8887
  }
8666
8888
  const row = await query.first();
8667
- return row ? this.relatedForCurrentType()?.newFromRecord(row) ?? null : null;
8889
+ return row ? this.related.newFromRecord(row) : null;
8890
+ }
8891
+ async first() {
8892
+ return this.get();
8668
8893
  }
8669
8894
  async pluck(column, keyBy) {
8670
8895
  return pluckFromQuery(this.relatedQuery(), column, keyBy);
@@ -8672,31 +8897,56 @@ class MorphToRelationQuery {
8672
8897
  async value(column) {
8673
8898
  return this.relatedQuery()?.value(column) ?? null;
8674
8899
  }
8675
- relatedForCurrentType() {
8676
- const type = String(this.parent.get(this.relation.morphTypeKey) ?? "");
8677
- return this.relatedByType[type];
8678
- }
8679
8900
  relatedQuery() {
8680
- const id = this.parent.get(this.relation.morphIdKey);
8681
- const related = this.relatedForCurrentType();
8682
- if (!related || id === null || id === undefined) {
8901
+ const foreign = this.parent.get(this.relation.foreignKey);
8902
+ if (foreign === null || foreign === undefined) {
8683
8903
  return null;
8684
8904
  }
8685
- const table = related.repository().getTable();
8686
- return relatedRead(related, this.parent.getRepository().getConnection(), asWhere({ [table.primaryKey]: id }), this.extraWhere);
8905
+ return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({ [this.relation.ownerKey]: foreign }), this.extraWhere, this.extraOptions);
8687
8906
  }
8688
8907
  then(onfulfilled, onrejected) {
8689
8908
  return thenGet(() => this.get(), onfulfilled, onrejected);
8690
8909
  }
8910
+ async associate(owner) {
8911
+ await this.parent.getRepository().updateById(this.parent.id, {
8912
+ [this.relation.foreignKey]: ownerId(owner, this.relation.ownerKey)
8913
+ });
8914
+ }
8915
+ async dissociate() {
8916
+ await this.parent.getRepository().updateById(this.parent.id, {
8917
+ [this.relation.foreignKey]: null
8918
+ });
8919
+ }
8920
+ }
8921
+ function pivotIdKey(id) {
8922
+ return typeof id === "number" || typeof id === "bigint" ? String(id) : id;
8923
+ }
8924
+ function hasRepeatedId(ids) {
8925
+ const seen = new Set;
8926
+ for (const id of ids) {
8927
+ const key = pivotIdKey(id);
8928
+ if (seen.has(key))
8929
+ return true;
8930
+ seen.add(key);
8931
+ }
8932
+ return false;
8933
+ }
8934
+ function canBatchPivotToggle(ids) {
8935
+ return ids.every((id) => typeof id === "bigint" && id >= BigInt(Number.MIN_SAFE_INTEGER) && id <= BigInt(Number.MAX_SAFE_INTEGER) || typeof id === "number" && Number.isSafeInteger(id) || typeof id === "string" && /^(?:0|-?[1-9]\d*)$/.test(id) && Number.isSafeInteger(Number(id)));
8936
+ }
8937
+ function isConfiguredConnection(connection) {
8938
+ const bound = getBoundDatabaseConnection();
8939
+ return connection === repositoryConnection || (bound ? connection === bound : isDefaultDatabaseConnection(connection));
8691
8940
  }
8692
8941
 
8693
- class HasManyThroughRelationQuery {
8942
+ class BelongsToManyRelationQuery {
8694
8943
  parent;
8695
8944
  related;
8696
8945
  relation;
8697
- kind = "hasManyThrough";
8946
+ kind = "belongsToMany";
8698
8947
  extraWhere = [];
8699
8948
  extraOptions = {};
8949
+ pivotValues = {};
8700
8950
  constructor(parent, related, relation) {
8701
8951
  this.parent = parent;
8702
8952
  this.related = related;
@@ -8710,12 +8960,12 @@ class HasManyThroughRelationQuery {
8710
8960
  this.extraOptions = { ...this.extraOptions, orderBy };
8711
8961
  return this;
8712
8962
  }
8713
- limit(limit) {
8714
- this.extraOptions = { ...this.extraOptions, limit };
8715
- return this;
8716
- }
8717
8963
  applyEagerLoad(query, alias) {
8718
- query.withHasManyThrough(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
8964
+ query.withBelongsToMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
8965
+ }
8966
+ withPivotValues(values) {
8967
+ this.pivotValues = { ...this.pivotValues, ...values };
8968
+ return this;
8719
8969
  }
8720
8970
  hydrateEager(row, alias) {
8721
8971
  const value = row[alias] ?? [];
@@ -8723,667 +8973,481 @@ class HasManyThroughRelationQuery {
8723
8973
  return rows.map((item) => this.related.newFromRecord(item));
8724
8974
  }
8725
8975
  toExistsClause(parentTable) {
8726
- const farTable = this.related.repository().getTable().name;
8727
- const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable, this.relation.throughTable]);
8728
- const sql = `SELECT 1 FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(this.relation.throughTable)} ON ${qualifyColumn(this.relation.throughTable, this.relation.secondLocalKey)} = ${qualifyColumn(farTable, this.relation.secondKey)}${extra.joins} WHERE ${qualifyColumn(this.relation.throughTable, this.relation.firstKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
8976
+ const relatedTable = this.related.repository().getTable().name;
8977
+ const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable, this.relation.pivotTable]);
8978
+ const sql = `SELECT 1 FROM ${quoteIdentifier(relatedTable)} INNER JOIN ${quoteIdentifier(this.relation.pivotTable)} ON ${qualifyColumn(this.relation.pivotTable, this.relation.relatedPivotKey)} = ${qualifyColumn(relatedTable, this.relation.relatedKey)}${extra.joins} WHERE ${qualifyColumn(this.relation.pivotTable, this.relation.foreignPivotKey)} = ${qualifyColumn(parentTable, this.relation.parentKey)}${extra.sql}`;
8729
8979
  return { sql, params: extra.params };
8730
8980
  }
8981
+ connection() {
8982
+ const connection = this.parent.getRepository().getConnection();
8983
+ return isConfiguredConnection(connection) ? getActiveDatabaseConnection(connection) : connection;
8984
+ }
8985
+ async atomically(work) {
8986
+ const connection = this.connection();
8987
+ if (isConfiguredConnection(connection) || hasActiveDatabaseConnection() && connection === getActiveDatabaseConnection(connection)) {
8988
+ await runInTransaction(work);
8989
+ return;
8990
+ }
8991
+ if (typeof connection.begin !== "function") {
8992
+ await work(connection);
8993
+ return;
8994
+ }
8995
+ await connection.begin(work);
8996
+ }
8731
8997
  async get() {
8732
- const rows = await this.farRows();
8998
+ const query = await this.relatedQuery();
8999
+ const rows = query ? await query.get() : [];
8733
9000
  return rows.map((row) => this.related.newFromRecord(row));
8734
9001
  }
8735
9002
  async first() {
8736
- const rows = await this.limit(1).get();
9003
+ const rows = await this.get();
8737
9004
  return rows[0] ?? null;
8738
9005
  }
8739
9006
  async count() {
8740
- const rows = await this.get();
8741
- return rows.length;
9007
+ const query = await this.relatedQuery();
9008
+ return query ? query.count() : 0;
8742
9009
  }
8743
9010
  async pluck(column, keyBy) {
8744
- const rows = await this.farRows();
8745
- return keyBy === undefined ? projectPluck(rows, column) : projectPluck(rows, column, keyBy);
9011
+ return pluckFromQuery(await this.relatedQuery(), column, keyBy);
8746
9012
  }
8747
9013
  async value(column) {
8748
- const values = await this.limit(1).pluck(column);
8749
- return values[0] ?? null;
9014
+ const query = await this.relatedQuery();
9015
+ return query ? query.value(column) : null;
8750
9016
  }
8751
- async farRows() {
8752
- return this.related.repository().withConnection(this.parent.getRepository().getConnection()).findHasManyThrough(this.parent.get(this.relation.localKey), this.relation, {
8753
- ...relatedOptions(this.related, this.extraWhere, this.extraOptions)
8754
- });
9017
+ async relatedQuery() {
9018
+ const parentId = this.parent.get(this.relation.parentKey);
9019
+ const pivotRows = await this.connection().unsafe(`SELECT * FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)}`, [parentId]);
9020
+ if (pivotRows.length === 0) {
9021
+ return null;
9022
+ }
9023
+ const relatedIds = [
9024
+ ...new Set(pivotRows.map((row) => row[this.relation.relatedPivotKey]))
9025
+ ];
9026
+ return relatedRead(this.related, this.connection(), asWhere({ [this.relation.relatedKey]: relatedIds }), this.extraWhere, this.extraOptions);
8755
9027
  }
8756
9028
  then(onfulfilled, onrejected) {
8757
9029
  return thenGet(() => this.get(), onfulfilled, onrejected);
8758
9030
  }
8759
- }
8760
-
8761
- // ../../src/core/database/model.ts
8762
- function snapshotAttributes(values) {
8763
- return Object.fromEntries(Object.entries(values).map(([key, value]) => [
8764
- key,
8765
- Buffer.isBuffer(value) ? Buffer.from(value) : structuredClone(value)
8766
- ]));
8767
- }
8768
- function changedAttributes(values, original) {
8769
- return Object.fromEntries(Object.entries(values).filter(([key, value]) => !(key in original) || !isDeepStrictEqual(value, original[key])));
8770
- }
8771
- var modelRepositories = new WeakMap;
8772
- var modelRepositoryFactories = new WeakMap;
8773
- var namedModels = new Map;
8774
- var modelGlobalScopes = new WeakMap;
8775
- var modelObservers = new WeakMap;
8776
- var modelBooted = new WeakSet;
8777
- function flattenRelationNames(relations) {
8778
- const names = [];
8779
- for (const item of relations) {
8780
- if (typeof item === "string") {
8781
- if (item.length > 0) {
8782
- names.push(item);
8783
- }
8784
- continue;
8785
- }
8786
- if (Array.isArray(item)) {
8787
- for (const nested of item) {
8788
- if (typeof nested === "string" && nested.length > 0) {
8789
- names.push(nested);
8790
- }
8791
- }
8792
- }
8793
- }
8794
- return names;
8795
- }
8796
- async function runObservers(model, hook) {
8797
- const observers = modelObservers.get(model.constructor) ?? [];
8798
- for (const observer of observers) {
8799
- const handler = observer[hook];
8800
- if (handler && await handler(model) === false) {
8801
- return false;
8802
- }
8803
- }
8804
- return true;
8805
- }
8806
- function accessorName(key) {
8807
- const pascal = key.replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
8808
- return `get${pascal.charAt(0).toUpperCase()}${pascal.slice(1)}Attribute`;
8809
- }
8810
- function isLoadableModel(value) {
8811
- return Boolean(value && typeof value === "object" && typeof value.load === "function" && typeof value.loaded === "function" && typeof value.setLoaded === "function");
8812
- }
8813
- async function eagerLoadOnModels(models, paths) {
8814
- if (models.length === 0 || paths.length === 0) {
8815
- return;
8816
- }
8817
- const grouped = new Map;
8818
- for (const path of paths) {
8819
- const [head, ...rest] = path.split(".");
8820
- if (!head) {
8821
- continue;
8822
- }
8823
- const nested = rest.join(".");
8824
- const existing = grouped.get(head) ?? [];
8825
- if (nested) {
8826
- existing.push(nested);
8827
- }
8828
- grouped.set(head, existing);
9031
+ async attach(ids) {
9032
+ const list = Array.isArray(ids) ? ids : [ids];
9033
+ if (list.length === 0)
9034
+ return;
9035
+ await this.atomically((connection) => this.insertPivotRows(connection, list));
8829
9036
  }
8830
- await Promise.all([...grouped.entries()].map(async ([head, nested]) => {
8831
- const unloaded = models.filter((model) => model.loaded(head) === undefined);
8832
- if (unloaded.length > 0) {
8833
- const first = unloaded[0];
8834
- if (!first) {
9037
+ async toggle(ids) {
9038
+ const list = Array.isArray(ids) ? ids : [ids];
9039
+ if (list.length === 0)
9040
+ return;
9041
+ await this.atomically(async (connection) => {
9042
+ if (!canBatchPivotToggle(list) || hasRepeatedId(list)) {
9043
+ for (const id of list)
9044
+ await this.toggleOne(connection, id);
8835
9045
  return;
8836
9046
  }
8837
- const method = first[head];
8838
- if (typeof method !== "function") {
8839
- throw new Error(`${first.constructor.name} has no relation method ${head}().`);
8840
- }
8841
- const relationQuery = method.call(first);
8842
- const query = first.getRepository().query();
8843
- relationQuery.applyEagerLoad(query, head);
8844
- const attached = await query.attachToRows(unloaded.map((model) => model.toObject()));
8845
- for (const [index, model] of unloaded.entries()) {
8846
- const row = attached[index] ?? model.toObject();
8847
- model.setLoaded(head, relationQuery.hydrateEager(row, head));
8848
- }
8849
- }
8850
- if (nested.length === 0) {
8851
- return;
8852
- }
8853
- const children = models.flatMap((model) => {
8854
- const loaded = model.loaded(head);
8855
- return Array.isArray(loaded) ? loaded : loaded ? [loaded] : [];
9047
+ const parentId = this.parent.get(this.relation.parentKey);
9048
+ const relatedColumn = quoteIdentifier(String(this.relation.relatedPivotKey));
9049
+ const parentColumn = quoteIdentifier(String(this.relation.foreignPivotKey));
9050
+ const placeholders = list.map((_, index) => currentSqlDialect().placeholder(index + 2));
9051
+ const existing = await connection.unsafe(`SELECT ${relatedColumn} FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${parentColumn} = ${currentSqlDialect().placeholder(1)} AND ${relatedColumn} IN (${placeholders.join(", ")})`, [parentId, ...list]);
9052
+ const existingIds = new Set(existing.map((row) => pivotIdKey(row[String(this.relation.relatedPivotKey)])));
9053
+ const present = list.filter((id) => existingIds.has(pivotIdKey(id)));
9054
+ const missing = list.filter((id) => !existingIds.has(pivotIdKey(id)));
9055
+ if (present.length > 0)
9056
+ await this.deletePivotRows(connection, present);
9057
+ if (missing.length > 0)
9058
+ await this.insertPivotRows(connection, missing);
8856
9059
  });
8857
- await eagerLoadOnModels(children.filter(isLoadableModel), nested);
8858
- }));
8859
- }
8860
- async function loadNested(model, path) {
8861
- await eagerLoadOnModels([model], [path]);
8862
- }
8863
- function nameModel(model) {
8864
- const { name, $morphClass } = model;
8865
- if (name)
8866
- namedModels.set(name, model);
8867
- if ($morphClass)
8868
- namedModels.set($morphClass, model);
8869
- }
8870
- function resolveModelRepository(model) {
8871
- const existing = modelRepositories.get(model);
8872
- if (existing)
8873
- return existing;
8874
- for (let current = model;current; current = Object.getPrototypeOf(current)) {
8875
- const factory = modelRepositoryFactories.get(current);
8876
- if (!factory)
8877
- continue;
8878
- const repository = factory();
8879
- modelRepositories.set(model, repository);
8880
- nameModel(model);
8881
- return repository;
8882
- }
8883
- throw new Error(`${model.name}.repository() is not implemented.`);
8884
- }
8885
- function defineModel(table) {
8886
-
8887
- class TableModel extends Model {
8888
- }
8889
- modelRepositoryFactories.set(TableModel, () => new baseRepository_default(table));
8890
- return TableModel;
8891
- }
8892
- function bootModels(models) {
8893
- const names = new Map;
8894
- for (const model of models) {
8895
- const { name, $morphClass } = model;
8896
- for (const alias of [name, $morphClass]) {
8897
- if (!alias)
8898
- continue;
8899
- const existing = names.get(alias);
8900
- if (existing && existing !== model)
8901
- throw new Error(`Duplicate model name [${alias}].`);
8902
- names.set(alias, model);
8903
- }
8904
- }
8905
- for (const model of models)
8906
- nameModel(model);
8907
- for (const model of models) {
8908
- resolveModelRepository(model);
8909
- ensureBooted(model);
8910
- }
8911
- }
8912
- function registerModelClass(name, model) {
8913
- namedModels.set(name, model);
8914
- }
8915
- function resolveRelated(related) {
8916
- if (typeof related === "string") {
8917
- const found = namedModels.get(related);
8918
- if (!found) {
8919
- throw new Error(`Model [${related}] is not registered. Call registerModelClass() first.`);
8920
- }
8921
- return found;
8922
- }
8923
- if (typeof related === "function" && typeof related.repository !== "function") {
8924
- return related();
8925
- }
8926
- return related;
8927
- }
8928
- function inferRelationMethodName(callee) {
8929
- const stack = new Error().stack ?? "";
8930
- let seenCallee = false;
8931
- for (const line of stack.split(`
8932
- `)) {
8933
- const match = /at (?:async )?(?:[^.\s]+\.)?(\w+)/.exec(line);
8934
- const name = match?.[1];
8935
- if (!name || name === "Error" || name === "inferRelationMethodName") {
8936
- continue;
8937
- }
8938
- if (!seenCallee) {
8939
- if (name === callee) {
8940
- seenCallee = true;
8941
- }
8942
- continue;
8943
- }
8944
- if (name !== callee) {
8945
- return name;
8946
- }
8947
- }
8948
- return;
8949
- }
8950
- function morphClassOf(model) {
8951
- const statics = modelStatics(model.constructor === Function ? model : model.constructor);
8952
- return statics.$morphClass ?? (model.constructor === Function ? model.name : model.constructor.name);
8953
- }
8954
- function modelStatics(model) {
8955
- return model;
8956
- }
8957
- function ensureBooted(model) {
8958
- if (modelBooted.has(model)) {
8959
- return;
8960
- }
8961
- nameModel(model);
8962
- modelBooted.add(model);
8963
- const scopes = modelGlobalScopes.get(model);
8964
- const observers = modelObservers.get(model);
8965
- const boot = model.boot;
8966
- if (typeof boot === "function") {
8967
- try {
8968
- boot.call(model);
8969
- } catch (error) {
8970
- modelBooted.delete(model);
8971
- if (scopes)
8972
- modelGlobalScopes.set(model, scopes);
8973
- else
8974
- modelGlobalScopes.delete(model);
8975
- if (observers)
8976
- modelObservers.set(model, observers);
8977
- else
8978
- modelObservers.delete(model);
8979
- throw error;
8980
- }
8981
- }
8982
- }
8983
- function getGlobalScopes(model) {
8984
- return modelGlobalScopes.get(model) ?? [];
8985
- }
8986
- var PASSWORD_HASH_PATTERN = /^\$(?:2[aby]?|argon2(?:i|d|id)?)\$/;
8987
- function isAlreadyHashed(value) {
8988
- return PASSWORD_HASH_PATTERN.test(value);
8989
- }
8990
- async function hashCastValue(value) {
8991
- if (value === null || value === undefined)
8992
- return value;
8993
- const plain = String(value);
8994
- if (isAlreadyHashed(plain)) {
8995
- return plain;
8996
- }
8997
- return await hashPassword(plain);
8998
- }
8999
- function hydrateValue(value, cast) {
9000
- if (value === null || value === undefined) {
9001
- return value;
9002
- }
9003
- switch (cast) {
9004
- case "date":
9005
- case "datetime":
9006
- return value instanceof Date ? value : new Date(String(value));
9007
- case "json":
9008
- return typeof value === "string" ? JSON.parse(value) : value;
9009
- case "bool":
9010
- case "boolean":
9011
- return value === true || value === 1 || value === "1" || value === "true";
9012
- case "integer":
9013
- case "int":
9014
- return value === "" ? null : Number(value);
9015
- case "hashed":
9016
- return value;
9017
- default:
9018
- return value;
9019
- }
9020
- }
9021
- function dehydrateValue(value, cast) {
9022
- if (cast === "hashed")
9023
- return hashCastValue(value);
9024
- if (value === null || value === undefined) {
9025
- return value;
9026
- }
9027
- switch (cast) {
9028
- case "date":
9029
- case "datetime":
9030
- return value instanceof Date ? value : new Date(String(value));
9031
- case "json":
9032
- return typeof value === "string" ? value : JSON.stringify(value);
9033
- case "bool":
9034
- case "boolean":
9035
- return Boolean(value);
9036
- case "integer":
9037
- case "int":
9038
- return value === "" ? null : Number(value);
9039
- default:
9040
- return value;
9041
- }
9042
- }
9043
- function filterMassAssignable(fillable, guarded, input) {
9044
- if (fillable === undefined && guarded === undefined && Object.keys(input).length > 0) {
9045
- throw new Error("Mass assignment is not configured for this model. Declare static $fillable = [...] to allow specific columns, or static $guarded = [] to allow all of them.");
9046
- }
9047
- const resolvedGuarded = guarded ?? true;
9048
- if (fillable && fillable.length > 0) {
9049
- const allowed = new Set(fillable);
9050
- return Object.fromEntries(Object.entries(input).filter(([key]) => allowed.has(key)));
9051
9060
  }
9052
- if (resolvedGuarded === true || resolvedGuarded.includes("*")) {
9053
- return {};
9054
- }
9055
- const blocked = new Set(resolvedGuarded);
9056
- return Object.fromEntries(Object.entries(input).filter(([key]) => !blocked.has(key)));
9057
- }
9058
- function applyCasts(values, casts, direction) {
9059
- const entries = Object.entries(casts);
9060
- if (entries.length === 0) {
9061
- return direction === "hydrate" ? values : Promise.resolve(values);
9062
- }
9063
- const result = { ...values };
9064
- if (direction === "hydrate") {
9065
- for (const [key, cast] of entries) {
9066
- if (key in result && cast)
9067
- result[key] = hydrateValue(result[key], cast);
9061
+ async detach(ids) {
9062
+ const parentId = this.parent.get(this.relation.parentKey);
9063
+ if (ids === undefined) {
9064
+ await this.connection().unsafe(`DELETE FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)}`, [parentId]);
9065
+ return;
9068
9066
  }
9069
- return result;
9067
+ const list = Array.isArray(ids) ? ids : [ids];
9068
+ if (list.length === 0)
9069
+ return;
9070
+ await this.deletePivotRows(this.connection(), list);
9070
9071
  }
9071
- return (async () => {
9072
- const hashes = [];
9073
- for (const [key, cast] of entries) {
9074
- if (!(key in result) || !cast)
9075
- continue;
9076
- if (cast === "hashed") {
9077
- const current = result[key];
9078
- hashes.push(hashCastValue(current).then((hashed) => {
9079
- result[key] = hashed;
9080
- }));
9081
- continue;
9082
- }
9083
- result[key] = dehydrateValue(result[key], cast);
9084
- }
9085
- await Promise.all(hashes);
9086
- return result;
9087
- })();
9088
- }
9089
- function castPluckedValue(modelClass, column, value) {
9090
- const cast = modelStatics(modelClass).$casts?.[column];
9091
- return cast ? hydrateValue(value, cast) : value;
9092
- }
9093
- function applyTimestampsOnCreate(columns, values, enabled) {
9094
- if (!enabled) {
9095
- return values;
9072
+ async toggleOne(connection, id) {
9073
+ const parentId = this.parent.get(this.relation.parentKey);
9074
+ const existing = await connection.unsafe(`SELECT 1 FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)} AND ${quoteIdentifier(String(this.relation.relatedPivotKey))} = ${currentSqlDialect().placeholder(2)} LIMIT 1`, [parentId, id]);
9075
+ if (existing.length > 0)
9076
+ await this.deletePivotRows(connection, [id]);
9077
+ else
9078
+ await this.insertPivotRows(connection, [id]);
9096
9079
  }
9097
- const now = new Date;
9098
- const result = { ...values };
9099
- if (columns.includes("created_at")) {
9100
- result.created_at = now;
9080
+ async insertPivotRows(connection, list) {
9081
+ const parentId = this.parent.get(this.relation.parentKey);
9082
+ const extraKeys = Object.keys(this.pivotValues);
9083
+ const extraColumns = extraKeys.length > 0 ? `, ${extraKeys.map((key) => quoteIdentifier(key)).join(", ")}` : "";
9084
+ const extraValues = extraKeys.map((key) => this.pivotValues[key]);
9085
+ const width = 2 + extraKeys.length;
9086
+ const tuples = list.map((_, row) => {
9087
+ const slots = Array.from({ length: width }, (__, column) => currentSqlDialect().placeholder(row * width + column + 1));
9088
+ return `(${slots.join(", ")})`;
9089
+ });
9090
+ const params = [];
9091
+ for (const id of list)
9092
+ params.push(parentId, id, ...extraValues);
9093
+ await connection.unsafe(`INSERT INTO ${quoteIdentifier(this.relation.pivotTable)} (${quoteIdentifier(String(this.relation.foreignPivotKey))}, ${quoteIdentifier(String(this.relation.relatedPivotKey))}${extraColumns}) VALUES ${tuples.join(", ")}`, params);
9101
9094
  }
9102
- if (columns.includes("updated_at")) {
9103
- result.updated_at = now;
9095
+ async deletePivotRows(connection, list) {
9096
+ const parentId = this.parent.get(this.relation.parentKey);
9097
+ const placeholders = list.map((_, index) => currentSqlDialect().placeholder(index + 2));
9098
+ await connection.unsafe(`DELETE FROM ${quoteIdentifier(this.relation.pivotTable)} WHERE ${quoteIdentifier(String(this.relation.foreignPivotKey))} = ${currentSqlDialect().placeholder(1)} AND ${quoteIdentifier(String(this.relation.relatedPivotKey))} IN (${placeholders.join(", ")})`, [parentId, ...list]);
9104
9099
  }
9105
- return result;
9106
- }
9107
- function applyTimestampsOnUpdate(columns, values, enabled) {
9108
- if (!enabled) {
9109
- return values;
9100
+ async sync(ids) {
9101
+ await this.detach();
9102
+ if (ids.length > 0) {
9103
+ await this.attach(ids);
9104
+ }
9110
9105
  }
9111
- const result = { ...values };
9112
- if (columns.includes("updated_at")) {
9113
- result.updated_at = new Date;
9106
+ async create(attributes = {}) {
9107
+ const related = await this.related.create(attributes);
9108
+ await this.attach(related.id);
9109
+ return related;
9114
9110
  }
9115
- return result;
9116
9111
  }
9117
9112
 
9118
- class ModelProjection {
9119
- load;
9120
- page;
9121
- constructor(load, page) {
9122
- this.load = load;
9123
- this.page = page;
9113
+ class MorphManyRelationQuery {
9114
+ parent;
9115
+ related;
9116
+ relation;
9117
+ kind = "morphMany";
9118
+ extraWhere = [];
9119
+ extraOptions = {};
9120
+ constructor(parent, related, relation) {
9121
+ this.parent = parent;
9122
+ this.related = related;
9123
+ this.relation = relation;
9124
9124
  }
9125
- keysetPaginate(options) {
9126
- return this.page(options);
9125
+ where(where) {
9126
+ this.extraWhere.push({ ...where });
9127
+ return this;
9127
9128
  }
9128
- get() {
9129
- return this.load();
9129
+ applyEagerLoad(query, alias) {
9130
+ query.withMorphMany(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
9130
9131
  }
9131
- async first() {
9132
- return (await this.load(1))[0] ?? null;
9132
+ hydrateEager(row, alias) {
9133
+ const value = row[alias] ?? [];
9134
+ const rows = Array.isArray(value) ? value : [];
9135
+ return rows.map((item) => this.related.newFromRecord(item));
9133
9136
  }
9134
- }
9135
-
9136
- class ModelQuery {
9137
- modelClass;
9138
- query;
9139
- eager = [];
9140
- constructor(modelClass, query) {
9141
- this.modelClass = modelClass;
9142
- this.query = query;
9137
+ toExistsClause(parentTable) {
9138
+ const childTable = this.related.repository().getTable().name;
9139
+ const extra = relatedConditions(this.related, [
9140
+ asWhere({ [this.relation.morphTypeKey]: this.relation.morphType }),
9141
+ ...this.extraWhere
9142
+ ], this.extraOptions, [], [parentTable]);
9143
+ const sql = `SELECT 1 FROM ${quoteIdentifier(childTable)}${extra.joins} WHERE ${qualifyColumn(childTable, this.relation.morphIdKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
9144
+ return { sql, params: extra.params };
9143
9145
  }
9144
- with(...relations) {
9145
- const statics = modelStatics(this.modelClass);
9146
- ensureBooted(this.modelClass);
9147
- const dummy = statics.newFromRecord({}, false);
9148
- for (const path of flattenRelationNames(relations)) {
9149
- const name = path.split(".")[0] ?? path;
9150
- const method = dummy[name];
9151
- if (typeof method !== "function") {
9152
- throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
9153
- }
9154
- const relationQuery = method.call(dummy);
9155
- this.eager.push({ name, path, relationQuery });
9156
- relationQuery.applyEagerLoad(this.query, name);
9157
- }
9158
- return this;
9146
+ scopedQuery() {
9147
+ return relatedRead(this.related, this.parent.getRepository().getConnection(), asWhere({
9148
+ [this.relation.morphTypeKey]: this.relation.morphType,
9149
+ [this.relation.morphIdKey]: this.parent.get(this.relation.localKey)
9150
+ }), this.extraWhere);
9159
9151
  }
9160
- where(input) {
9161
- this.query.where(input);
9162
- return this;
9152
+ async get() {
9153
+ const rows = await this.scopedQuery().get();
9154
+ return rows.map((row) => this.related.newFromRecord(row));
9163
9155
  }
9164
- orWhere(input) {
9165
- this.query.orWhere(input);
9166
- return this;
9156
+ async first() {
9157
+ const rows = await this.get();
9158
+ return rows[0] ?? null;
9167
9159
  }
9168
- whereDynamic(input) {
9169
- this.query.where(input);
9170
- return this;
9160
+ async count() {
9161
+ return this.scopedQuery().count();
9171
9162
  }
9172
- select(...columns) {
9173
- return new ModelProjection(async (limit) => {
9174
- const rows = await this.query.project(columns, limit);
9175
- return rows.map((row) => applyCasts(row, modelStatics(this.modelClass).$casts, "hydrate"));
9176
- }, async (options) => {
9177
- const page = await this.query.projectKeyset(columns, options);
9178
- return {
9179
- ...page,
9180
- data: page.data.map((row) => applyCasts(row, modelStatics(this.modelClass).$casts, "hydrate"))
9181
- };
9182
- });
9163
+ async pluck(column, keyBy) {
9164
+ return pluckFromQuery(this.scopedQuery(), column, keyBy);
9183
9165
  }
9184
- lockForUpdate(options = {}) {
9185
- this.query.lockForUpdate(options);
9186
- return this;
9166
+ async value(column) {
9167
+ return this.scopedQuery().value(column);
9187
9168
  }
9188
- sharedLock(options = {}) {
9189
- this.query.sharedLock(options);
9190
- return this;
9169
+ then(onfulfilled, onrejected) {
9170
+ return thenGet(() => this.get(), onfulfilled, onrejected);
9191
9171
  }
9192
- orderBy(orderBy) {
9193
- this.query.orderBy(orderBy);
9194
- return this;
9172
+ async create(attributes = {}) {
9173
+ return this.related.create(attributes, {
9174
+ [this.relation.morphTypeKey]: this.relation.morphType,
9175
+ [this.relation.morphIdKey]: this.parent.get(this.relation.localKey)
9176
+ });
9195
9177
  }
9196
- limit(limit) {
9197
- this.query.limit(limit);
9198
- return this;
9178
+ }
9179
+
9180
+ class MorphOneRelationQuery {
9181
+ relation;
9182
+ kind = "morphOne";
9183
+ inner;
9184
+ constructor(parent, related, relation) {
9185
+ this.relation = relation;
9186
+ this.inner = new MorphManyRelationQuery(parent, related, {
9187
+ type: "morphMany",
9188
+ name: relation.name,
9189
+ localKey: relation.localKey,
9190
+ morphTypeKey: relation.morphTypeKey,
9191
+ morphIdKey: relation.morphIdKey,
9192
+ morphType: relation.morphType
9193
+ });
9199
9194
  }
9200
- offset(offset) {
9201
- this.query.offset(offset);
9195
+ where(where) {
9196
+ this.inner.where(where);
9202
9197
  return this;
9203
9198
  }
9204
- whereNull(column) {
9205
- this.query.whereNull(column);
9206
- return this;
9199
+ applyEagerLoad(query, alias) {
9200
+ this.inner.applyEagerLoad(query, alias);
9207
9201
  }
9208
- whereNotNull(column) {
9209
- this.query.whereNotNull(column);
9210
- return this;
9202
+ hydrateEager(row, alias) {
9203
+ const hydrated = this.inner.hydrateEager(row, alias);
9204
+ return hydrated[0];
9211
9205
  }
9212
- whereIn(column, values) {
9213
- this.query.whereIn(column, values);
9214
- return this;
9206
+ toExistsClause(parentTable) {
9207
+ return this.inner.toExistsClause(parentTable);
9215
9208
  }
9216
- whereNotIn(column, values) {
9217
- this.query.whereNotIn(column, values);
9218
- return this;
9209
+ async get() {
9210
+ return this.inner.first();
9219
9211
  }
9220
- groupBy(groupBy) {
9221
- this.query.groupBy(groupBy);
9222
- return this;
9212
+ async first() {
9213
+ return this.get();
9223
9214
  }
9224
- having(having) {
9225
- this.query.having(having);
9226
- return this;
9215
+ async count() {
9216
+ return this.inner.count();
9217
+ }
9218
+ async pluck(column, keyBy) {
9219
+ return keyBy === undefined ? this.inner.pluck(column) : this.inner.pluck(column, keyBy);
9227
9220
  }
9228
- join(left, right) {
9229
- this.query.join(left, right);
9230
- return this;
9221
+ async value(column) {
9222
+ return this.inner.value(column);
9231
9223
  }
9232
- leftJoin(left, right) {
9233
- this.query.leftJoin(left, right);
9234
- return this;
9224
+ then(onfulfilled, onrejected) {
9225
+ return thenGet(() => this.get(), onfulfilled, onrejected);
9235
9226
  }
9236
- async paginate(options) {
9237
- const { data, meta } = await this.query.paginate(options);
9238
- return { data: await this.hydrateRows(data), meta };
9227
+ async create(attributes = {}) {
9228
+ return this.inner.create(attributes);
9239
9229
  }
9240
- whereExists(sql, params = []) {
9241
- this.query.whereExists(sql, params);
9242
- return this;
9230
+ }
9231
+
9232
+ class MorphToRelationQuery {
9233
+ parent;
9234
+ relatedByType;
9235
+ relation;
9236
+ kind = "morphTo";
9237
+ extraWhere = [];
9238
+ constructor(parent, relatedByType, relation) {
9239
+ this.parent = parent;
9240
+ this.relatedByType = relatedByType;
9241
+ this.relation = relation;
9243
9242
  }
9244
- whereNotExists(sql, params = []) {
9245
- this.query.whereNotExists(sql, params);
9243
+ where(where) {
9244
+ this.extraWhere.push({ ...where });
9246
9245
  return this;
9247
9246
  }
9248
- whereHas(name, constrain) {
9249
- return this.constrainExists(name, constrain, false);
9247
+ applyEagerLoad(query, alias) {
9248
+ const repositories = new Map(Object.entries(this.relatedByType).map(([type, model]) => [
9249
+ type,
9250
+ model.repository()
9251
+ ]));
9252
+ query.withMorphTo(alias, this.relation, repositories, {}, new Map(Object.entries(this.relatedByType).map(([type, model]) => [
9253
+ type,
9254
+ relatedOptions(model, this.extraWhere)
9255
+ ])));
9250
9256
  }
9251
- has(name) {
9252
- return this.constrainExists(name, undefined, false);
9257
+ hydrateEager(row, alias) {
9258
+ return row[alias];
9253
9259
  }
9254
- doesntHave(name) {
9255
- return this.constrainExists(name, undefined, true);
9260
+ toExistsClause(parentTable) {
9261
+ const params = [];
9262
+ const type = this.parent.get(this.relation.morphTypeKey);
9263
+ if (type !== undefined && type !== null && !this.relatedByType[String(type)]) {
9264
+ return { sql: "SELECT 1 WHERE 1 = 0", params };
9265
+ }
9266
+ const branches = Object.entries(this.relatedByType).map(([type, related]) => {
9267
+ params.push(type);
9268
+ const discriminator = currentSqlDialect().placeholder(params.length);
9269
+ const table = related.repository().getTable();
9270
+ const extra = relatedConditions(related, this.extraWhere, {}, params, [parentTable]);
9271
+ return `(${qualifyColumn(parentTable, this.relation.morphTypeKey)} = ${discriminator} AND EXISTS (SELECT 1 FROM ${quoteIdentifier(table.name)}${extra.joins} WHERE ${qualifyColumn(table.name, table.primaryKey)} = ${qualifyColumn(parentTable, this.relation.morphIdKey)}${extra.sql}))`;
9272
+ });
9273
+ return {
9274
+ sql: `SELECT 1 WHERE ${branches.length > 0 ? branches.join(" OR ") : "1 = 0"}`,
9275
+ params
9276
+ };
9256
9277
  }
9257
- whereDoesntHave(name, constrain) {
9258
- return this.constrainExists(name, constrain, true);
9278
+ async get() {
9279
+ const query = this.relatedQuery();
9280
+ if (!query) {
9281
+ return null;
9282
+ }
9283
+ const row = await query.first();
9284
+ return row ? this.relatedForCurrentType()?.newFromRecord(row) ?? null : null;
9259
9285
  }
9260
- withHasMany(...args) {
9261
- this.query.withHasMany(...args);
9262
- return this;
9286
+ async pluck(column, keyBy) {
9287
+ return pluckFromQuery(this.relatedQuery(), column, keyBy);
9263
9288
  }
9264
- withBelongsTo(...args) {
9265
- this.query.withBelongsTo(...args);
9266
- return this;
9289
+ async value(column) {
9290
+ return this.relatedQuery()?.value(column) ?? null;
9267
9291
  }
9268
- withBelongsToMany(...args) {
9269
- this.query.withBelongsToMany(...args);
9270
- return this;
9292
+ relatedForCurrentType() {
9293
+ const type = String(this.parent.get(this.relation.morphTypeKey) ?? "");
9294
+ return this.relatedByType[type];
9271
9295
  }
9272
- withMorphMany(...args) {
9273
- this.query.withMorphMany(...args);
9274
- return this;
9296
+ relatedQuery() {
9297
+ const id = this.parent.get(this.relation.morphIdKey);
9298
+ const related = this.relatedForCurrentType();
9299
+ if (!related || id === null || id === undefined) {
9300
+ return null;
9301
+ }
9302
+ const table = related.repository().getTable();
9303
+ return relatedRead(related, this.parent.getRepository().getConnection(), asWhere({ [table.primaryKey]: id }), this.extraWhere);
9275
9304
  }
9276
- withMorphOne(...args) {
9277
- this.query.withMorphOne(...args);
9278
- return this;
9305
+ then(onfulfilled, onrejected) {
9306
+ return thenGet(() => this.get(), onfulfilled, onrejected);
9279
9307
  }
9280
- withMorphTo(...args) {
9281
- this.query.withMorphTo(...args);
9282
- return this;
9308
+ }
9309
+
9310
+ class HasManyThroughRelationQuery {
9311
+ parent;
9312
+ related;
9313
+ relation;
9314
+ kind = "hasManyThrough";
9315
+ extraWhere = [];
9316
+ extraOptions = {};
9317
+ constructor(parent, related, relation) {
9318
+ this.parent = parent;
9319
+ this.related = related;
9320
+ this.relation = relation;
9283
9321
  }
9284
- withHasManyThrough(...args) {
9285
- this.query.withHasManyThrough(...args);
9322
+ where(where) {
9323
+ this.extraWhere.push({ ...where });
9286
9324
  return this;
9287
9325
  }
9288
- withTrashed() {
9289
- this.query.withTrashed();
9326
+ orderBy(orderBy) {
9327
+ this.extraOptions = { ...this.extraOptions, orderBy };
9290
9328
  return this;
9291
9329
  }
9292
- onlyTrashed() {
9293
- this.query.onlyTrashed();
9330
+ limit(limit) {
9331
+ this.extraOptions = { ...this.extraOptions, limit };
9294
9332
  return this;
9295
9333
  }
9296
- async get() {
9297
- return await this.hydrateRows(await this.query.get());
9334
+ applyEagerLoad(query, alias) {
9335
+ query.withHasManyThrough(alias, this.relation, this.related.repository(), relatedOptions(this.related, this.extraWhere, this.extraOptions));
9298
9336
  }
9299
- async keysetPaginate(options) {
9300
- const page = await this.query.keysetPaginate(options);
9301
- return { ...page, data: await this.hydrateRows(page.data) };
9337
+ hydrateEager(row, alias) {
9338
+ const value = row[alias] ?? [];
9339
+ const rows = Array.isArray(value) ? value : [];
9340
+ return rows.map((item) => this.related.newFromRecord(item));
9302
9341
  }
9303
- async hydrateRows(rows) {
9304
- const statics = modelStatics(this.modelClass);
9305
- const models = [];
9306
- for (const row of rows) {
9307
- const model = statics.newFromRecord(row, true);
9308
- for (const { name, relationQuery } of this.eager) {
9309
- model.setLoaded(name, relationQuery.hydrateEager(row, name));
9310
- }
9311
- models.push(model);
9312
- }
9313
- await Promise.all(models.map((model) => runObservers(model, "retrieved")));
9314
- const nested = this.eager.filter((item) => item.path.includes(".")).map((item) => item.path);
9315
- await eagerLoadOnModels(models.filter(isLoadableModel), nested);
9316
- return models;
9342
+ toExistsClause(parentTable) {
9343
+ const farTable = this.related.repository().getTable().name;
9344
+ const extra = relatedConditions(this.related, this.extraWhere, this.extraOptions, [], [parentTable, this.relation.throughTable]);
9345
+ const sql = `SELECT 1 FROM ${quoteIdentifier(farTable)} INNER JOIN ${quoteIdentifier(this.relation.throughTable)} ON ${qualifyColumn(this.relation.throughTable, this.relation.secondLocalKey)} = ${qualifyColumn(farTable, this.relation.secondKey)}${extra.joins} WHERE ${qualifyColumn(this.relation.throughTable, this.relation.firstKey)} = ${qualifyColumn(parentTable, this.relation.localKey)}${extra.sql}`;
9346
+ return { sql, params: extra.params };
9347
+ }
9348
+ async get() {
9349
+ const rows = await this.farRows();
9350
+ return rows.map((row) => this.related.newFromRecord(row));
9317
9351
  }
9318
9352
  async first() {
9319
- this.query.limit(1);
9320
- const models = await this.get();
9321
- return models[0] ?? null;
9353
+ const rows = await this.limit(1).get();
9354
+ return rows[0] ?? null;
9322
9355
  }
9323
9356
  async count() {
9324
- return this.query.count();
9357
+ const rows = await this.get();
9358
+ return rows.length;
9325
9359
  }
9326
9360
  async pluck(column, keyBy) {
9327
- if (keyBy === undefined) {
9328
- const values = await this.query.pluck(column);
9329
- return values.map((value) => castPluckedValue(this.modelClass, column, value));
9330
- }
9331
- const keyed = await this.query.pluck(column, keyBy);
9332
- const result = new Map;
9333
- for (const [key, value] of keyed) {
9334
- result.set(castPluckedValue(this.modelClass, keyBy, key), castPluckedValue(this.modelClass, column, value));
9335
- }
9336
- return result;
9361
+ const rows = await this.farRows();
9362
+ return keyBy === undefined ? projectPluck(rows, column) : projectPluck(rows, column, keyBy);
9337
9363
  }
9338
9364
  async value(column) {
9339
- const value = await this.query.value(column);
9340
- return castPluckedValue(this.modelClass, column, value);
9341
- }
9342
- async find(id) {
9343
- const primaryKey = resolveModelRepository(this.modelClass).getTable().primaryKey;
9344
- return this.whereDynamic({ [primaryKey]: id }).first();
9365
+ const values = await this.limit(1).pluck(column);
9366
+ return values[0] ?? null;
9345
9367
  }
9346
- async findOrFail(id, errorFactory) {
9347
- const model = await this.find(id);
9348
- if (model) {
9349
- return model;
9350
- }
9351
- throw errorFactory?.(id) ?? new NotFoundError(`${this.modelClass.name} ${String(id)} not found.`);
9368
+ async farRows() {
9369
+ return this.related.repository().withConnection(this.parent.getRepository().getConnection()).findHasManyThrough(this.parent.get(this.relation.localKey), this.relation, {
9370
+ ...relatedOptions(this.related, this.extraWhere, this.extraOptions)
9371
+ });
9352
9372
  }
9353
9373
  then(onfulfilled, onrejected) {
9354
- return this.get().then(onfulfilled ?? undefined, onrejected ?? undefined);
9374
+ return thenGet(() => this.get(), onfulfilled, onrejected);
9355
9375
  }
9356
- withCount(name, alias = `${name}_count`) {
9357
- const statics = modelStatics(this.modelClass);
9358
- ensureBooted(this.modelClass);
9359
- const repository = resolveModelRepository(this.modelClass);
9360
- const dummy = statics.newFromRecord({});
9361
- const method = dummy[name];
9362
- if (typeof method !== "function") {
9363
- throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
9376
+ }
9377
+
9378
+ // ../../src/core/database/model.ts
9379
+ function accessorName(key) {
9380
+ const pascal = key.replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
9381
+ return `get${pascal.charAt(0).toUpperCase()}${pascal.slice(1)}Attribute`;
9382
+ }
9383
+ function defineModel(table) {
9384
+
9385
+ class TableModel extends Model {
9386
+ }
9387
+ registerModelRepositoryFactory(TableModel, () => new baseRepository_default(table));
9388
+ return TableModel;
9389
+ }
9390
+ function bootModels(models) {
9391
+ const names = new Map;
9392
+ for (const model of models) {
9393
+ const { name, $morphClass } = model;
9394
+ for (const alias of [name, $morphClass]) {
9395
+ if (!alias)
9396
+ continue;
9397
+ const existing = names.get(alias);
9398
+ if (existing && existing !== model)
9399
+ throw new Error(`Duplicate model name [${alias}].`);
9400
+ names.set(alias, model);
9364
9401
  }
9365
- const relationQuery = method.call(dummy);
9366
- const exists = relationQuery.toExistsClause(repository.getTable().name);
9367
- if (!exists.sql.startsWith("SELECT 1 ")) {
9368
- throw new Error(`Cannot count relation ${name}: unexpected subquery shape.`);
9402
+ }
9403
+ for (const model of models)
9404
+ nameModel(model);
9405
+ for (const model of models) {
9406
+ resolveModelRepository(model);
9407
+ ensureBooted(model);
9408
+ }
9409
+ }
9410
+ function resolveRelated(related) {
9411
+ if (typeof related === "string") {
9412
+ const found = findNamedModel(related);
9413
+ if (!found) {
9414
+ throw new Error(`Model [${related}] is not registered. Call registerModelClass() first.`);
9369
9415
  }
9370
- this.query.withSubqueryCount(alias, `SELECT COUNT(*) ${exists.sql.slice("SELECT 1 ".length)}`, exists.params);
9371
- return this;
9416
+ return found;
9372
9417
  }
9373
- constrainExists(name, constrain, not) {
9374
- const statics = modelStatics(this.modelClass);
9375
- ensureBooted(this.modelClass);
9376
- const repository = resolveModelRepository(this.modelClass);
9377
- const dummy = statics.newFromRecord({});
9378
- const method = dummy[name];
9379
- if (typeof method !== "function") {
9380
- throw new Error(`${this.modelClass.name} has no relation method ${name}().`);
9418
+ if (typeof related === "function" && typeof related.repository !== "function") {
9419
+ return related();
9420
+ }
9421
+ return related;
9422
+ }
9423
+ function inferRelationMethodName(callee) {
9424
+ const stack = new Error().stack ?? "";
9425
+ let seenCallee = false;
9426
+ for (const line of stack.split(`
9427
+ `)) {
9428
+ const match = /at (?:async )?(?:[^.\s]+\.)?(\w+)/.exec(line);
9429
+ const name = match?.[1];
9430
+ if (!name || name === "Error" || name === "inferRelationMethodName") {
9431
+ continue;
9432
+ }
9433
+ if (!seenCallee) {
9434
+ if (name === callee) {
9435
+ seenCallee = true;
9436
+ }
9437
+ continue;
9438
+ }
9439
+ if (name !== callee) {
9440
+ return name;
9381
9441
  }
9382
- const relationQuery = method.call(dummy);
9383
- constrain?.(relationQuery);
9384
- const exists = relationQuery.toExistsClause(repository.getTable().name);
9385
- return not ? this.whereNotExists(exists.sql, exists.params) : this.whereExists(exists.sql, exists.params);
9386
9442
  }
9443
+ return;
9444
+ }
9445
+ function morphClassOf(model) {
9446
+ const statics = modelStatics2(model.constructor === Function ? model : model.constructor);
9447
+ return statics.$morphClass ?? (model.constructor === Function ? model.name : model.constructor.name);
9448
+ }
9449
+ function modelStatics2(model) {
9450
+ return model;
9387
9451
  }
9388
9452
 
9389
9453
  class Model {
@@ -9407,14 +9471,14 @@ class Model {
9407
9471
  this.attributes = attributes;
9408
9472
  this.repository = repository;
9409
9473
  this._exists = exists;
9410
- this.attributes = modelStatics(this.constructor).hydrateAttributes(attributes);
9474
+ this.attributes = modelStatics2(this.constructor).hydrateAttributes(attributes);
9411
9475
  this.originalAttributes = snapshotAttributes(this.attributes);
9412
9476
  }
9413
9477
  acceptPersistedAttributes(record) {
9414
9478
  const original = this.originalAttributes;
9415
9479
  const beforeWrite = snapshotAttributes(this.attributes);
9416
9480
  const existed = this._exists;
9417
- this.attributes = modelStatics(this.constructor).hydrateAttributes(record);
9481
+ this.attributes = modelStatics2(this.constructor).hydrateAttributes(record);
9418
9482
  this.originalAttributes = snapshotAttributes(this.attributes);
9419
9483
  const written = this.originalAttributes;
9420
9484
  this._exists = true;
@@ -9443,7 +9507,7 @@ class Model {
9443
9507
  return { ...this.attributes };
9444
9508
  }
9445
9509
  toArray() {
9446
- const ModelClass = modelStatics(this.constructor);
9510
+ const ModelClass = modelStatics2(this.constructor);
9447
9511
  const hidden = new Set([...ModelClass.$hidden ?? [], ...this.hiddenOverrides]);
9448
9512
  const visible = this.visibleOverrides.length > 0 ? this.visibleOverrides : ModelClass.$visible;
9449
9513
  const data = { ...this.attributes };
@@ -9492,30 +9556,24 @@ class Model {
9492
9556
  return resolveModelRepository(this).getTable().primaryKey;
9493
9557
  }
9494
9558
  static hydrateAttributes(attributes) {
9495
- const casts = modelStatics(this).$casts ?? {};
9559
+ const casts = modelStatics2(this).$casts ?? {};
9496
9560
  return applyCasts(attributes, casts, "hydrate");
9497
9561
  }
9498
9562
  static dehydrateAttributes(attributes) {
9499
- const casts = modelStatics(this).$casts ?? {};
9563
+ const casts = modelStatics2(this).$casts ?? {};
9500
9564
  return applyCasts(attributes, casts, "dehydrate");
9501
9565
  }
9502
9566
  static fromRecord(record, repository, exists = true) {
9503
- const statics = modelStatics(this);
9567
+ const statics = modelStatics2(this);
9504
9568
  const hydrated = statics.hydrateAttributes(record);
9505
9569
  return new statics(hydrated, repository, exists);
9506
9570
  }
9507
9571
  static boot() {}
9508
9572
  static observe(observer) {
9509
- const existing = modelObservers.get(this) ?? [];
9510
- modelObservers.set(this, [...existing, observer]);
9573
+ observeModel(this, observer);
9511
9574
  }
9512
9575
  static addGlobalScope(_name, scope) {
9513
- ensureBooted(this);
9514
- const existing = modelGlobalScopes.get(this) ?? [];
9515
- modelGlobalScopes.set(this, [
9516
- ...existing,
9517
- scope
9518
- ]);
9576
+ addModelGlobalScope(this, scope);
9519
9577
  }
9520
9578
  static repository() {
9521
9579
  const repository = resolveModelRepository(this);
@@ -9537,13 +9595,13 @@ class Model {
9537
9595
  }
9538
9596
  static newFromRecord(record, exists = true) {
9539
9597
  const repository = resolveModelRepository(this);
9540
- return modelStatics(this).fromRecord(record, repository, exists);
9598
+ return modelStatics2(this).fromRecord(record, repository, exists);
9541
9599
  }
9542
9600
  static newFromTrustedRecord(record, exists = true) {
9543
- return modelStatics(this).newFromRecord(record, exists);
9601
+ return modelStatics2(this).newFromRecord(record, exists);
9544
9602
  }
9545
9603
  static async create(attributes, forced = {}) {
9546
- const statics = modelStatics(this);
9604
+ const statics = modelStatics2(this);
9547
9605
  ensureBooted(this);
9548
9606
  const repository = resolveModelRepository(this);
9549
9607
  const table = repository.getTable();
@@ -9577,7 +9635,7 @@ class Model {
9577
9635
  return Model.query.call(this).onlyTrashed();
9578
9636
  }
9579
9637
  static async chunk(count, callback) {
9580
- const statics = modelStatics(this);
9638
+ const statics = modelStatics2(this);
9581
9639
  ensureBooted(this);
9582
9640
  await Model.query.call(this).query.chunk(count, async (rows) => {
9583
9641
  return await callback(rows.map((row) => statics.newFromRecord(row, true)));
@@ -9587,7 +9645,7 @@ class Model {
9587
9645
  return Model.query.call(this).keysetPaginate(options);
9588
9646
  }
9589
9647
  static async cursorPaginate(options) {
9590
- const statics = modelStatics(this);
9648
+ const statics = modelStatics2(this);
9591
9649
  ensureBooted(this);
9592
9650
  const page = await Model.query.call(this).query.cursorPaginate({
9593
9651
  perPage: options.perPage,
@@ -9656,7 +9714,7 @@ class Model {
9656
9714
  if (existing) {
9657
9715
  return existing;
9658
9716
  }
9659
- return modelStatics(this).newFromRecord({ ...where, ...values }, false);
9717
+ return modelStatics2(this).newFromRecord({ ...where, ...values }, false);
9660
9718
  }
9661
9719
  static async firstOrCreate(where, values = {}) {
9662
9720
  const findExisting = () => Model.firstWhere.call(this, where);
@@ -9685,9 +9743,8 @@ class Model {
9685
9743
  return Model.create.call(this, { ...where, ...values });
9686
9744
  }
9687
9745
  async save() {
9688
- const ModelClass = modelStatics(this.constructor);
9746
+ const ModelClass = modelStatics2(this.constructor);
9689
9747
  const timestamps = ModelClass.$timestamps ?? true;
9690
- const casts = ModelClass.$casts ?? {};
9691
9748
  const table = this.repository.getTable();
9692
9749
  const updating = this.$exists;
9693
9750
  if (await runObservers(this, "saving") === false) {
@@ -9702,7 +9759,7 @@ class Model {
9702
9759
  await runObservers(this, "saved");
9703
9760
  return this;
9704
9761
  }
9705
- const changes = applyTimestampsOnUpdate(table.columns, await applyCasts(dirty, casts, "dehydrate"), timestamps);
9762
+ const changes = applyTimestampsOnUpdate(table.columns, await ModelClass.dehydrateAttributes(dirty), timestamps);
9706
9763
  const record = await this.repository.updateByIdOrThrow(this.id, changes);
9707
9764
  this.acceptPersistedAttributes(record);
9708
9765
  await runObservers(this, "updated");
@@ -9719,7 +9776,7 @@ class Model {
9719
9776
  return this;
9720
9777
  }
9721
9778
  async update(changes) {
9722
- const ModelClass = modelStatics(this.constructor);
9779
+ const ModelClass = modelStatics2(this.constructor);
9723
9780
  const assignable = filterMassAssignable(ModelClass.$fillable, ModelClass.$guarded, changes);
9724
9781
  Object.assign(this.attributes, assignable);
9725
9782
  return await this.save();
@@ -9896,7 +9953,7 @@ class Model {
9896
9953
  }
9897
9954
  }
9898
9955
  function registerModelRepository(model, repository) {
9899
- modelRepositories.set(model, repository);
9956
+ bindModelRepository(model, repository);
9900
9957
  nameModel(model);
9901
9958
  ensureBooted(model);
9902
9959
  return model;
@@ -10971,30 +11028,7 @@ class SqlOutbox {
10971
11028
  });
10972
11029
  }
10973
11030
  }
10974
- // ../../src/core/mail/mailer.ts
10975
- function resolveSmtpConfig() {
10976
- const host = process.env.MAIL_HOST?.trim();
10977
- if (!host) {
10978
- throw new Error('MAIL_DRIVER="smtp" requires MAIL_HOST to be set.');
10979
- }
10980
- const from = process.env.MAIL_FROM?.trim();
10981
- if (!from) {
10982
- throw new Error('MAIL_DRIVER="smtp" requires MAIL_FROM to be set.');
10983
- }
10984
- const port = Number(process.env.MAIL_PORT ?? "587");
10985
- if (!Number.isInteger(port) || port <= 0 || port > 65535) {
10986
- throw new Error('Environment variable "MAIL_PORT" must be a positive integer.');
10987
- }
10988
- return {
10989
- host,
10990
- port,
10991
- from,
10992
- secure: (process.env.MAIL_SECURE ?? "false") === "true",
10993
- ...process.env.MAIL_TIMEOUT_MS !== undefined ? { timeoutMs: smtpTimeout(Number(process.env.MAIL_TIMEOUT_MS)) } : {},
10994
- ...process.env.MAIL_USERNAME?.trim() ? { username: process.env.MAIL_USERNAME.trim() } : {},
10995
- ...process.env.MAIL_PASSWORD?.trim() ? { password: process.env.MAIL_PASSWORD.trim() } : {}
10996
- };
10997
- }
11031
+ // ../../src/core/mail/smtpMessage.ts
10998
11032
  var EMAIL_SHAPE = /^[^\s@\r\n]+@[^\s@\r\n]+\.[^\s@\r\n]+$/u;
10999
11033
  function assertSafeSmtpField(value, field) {
11000
11034
  if (/[\r\n]/u.test(value)) {
@@ -11020,12 +11054,111 @@ function assertSafeSmtpAddress(value, field) {
11020
11054
  smtpEnvelopeAddress(value, field);
11021
11055
  return assertSafeSmtpField(value, field).trim();
11022
11056
  }
11023
- function redactMailBody(body) {
11024
- return body.replace(/https?:\/\/[^\s]+/giu, "[redacted-url]").replace(/[?&](token|signature|expires|code)=[^&\s]+/giu, "[redacted-query]");
11025
- }
11026
11057
  function encodeBase64(value) {
11027
11058
  return Buffer.from(value, "utf8").toString("base64");
11028
11059
  }
11060
+ function encodeSmtpHeader(value) {
11061
+ if (/^[\x20-\x7e]{0,60}$/u.test(value))
11062
+ return value;
11063
+ const words = [];
11064
+ let part = "";
11065
+ for (const character of value) {
11066
+ if (Buffer.byteLength(part + character, "utf8") > 45) {
11067
+ words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
11068
+ part = "";
11069
+ }
11070
+ part += character;
11071
+ }
11072
+ if (part)
11073
+ words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
11074
+ return words.join(`\r
11075
+ `);
11076
+ }
11077
+ function smtpAddressHeader(value) {
11078
+ if (!value.includes("<"))
11079
+ return value;
11080
+ const name = value.slice(0, value.lastIndexOf("<")).trim();
11081
+ const address = smtpEnvelopeAddress(value, "address");
11082
+ if (!name)
11083
+ return address;
11084
+ const encoded = encodeSmtpHeader(name);
11085
+ const display = encoded.startsWith("=?UTF-8?B?") ? encoded : `"${encoded.replace(/[\\"]/gu, "\\$&")}"`;
11086
+ return `${display} <${address}>`;
11087
+ }
11088
+ function smtpMimePart(type, value) {
11089
+ const normalized = value.replace(/\r\n|\r|\n/gu, `\r
11090
+ `);
11091
+ const base64 = /[^\t\r\n\x20-\x7e]/u.test(normalized) || normalized.split(`\r
11092
+ `).some((line) => line.length > 998);
11093
+ return [
11094
+ `Content-Type: ${type}; charset=utf-8`,
11095
+ `Content-Transfer-Encoding: ${base64 ? "base64" : "7bit"}`,
11096
+ "",
11097
+ base64 ? (encodeBase64(normalized).match(/.{1,76}/gu) ?? []).join(`\r
11098
+ `) : normalized
11099
+ ];
11100
+ }
11101
+ function buildSmtpPayload(from, message) {
11102
+ const headers = [
11103
+ `From: ${smtpAddressHeader(assertSafeSmtpAddress(from, "from"))}`,
11104
+ `To: ${smtpAddressHeader(assertSafeSmtpAddress(message.to, "to"))}`,
11105
+ `Subject: ${encodeSmtpHeader(assertSafeSmtpField(message.subject, "subject"))}`,
11106
+ "MIME-Version: 1.0"
11107
+ ];
11108
+ let lines;
11109
+ if (message.html) {
11110
+ let boundary;
11111
+ do {
11112
+ boundary = `strata-${crypto.randomUUID()}`;
11113
+ } while (message.body.includes(boundary) || message.html.includes(boundary));
11114
+ lines = [
11115
+ ...headers,
11116
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
11117
+ "",
11118
+ `--${boundary}`,
11119
+ ...smtpMimePart("text/plain", message.body),
11120
+ `--${boundary}`,
11121
+ ...smtpMimePart("text/html", message.html),
11122
+ `--${boundary}--`,
11123
+ ""
11124
+ ];
11125
+ } else
11126
+ lines = [...headers, ...smtpMimePart("text/plain", message.body)];
11127
+ const content = lines.join(`\r
11128
+ `).replace(/(^|\r\n)\./gu, "$1..");
11129
+ return `${content}${content.endsWith(`\r
11130
+ `) ? "" : `\r
11131
+ `}.\r
11132
+ `;
11133
+ }
11134
+
11135
+ // ../../src/core/mail/mailer.ts
11136
+ function resolveSmtpConfig() {
11137
+ const host = process.env.MAIL_HOST?.trim();
11138
+ if (!host) {
11139
+ throw new Error('MAIL_DRIVER="smtp" requires MAIL_HOST to be set.');
11140
+ }
11141
+ const from = process.env.MAIL_FROM?.trim();
11142
+ if (!from) {
11143
+ throw new Error('MAIL_DRIVER="smtp" requires MAIL_FROM to be set.');
11144
+ }
11145
+ const port = Number(process.env.MAIL_PORT ?? "587");
11146
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
11147
+ throw new Error('Environment variable "MAIL_PORT" must be a positive integer.');
11148
+ }
11149
+ return {
11150
+ host,
11151
+ port,
11152
+ from,
11153
+ secure: (process.env.MAIL_SECURE ?? "false") === "true",
11154
+ ...process.env.MAIL_TIMEOUT_MS !== undefined ? { timeoutMs: smtpTimeout(Number(process.env.MAIL_TIMEOUT_MS)) } : {},
11155
+ ...process.env.MAIL_USERNAME?.trim() ? { username: process.env.MAIL_USERNAME.trim() } : {},
11156
+ ...process.env.MAIL_PASSWORD?.trim() ? { password: process.env.MAIL_PASSWORD.trim() } : {}
11157
+ };
11158
+ }
11159
+ function redactMailBody(body) {
11160
+ return body.replace(/https?:\/\/[^\s]+/giu, "[redacted-url]").replace(/[?&](token|signature|expires|code)=[^&\s]+/giu, "[redacted-query]");
11161
+ }
11029
11162
  function smtpTimeout(value = 1e4) {
11030
11163
  if (!Number.isSafeInteger(value) || value < 1 || value > 2147483647) {
11031
11164
  throw new RangeError("SMTP timeoutMs must be a positive integer within the timer range.");
@@ -11254,80 +11387,6 @@ async function defaultSmtpTransport(config, message) {
11254
11387
  socket?.end();
11255
11388
  }
11256
11389
  }
11257
- function encodeSmtpHeader(value) {
11258
- if (/^[\x20-\x7e]{0,60}$/u.test(value))
11259
- return value;
11260
- const words = [];
11261
- let part = "";
11262
- for (const character of value) {
11263
- if (Buffer.byteLength(part + character, "utf8") > 45) {
11264
- words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
11265
- part = "";
11266
- }
11267
- part += character;
11268
- }
11269
- if (part)
11270
- words.push(`=?UTF-8?B?${encodeBase64(part)}?=`);
11271
- return words.join(`\r
11272
- `);
11273
- }
11274
- function smtpAddressHeader(value) {
11275
- if (!value.includes("<"))
11276
- return value;
11277
- const name = value.slice(0, value.lastIndexOf("<")).trim();
11278
- const address = smtpEnvelopeAddress(value, "address");
11279
- if (!name)
11280
- return address;
11281
- const encoded = encodeSmtpHeader(name);
11282
- const display = encoded.startsWith("=?UTF-8?B?") ? encoded : `"${encoded.replace(/[\\"]/gu, "\\$&")}"`;
11283
- return `${display} <${address}>`;
11284
- }
11285
- function smtpMimePart(type, value) {
11286
- const normalized = value.replace(/\r\n|\r|\n/gu, `\r
11287
- `);
11288
- const base64 = /[^\t\r\n\x20-\x7e]/u.test(normalized) || normalized.split(`\r
11289
- `).some((line) => line.length > 998);
11290
- return [
11291
- `Content-Type: ${type}; charset=utf-8`,
11292
- `Content-Transfer-Encoding: ${base64 ? "base64" : "7bit"}`,
11293
- "",
11294
- base64 ? (encodeBase64(normalized).match(/.{1,76}/gu) ?? []).join(`\r
11295
- `) : normalized
11296
- ];
11297
- }
11298
- function buildSmtpPayload(from, message) {
11299
- const headers = [
11300
- `From: ${smtpAddressHeader(assertSafeSmtpAddress(from, "from"))}`,
11301
- `To: ${smtpAddressHeader(assertSafeSmtpAddress(message.to, "to"))}`,
11302
- `Subject: ${encodeSmtpHeader(assertSafeSmtpField(message.subject, "subject"))}`,
11303
- "MIME-Version: 1.0"
11304
- ];
11305
- let lines;
11306
- if (message.html) {
11307
- let boundary;
11308
- do {
11309
- boundary = `strata-${crypto.randomUUID()}`;
11310
- } while (message.body.includes(boundary) || message.html.includes(boundary));
11311
- lines = [
11312
- ...headers,
11313
- `Content-Type: multipart/alternative; boundary="${boundary}"`,
11314
- "",
11315
- `--${boundary}`,
11316
- ...smtpMimePart("text/plain", message.body),
11317
- `--${boundary}`,
11318
- ...smtpMimePart("text/html", message.html),
11319
- `--${boundary}--`,
11320
- ""
11321
- ];
11322
- } else
11323
- lines = [...headers, ...smtpMimePart("text/plain", message.body)];
11324
- const content = lines.join(`\r
11325
- `).replace(/(^|\r\n)\./gu, "$1..");
11326
- return `${content}${content.endsWith(`\r
11327
- `) ? "" : `\r
11328
- `}.\r
11329
- `;
11330
- }
11331
11390
 
11332
11391
  class LogMailDriver {
11333
11392
  async send(message) {
@@ -12853,16 +12912,16 @@ function isMethodRouteMap(value) {
12853
12912
  }
12854
12913
  function composeMiddleware(...middleware) {
12855
12914
  return (handler) => {
12856
- return async (request) => {
12915
+ return async (request, ...arguments_) => {
12857
12916
  let index = 0;
12858
12917
  const dispatch = async () => {
12859
12918
  if (index >= middleware.length) {
12860
- return await handler(request);
12919
+ return await handler(request, ...arguments_);
12861
12920
  }
12862
12921
  const current = middleware[index];
12863
12922
  index += 1;
12864
12923
  if (!current) {
12865
- return await handler(request);
12924
+ return await handler(request, ...arguments_);
12866
12925
  }
12867
12926
  return await current(request, dispatch);
12868
12927
  };
@@ -14751,6 +14810,143 @@ async function runQueueJob(envelope, failedJobs, options = {}) {
14751
14810
  // ../../src/core/queue/redisQueue.ts
14752
14811
  var {RedisClient: RedisClient4 } = globalThis.Bun;
14753
14812
 
14813
+ // ../../src/core/queue/redisListScripts.ts
14814
+ var SCRIPT_HEADER = `
14815
+ local function checkType(key, expected)
14816
+ local actual = redis.call('TYPE', key).ok
14817
+ if actual ~= 'none' and actual ~= expected then
14818
+ return redis.error_reply('Unexpected queue key type: ' .. key)
14819
+ end
14820
+ end
14821
+ local function nowMs()
14822
+ local time = redis.call('TIME')
14823
+ return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
14824
+ end
14825
+ `;
14826
+ var RESERVE_JOB = `${SCRIPT_HEADER}
14827
+ local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')
14828
+ if err then return err end
14829
+ local payload = redis.call('LINDEX', KEYS[1], -1)
14830
+ if not payload then return nil end
14831
+ local record = cjson.encode({strataReservation=1, id=ARGV[1], owner=ARGV[2], payload=payload})
14832
+ local lease = cjson.encode({owner=ARGV[2], expiresAt=nowMs()+tonumber(ARGV[3])})
14833
+ redis.call('LPUSH', KEYS[2], record)
14834
+ redis.call('HSET', KEYS[3], ARGV[1], lease)
14835
+ redis.call('RPOP', KEYS[1])
14836
+ return record
14837
+ `;
14838
+ var RENEW_OR_ACK = `${SCRIPT_HEADER}
14839
+ local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'hash') or checkType(KEYS[3], 'list')
14840
+ if err then return err end
14841
+ local raw = redis.call('HGET', KEYS[2], ARGV[1])
14842
+ if not raw then return 0 end
14843
+ local ok, lease = pcall(cjson.decode, raw)
14844
+ local now = nowMs()
14845
+ if not ok or type(lease) ~= 'table' or lease.owner ~= ARGV[2] or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now then
14846
+ return 0
14847
+ end
14848
+ if ARGV[4] == 'renew' then
14849
+ redis.call('HSET', KEYS[2], ARGV[1], cjson.encode({owner=ARGV[2], expiresAt=now+tonumber(ARGV[5])}))
14850
+ return 1
14851
+ end
14852
+ if ARGV[4] == 'quarantine' then redis.call('LPUSH', KEYS[3], ARGV[6]) end
14853
+ local removed = redis.call('LREM', KEYS[1], 1, ARGV[3])
14854
+ redis.call('HDEL', KEYS[2], ARGV[1])
14855
+ return removed
14856
+ `;
14857
+ var RECLAIM_JOBS = `${SCRIPT_HEADER}
14858
+ local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')
14859
+ if err then return err end
14860
+ local now = nowMs()
14861
+ local reclaimed = 0
14862
+ for _, record in ipairs(redis.call('LRANGE', KEYS[2], 0, -1)) do
14863
+ local payload, field = record, record
14864
+ local modern = false
14865
+ local ok, reservation = pcall(cjson.decode, record)
14866
+ if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then
14867
+ payload, field, modern = reservation.payload, reservation.id, true
14868
+ end
14869
+ local raw = redis.call('HGET', KEYS[3], field)
14870
+ local expired = true
14871
+ if raw then
14872
+ if modern then
14873
+ local leaseOk, lease = pcall(cjson.decode, raw)
14874
+ expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now
14875
+ else
14876
+ local reservedAt = tonumber(raw)
14877
+ expired = not reservedAt or now - reservedAt >= tonumber(ARGV[1])
14878
+ end
14879
+ end
14880
+ if expired then
14881
+ redis.call('LPUSH', KEYS[1], payload)
14882
+ redis.call('LREM', KEYS[2], 1, record)
14883
+ redis.call('HDEL', KEYS[3], field)
14884
+ reclaimed = reclaimed + 1
14885
+ end
14886
+ end
14887
+ return reclaimed
14888
+ `;
14889
+ var POLL_LIST_PRIORITIES = `${SCRIPT_HEADER}
14890
+ local owner = ARGV[1]
14891
+ local visibility = ARGV[2]
14892
+ local reservationId = ARGV[3]
14893
+ local reclaim = ARGV[4] == '1'
14894
+ local function reclaimQueue(listKey, processingKey, leaseKey)
14895
+ local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')
14896
+ if err then return err end
14897
+ local now = nowMs()
14898
+ for _, record in ipairs(redis.call('LRANGE', processingKey, 0, -1)) do
14899
+ local payload, field = record, record
14900
+ local modern = false
14901
+ local ok, reservation = pcall(cjson.decode, record)
14902
+ if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then
14903
+ payload, field, modern = reservation.payload, reservation.id, true
14904
+ end
14905
+ local raw = redis.call('HGET', leaseKey, field)
14906
+ local expired = true
14907
+ if raw then
14908
+ if modern then
14909
+ local leaseOk, lease = pcall(cjson.decode, raw)
14910
+ expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now
14911
+ else
14912
+ local reservedAt = tonumber(raw)
14913
+ expired = not reservedAt or now - reservedAt >= tonumber(visibility)
14914
+ end
14915
+ end
14916
+ if expired then
14917
+ redis.call('LPUSH', listKey, payload)
14918
+ redis.call('LREM', processingKey, 1, record)
14919
+ redis.call('HDEL', leaseKey, field)
14920
+ end
14921
+ end
14922
+ end
14923
+ local function reserveQueue(listKey, processingKey, leaseKey)
14924
+ local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')
14925
+ if err then return err end
14926
+ local payload = redis.call('LINDEX', listKey, -1)
14927
+ if not payload then return nil end
14928
+ local record = cjson.encode({strataReservation=1, id=reservationId, owner=owner, payload=payload})
14929
+ local lease = cjson.encode({owner=owner, expiresAt=nowMs()+tonumber(visibility)})
14930
+ redis.call('LPUSH', processingKey, record)
14931
+ redis.call('HSET', leaseKey, reservationId, lease)
14932
+ redis.call('RPOP', listKey)
14933
+ return record
14934
+ end
14935
+ local count = #KEYS / 3
14936
+ if reclaim then
14937
+ for i = 1, count do
14938
+ local err = reclaimQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])
14939
+ if err then return err end
14940
+ end
14941
+ end
14942
+ for i = 1, count do
14943
+ local record = reserveQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])
14944
+ if type(record) == 'string' then return {'1', tostring(i), record} end
14945
+ if record then return record end
14946
+ end
14947
+ return {'0'}
14948
+ `;
14949
+
14754
14950
  // ../../src/core/queue/redisQueueKeys.ts
14755
14951
  function queueListKey() {
14756
14952
  return namespacedRedisKey("queue:default");
@@ -14781,22 +14977,8 @@ function queueKeyForPriority(priority = "default") {
14781
14977
 
14782
14978
  // ../../src/core/queue/redisStreams.ts
14783
14979
  var {RedisClient: RedisClient3 } = globalThis.Bun;
14784
- var STREAM_GROUP = "strata-workers-v1";
14785
- function streamQueueKey(queueKey) {
14786
- return `${queueKey}:stream`;
14787
- }
14788
- function streamDeadLetterKey(queueKey) {
14789
- return `${streamQueueKey(queueKey)}:invalid`;
14790
- }
14791
- function streamRetryKey(queueKey) {
14792
- return `${streamQueueKey(queueKey)}:retries`;
14793
- }
14794
- function streamControlKey(key, jobId) {
14795
- const prefix = `${streamQueueKey(key)}/`;
14796
- if (!jobId.startsWith(prefix) || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(jobId.slice(prefix.length)))
14797
- throw new Error("Invalid cancellable Streams job ID");
14798
- return `${streamQueueKey(key)}:control:${jobId.slice(prefix.length)}`;
14799
- }
14980
+
14981
+ // ../../src/core/queue/redisStreamsScripts.ts
14800
14982
  var ENQUEUE_CONTROLLED = `
14801
14983
  local kind = redis.call('TYPE', KEYS[1]).ok
14802
14984
  if kind ~= 'none' and kind ~= 'stream' then return redis.error_reply('Invalid stream admission key type') end
@@ -14815,6 +14997,127 @@ if payload and redis.call('ZSCORE', KEYS[2], payload) then redis.call('ZADD', KE
14815
14997
  redis.call('HSET', KEYS[1], 'state', 'cancelled')
14816
14998
  return 1
14817
14999
  `;
15000
+ var SCHEDULE_RETRY = `
15001
+ local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
15002
+ if #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end
15003
+ local kind = redis.call('TYPE', KEYS[2]).ok
15004
+ if kind ~= 'none' and kind ~= 'zset' then return redis.error_reply('Invalid stream retry key type') end
15005
+ if ARGV[8] == '1' then
15006
+ local state = redis.call('HGET', KEYS[3], 'state')
15007
+ if state == 'cancelled' then return redis.error_reply('Streams job cancelled') end
15008
+ if state ~= 'active' then return redis.error_reply('Missing or invalid Streams control state') end
15009
+ end
15010
+ local now = redis.call('TIME')
15011
+ local due = tonumber(now[1])*1000 + math.floor(tonumber(now[2])/1000) + tonumber(ARGV[5])
15012
+ if ARGV[7] ~= '' then due = math.min(due, tonumber(ARGV[7])) end
15013
+ redis.call('ZADD', KEYS[2], due, ARGV[6])
15014
+ if ARGV[8] == '1' then redis.call('HSET', KEYS[3], 'retryPayload', ARGV[6]) end
15015
+ redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
15016
+ redis.call('XDEL', KEYS[1], ARGV[2])
15017
+ if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end
15018
+ return 1
15019
+ `;
15020
+ var POLL_STREAM_PRIORITIES = `
15021
+ local group = ARGV[1]
15022
+ local owner = ARGV[2]
15023
+ local visibility = ARGV[3]
15024
+ local function payloadOf(fields)
15025
+ for index = 1, #fields, 2 do
15026
+ if fields[index] == 'payload' and type(fields[index + 1]) == 'string' then return fields[index + 1] end
15027
+ end
15028
+ return ''
15029
+ end
15030
+ local cursors = {}
15031
+ for i = 1, #KEYS / 2 do cursors[i] = ARGV[3 + i] end
15032
+ for i = 1, #KEYS / 2 do
15033
+ local stream = KEYS[(i - 1) * 2 + 1]
15034
+ local retries = KEYS[(i - 1) * 2 + 2]
15035
+ local cursor = ARGV[3 + i]
15036
+ local streamKind = redis.call('TYPE', stream).ok
15037
+ local retryKind = redis.call('TYPE', retries).ok
15038
+ if streamKind ~= 'none' and streamKind ~= 'stream' then return redis.error_reply('Invalid stream retry promotion key type') end
15039
+ if retryKind ~= 'none' and retryKind ~= 'zset' then return redis.error_reply('Invalid stream retry promotion key type') end
15040
+ if streamKind == 'stream' then
15041
+ local now = redis.call('TIME')
15042
+ local due = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)
15043
+ local ready = redis.call('ZRANGE', retries, '-inf', due, 'BYSCORE', 'LIMIT', 0, 100)
15044
+ for _, payload in ipairs(ready) do
15045
+ redis.call('XADD', stream, '*', 'payload', payload)
15046
+ redis.call('ZREM', retries, payload)
15047
+ end
15048
+ local window = redis.call('XPENDING', stream, group, cursor, '+', 10)
15049
+ local claimed = redis.call('XAUTOCLAIM', stream, group, owner, visibility, cursor, 'COUNT', 1)
15050
+ for _, entry in ipairs(window) do
15051
+ if entry[2] ~= owner and #redis.call('XPENDING', stream, group, '-', '+', 1, entry[2]) == 0 then
15052
+ redis.call('XGROUP', 'DELCONSUMER', stream, group, entry[2])
15053
+ end
15054
+ end
15055
+ if #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then
15056
+ redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)
15057
+ end
15058
+ cursors[i] = claimed[1]
15059
+ if #claimed[2] > 0 then
15060
+ return {'1', tostring(i), claimed[2][1][1], payloadOf(claimed[2][1][2]), unpack(cursors)}
15061
+ end
15062
+ local fresh = redis.call('XREADGROUP', 'GROUP', group, owner, 'COUNT', 1, 'STREAMS', stream, '>')
15063
+ if not fresh and #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then
15064
+ redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)
15065
+ end
15066
+ if fresh and #fresh > 0 and #fresh[1][2] > 0 then
15067
+ return {'1', tostring(i), fresh[1][2][1][1], payloadOf(fresh[1][2][1][2]), unpack(cursors)}
15068
+ end
15069
+ end
15070
+ end
15071
+ return {'0', unpack(cursors)}
15072
+ `;
15073
+ var ASSERT_DRAINED = `
15074
+ if redis.call('LLEN', KEYS[1]) > 0 or redis.call('LLEN', KEYS[2]) > 0 or redis.call('HLEN', KEYS[3]) > 0 then
15075
+ return redis.error_reply('Legacy queue state requires maintenance conversion before Streams activation')
15076
+ end
15077
+ return 1
15078
+ `;
15079
+ var UPDATE_STREAM = `
15080
+ local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
15081
+ if #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end
15082
+ if ARGV[7] == '1' then
15083
+ local kind = redis.call('TYPE', KEYS[3]).ok
15084
+ if kind ~= 'none' and kind ~= 'hash' then return redis.error_reply('Invalid stream control key type') end
15085
+ end
15086
+ if ARGV[5] == 'renew' then
15087
+ local claimed = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[3], 0, ARGV[2], 'JUSTID')
15088
+ return #claimed
15089
+ end
15090
+ if ARGV[5] == 'quarantine' then
15091
+ local kind = redis.call('TYPE', KEYS[2]).ok
15092
+ if kind ~= 'none' and kind ~= 'stream' then return redis.error_reply('Invalid stream quarantine key type') end
15093
+ redis.call('XADD', KEYS[2], '*', 'sourceId', ARGV[2], 'payload', ARGV[6])
15094
+ end
15095
+ local acknowledged = redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
15096
+ if acknowledged == 1 then
15097
+ redis.call('XDEL', KEYS[1], ARGV[2])
15098
+ if ARGV[7] == '1' then redis.call('DEL', KEYS[3]) end
15099
+ end
15100
+ if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end
15101
+ return acknowledged
15102
+ `;
15103
+
15104
+ // ../../src/core/queue/redisStreams.ts
15105
+ var STREAM_GROUP = "strata-workers-v1";
15106
+ function streamQueueKey(queueKey) {
15107
+ return `${queueKey}:stream`;
15108
+ }
15109
+ function streamDeadLetterKey(queueKey) {
15110
+ return `${streamQueueKey(queueKey)}:invalid`;
15111
+ }
15112
+ function streamRetryKey(queueKey) {
15113
+ return `${streamQueueKey(queueKey)}:retries`;
15114
+ }
15115
+ function streamControlKey(key, jobId) {
15116
+ const prefix = `${streamQueueKey(key)}/`;
15117
+ if (!jobId.startsWith(prefix) || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(jobId.slice(prefix.length)))
15118
+ throw new Error("Invalid cancellable Streams job ID");
15119
+ return `${streamQueueKey(key)}:control:${jobId.slice(prefix.length)}`;
15120
+ }
14818
15121
  async function cancelStreamJob(client, key, jobId) {
14819
15122
  return Number(await client.send("EVAL", [
14820
15123
  CANCEL_STREAM,
@@ -14868,26 +15171,6 @@ function watchStreamDeadline(client, deadlineAtMs, remainingMs, expire, fail) {
14868
15171
  clearTimeout(timer);
14869
15172
  };
14870
15173
  }
14871
- var SCHEDULE_RETRY = `
14872
- local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
14873
- if #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end
14874
- local kind = redis.call('TYPE', KEYS[2]).ok
14875
- if kind ~= 'none' and kind ~= 'zset' then return redis.error_reply('Invalid stream retry key type') end
14876
- if ARGV[8] == '1' then
14877
- local state = redis.call('HGET', KEYS[3], 'state')
14878
- if state == 'cancelled' then return redis.error_reply('Streams job cancelled') end
14879
- if state ~= 'active' then return redis.error_reply('Missing or invalid Streams control state') end
14880
- end
14881
- local now = redis.call('TIME')
14882
- local due = tonumber(now[1])*1000 + math.floor(tonumber(now[2])/1000) + tonumber(ARGV[5])
14883
- if ARGV[7] ~= '' then due = math.min(due, tonumber(ARGV[7])) end
14884
- redis.call('ZADD', KEYS[2], due, ARGV[6])
14885
- if ARGV[8] == '1' then redis.call('HSET', KEYS[3], 'retryPayload', ARGV[6]) end
14886
- redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
14887
- redis.call('XDEL', KEYS[1], ARGV[2])
14888
- if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end
14889
- return 1
14890
- `;
14891
15174
  async function scheduleStreamRetry(client, key, reservation, envelope, delayMs) {
14892
15175
  if (!Number.isSafeInteger(delayMs) || delayMs < 0 || delayMs > Number.MAX_SAFE_INTEGER / 2)
14893
15176
  throw new Error("Invalid Streams retry delay");
@@ -14909,59 +15192,6 @@ async function scheduleStreamRetry(client, key, reservation, envelope, delayMs)
14909
15192
  if (Number(scheduled) !== 1)
14910
15193
  throw new Error("Queue lease lost while scheduling retry");
14911
15194
  }
14912
- var POLL_STREAM_PRIORITIES = `
14913
- local group = ARGV[1]
14914
- local owner = ARGV[2]
14915
- local visibility = ARGV[3]
14916
- local function payloadOf(fields)
14917
- for index = 1, #fields, 2 do
14918
- if fields[index] == 'payload' and type(fields[index + 1]) == 'string' then return fields[index + 1] end
14919
- end
14920
- return ''
14921
- end
14922
- local cursors = {}
14923
- for i = 1, #KEYS / 2 do cursors[i] = ARGV[3 + i] end
14924
- for i = 1, #KEYS / 2 do
14925
- local stream = KEYS[(i - 1) * 2 + 1]
14926
- local retries = KEYS[(i - 1) * 2 + 2]
14927
- local cursor = ARGV[3 + i]
14928
- local streamKind = redis.call('TYPE', stream).ok
14929
- local retryKind = redis.call('TYPE', retries).ok
14930
- if streamKind ~= 'none' and streamKind ~= 'stream' then return redis.error_reply('Invalid stream retry promotion key type') end
14931
- if retryKind ~= 'none' and retryKind ~= 'zset' then return redis.error_reply('Invalid stream retry promotion key type') end
14932
- if streamKind == 'stream' then
14933
- local now = redis.call('TIME')
14934
- local due = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)
14935
- local ready = redis.call('ZRANGE', retries, '-inf', due, 'BYSCORE', 'LIMIT', 0, 100)
14936
- for _, payload in ipairs(ready) do
14937
- redis.call('XADD', stream, '*', 'payload', payload)
14938
- redis.call('ZREM', retries, payload)
14939
- end
14940
- local window = redis.call('XPENDING', stream, group, cursor, '+', 10)
14941
- local claimed = redis.call('XAUTOCLAIM', stream, group, owner, visibility, cursor, 'COUNT', 1)
14942
- for _, entry in ipairs(window) do
14943
- if entry[2] ~= owner and #redis.call('XPENDING', stream, group, '-', '+', 1, entry[2]) == 0 then
14944
- redis.call('XGROUP', 'DELCONSUMER', stream, group, entry[2])
14945
- end
14946
- end
14947
- if #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then
14948
- redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)
14949
- end
14950
- cursors[i] = claimed[1]
14951
- if #claimed[2] > 0 then
14952
- return {'1', tostring(i), claimed[2][1][1], payloadOf(claimed[2][1][2]), unpack(cursors)}
14953
- end
14954
- local fresh = redis.call('XREADGROUP', 'GROUP', group, owner, 'COUNT', 1, 'STREAMS', stream, '>')
14955
- if not fresh and #redis.call('XPENDING', stream, group, '-', '+', 1, owner) == 0 then
14956
- redis.call('XGROUP', 'DELCONSUMER', stream, group, owner)
14957
- end
14958
- if fresh and #fresh > 0 and #fresh[1][2] > 0 then
14959
- return {'1', tostring(i), fresh[1][2][1][1], payloadOf(fresh[1][2][1][2]), unpack(cursors)}
14960
- end
14961
- end
14962
- end
14963
- return {'0', unpack(cursors)}
14964
- `;
14965
15195
  async function pollStreamPriorities(client, queueKeys, owner, cursors) {
14966
15196
  const keys = [];
14967
15197
  for (const key of queueKeys)
@@ -15005,12 +15235,6 @@ async function readStreamQueueDepth(client, key) {
15005
15235
  streamRetryKey(key)
15006
15236
  ]));
15007
15237
  }
15008
- var ASSERT_DRAINED = `
15009
- if redis.call('LLEN', KEYS[1]) > 0 or redis.call('LLEN', KEYS[2]) > 0 or redis.call('HLEN', KEYS[3]) > 0 then
15010
- return redis.error_reply('Legacy queue state requires maintenance conversion before Streams activation')
15011
- end
15012
- return 1
15013
- `;
15014
15238
  async function assertLegacyDrained(client, key) {
15015
15239
  await client.send("EVAL", [
15016
15240
  ASSERT_DRAINED,
@@ -15020,30 +15244,6 @@ async function assertLegacyDrained(client, key) {
15020
15244
  `${key}:processing:leases`
15021
15245
  ]);
15022
15246
  }
15023
- var UPDATE_STREAM = `
15024
- local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
15025
- if #pending == 0 or pending[1][2] ~= ARGV[3] or tonumber(pending[1][3]) >= tonumber(ARGV[4]) then return 0 end
15026
- if ARGV[7] == '1' then
15027
- local kind = redis.call('TYPE', KEYS[3]).ok
15028
- if kind ~= 'none' and kind ~= 'hash' then return redis.error_reply('Invalid stream control key type') end
15029
- end
15030
- if ARGV[5] == 'renew' then
15031
- local claimed = redis.call('XCLAIM', KEYS[1], ARGV[1], ARGV[3], 0, ARGV[2], 'JUSTID')
15032
- return #claimed
15033
- end
15034
- if ARGV[5] == 'quarantine' then
15035
- local kind = redis.call('TYPE', KEYS[2]).ok
15036
- if kind ~= 'none' and kind ~= 'stream' then return redis.error_reply('Invalid stream quarantine key type') end
15037
- redis.call('XADD', KEYS[2], '*', 'sourceId', ARGV[2], 'payload', ARGV[6])
15038
- end
15039
- local acknowledged = redis.call('XACK', KEYS[1], ARGV[1], ARGV[2])
15040
- if acknowledged == 1 then
15041
- redis.call('XDEL', KEYS[1], ARGV[2])
15042
- if ARGV[7] == '1' then redis.call('DEL', KEYS[3]) end
15043
- end
15044
- if #redis.call('XPENDING', KEYS[1], ARGV[1], '-', '+', 1, ARGV[3]) == 0 then redis.call('XGROUP', 'DELCONSUMER', KEYS[1], ARGV[1], ARGV[3]) end
15045
- return acknowledged
15046
- `;
15047
15247
  async function ensureStreamGroup(client, key) {
15048
15248
  await assertLegacyDrained(client, key);
15049
15249
  try {
@@ -15361,141 +15561,6 @@ function queueProcessingKey(queueKey) {
15361
15561
  function queueProcessingLeaseKey(queueKey) {
15362
15562
  return `${queueKey}:processing:leases`;
15363
15563
  }
15364
- var SCRIPT_HEADER = `
15365
- local function checkType(key, expected)
15366
- local actual = redis.call('TYPE', key).ok
15367
- if actual ~= 'none' and actual ~= expected then
15368
- return redis.error_reply('Unexpected queue key type: ' .. key)
15369
- end
15370
- end
15371
- local function nowMs()
15372
- local time = redis.call('TIME')
15373
- return tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
15374
- end
15375
- `;
15376
- var RESERVE_JOB = `${SCRIPT_HEADER}
15377
- local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')
15378
- if err then return err end
15379
- local payload = redis.call('LINDEX', KEYS[1], -1)
15380
- if not payload then return nil end
15381
- local record = cjson.encode({strataReservation=1, id=ARGV[1], owner=ARGV[2], payload=payload})
15382
- local lease = cjson.encode({owner=ARGV[2], expiresAt=nowMs()+tonumber(ARGV[3])})
15383
- redis.call('LPUSH', KEYS[2], record)
15384
- redis.call('HSET', KEYS[3], ARGV[1], lease)
15385
- redis.call('RPOP', KEYS[1])
15386
- return record
15387
- `;
15388
- var RENEW_OR_ACK = `${SCRIPT_HEADER}
15389
- local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'hash') or checkType(KEYS[3], 'list')
15390
- if err then return err end
15391
- local raw = redis.call('HGET', KEYS[2], ARGV[1])
15392
- if not raw then return 0 end
15393
- local ok, lease = pcall(cjson.decode, raw)
15394
- local now = nowMs()
15395
- if not ok or type(lease) ~= 'table' or lease.owner ~= ARGV[2] or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now then
15396
- return 0
15397
- end
15398
- if ARGV[4] == 'renew' then
15399
- redis.call('HSET', KEYS[2], ARGV[1], cjson.encode({owner=ARGV[2], expiresAt=now+tonumber(ARGV[5])}))
15400
- return 1
15401
- end
15402
- if ARGV[4] == 'quarantine' then redis.call('LPUSH', KEYS[3], ARGV[6]) end
15403
- local removed = redis.call('LREM', KEYS[1], 1, ARGV[3])
15404
- redis.call('HDEL', KEYS[2], ARGV[1])
15405
- return removed
15406
- `;
15407
- var RECLAIM_JOBS = `${SCRIPT_HEADER}
15408
- local err = checkType(KEYS[1], 'list') or checkType(KEYS[2], 'list') or checkType(KEYS[3], 'hash')
15409
- if err then return err end
15410
- local now = nowMs()
15411
- local reclaimed = 0
15412
- for _, record in ipairs(redis.call('LRANGE', KEYS[2], 0, -1)) do
15413
- local payload, field = record, record
15414
- local modern = false
15415
- local ok, reservation = pcall(cjson.decode, record)
15416
- if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then
15417
- payload, field, modern = reservation.payload, reservation.id, true
15418
- end
15419
- local raw = redis.call('HGET', KEYS[3], field)
15420
- local expired = true
15421
- if raw then
15422
- if modern then
15423
- local leaseOk, lease = pcall(cjson.decode, raw)
15424
- expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now
15425
- else
15426
- local reservedAt = tonumber(raw)
15427
- expired = not reservedAt or now - reservedAt >= tonumber(ARGV[1])
15428
- end
15429
- end
15430
- if expired then
15431
- redis.call('LPUSH', KEYS[1], payload)
15432
- redis.call('LREM', KEYS[2], 1, record)
15433
- redis.call('HDEL', KEYS[3], field)
15434
- reclaimed = reclaimed + 1
15435
- end
15436
- end
15437
- return reclaimed
15438
- `;
15439
- var POLL_LIST_PRIORITIES = `${SCRIPT_HEADER}
15440
- local owner = ARGV[1]
15441
- local visibility = ARGV[2]
15442
- local reservationId = ARGV[3]
15443
- local reclaim = ARGV[4] == '1'
15444
- local function reclaimQueue(listKey, processingKey, leaseKey)
15445
- local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')
15446
- if err then return err end
15447
- local now = nowMs()
15448
- for _, record in ipairs(redis.call('LRANGE', processingKey, 0, -1)) do
15449
- local payload, field = record, record
15450
- local modern = false
15451
- local ok, reservation = pcall(cjson.decode, record)
15452
- if ok and type(reservation) == 'table' and reservation.strataReservation == 1 then
15453
- payload, field, modern = reservation.payload, reservation.id, true
15454
- end
15455
- local raw = redis.call('HGET', leaseKey, field)
15456
- local expired = true
15457
- if raw then
15458
- if modern then
15459
- local leaseOk, lease = pcall(cjson.decode, raw)
15460
- expired = not leaseOk or type(lease) ~= 'table' or not tonumber(lease.expiresAt) or tonumber(lease.expiresAt) <= now
15461
- else
15462
- local reservedAt = tonumber(raw)
15463
- expired = not reservedAt or now - reservedAt >= tonumber(visibility)
15464
- end
15465
- end
15466
- if expired then
15467
- redis.call('LPUSH', listKey, payload)
15468
- redis.call('LREM', processingKey, 1, record)
15469
- redis.call('HDEL', leaseKey, field)
15470
- end
15471
- end
15472
- end
15473
- local function reserveQueue(listKey, processingKey, leaseKey)
15474
- local err = checkType(listKey, 'list') or checkType(processingKey, 'list') or checkType(leaseKey, 'hash')
15475
- if err then return err end
15476
- local payload = redis.call('LINDEX', listKey, -1)
15477
- if not payload then return nil end
15478
- local record = cjson.encode({strataReservation=1, id=reservationId, owner=owner, payload=payload})
15479
- local lease = cjson.encode({owner=owner, expiresAt=nowMs()+tonumber(visibility)})
15480
- redis.call('LPUSH', processingKey, record)
15481
- redis.call('HSET', leaseKey, reservationId, lease)
15482
- redis.call('RPOP', listKey)
15483
- return record
15484
- end
15485
- local count = #KEYS / 3
15486
- if reclaim then
15487
- for i = 1, count do
15488
- local err = reclaimQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])
15489
- if err then return err end
15490
- end
15491
- end
15492
- for i = 1, count do
15493
- local record = reserveQueue(KEYS[(i - 1) * 3 + 1], KEYS[(i - 1) * 3 + 2], KEYS[(i - 1) * 3 + 3])
15494
- if type(record) == 'string' then return {'1', tostring(i), record} end
15495
- if record then return record end
15496
- end
15497
- return {'0'}
15498
- `;
15499
15564
  function queueInvalidKey(queueKey) {
15500
15565
  return `${queueKey}:invalid`;
15501
15566
  }
@@ -15801,6 +15866,8 @@ import { createHash as createHash7 } from "crypto";
15801
15866
  // ../../src/core/scheduler/leases.ts
15802
15867
  import { createHash as createHash6 } from "crypto";
15803
15868
  var {RedisClient: RedisClient6 } = globalThis.Bun;
15869
+
15870
+ // ../../src/core/scheduler/leaseScript.ts
15804
15871
  var LEASE_SCRIPT = `
15805
15872
  for _, key in ipairs(KEYS) do
15806
15873
  local kind = redis.call('TYPE', key).ok
@@ -15828,6 +15895,7 @@ else return redis.error_reply('Unexpected scheduler action') end
15828
15895
  return 1
15829
15896
  `;
15830
15897
 
15898
+ // ../../src/core/scheduler/leases.ts
15831
15899
  class RedisSchedulerLeaseStore {
15832
15900
  client;
15833
15901
  owned;
@@ -17175,7 +17243,7 @@ export {
17175
17243
  LogMailDriver,
17176
17244
  MAX_PER_PAGE,
17177
17245
  Mailer,
17178
- membershipService_default as MembershipService,
17246
+ membershipServiceImplementation_default as MembershipService,
17179
17247
  Model,
17180
17248
  ModelQuery,
17181
17249
  MorphManyRelationQuery,