@getstrata/core 2.2.51 → 2.2.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4281,6 +4281,42 @@ function buildSelectQuery(table, options = {}, whereNodes = []) {
4281
4281
  params
4282
4282
  };
4283
4283
  }
4284
+ var EAGER_ROW_NUMBER = "__strata_eager_row_number";
4285
+ function buildLimitedRelationQuery(table, options, partition, source) {
4286
+ if (options.lock || options.groupBy?.length || options.having) {
4287
+ throw new Error("Limited eager relations do not support row locks, grouping or HAVING.");
4288
+ }
4289
+ if (table.columns.includes(EAGER_ROW_NUMBER) || options.select?.some((item) => ("as" in item) && item.as === EAGER_ROW_NUMBER)) {
4290
+ throw new Error(`Reserved eager relation column: ${EAGER_ROW_NUMBER}`);
4291
+ }
4292
+ buildLimitClause(options.limit);
4293
+ buildOffsetClause(options.offset);
4294
+ if (!Number.isSafeInteger((options.offset ?? 0) + (options.limit ?? 0))) {
4295
+ throw new Error("Limited eager relation bounds must fit a safe integer.");
4296
+ }
4297
+ const order = [...normalizeOrderBy(options.orderBy ?? table.defaultOrderBy)];
4298
+ if (!order.some((item) => item.column === table.primaryKey || item.column === `${table.name}.${table.primaryKey}`)) {
4299
+ order.push({ column: table.primaryKey, direction: "ASC" });
4300
+ }
4301
+ const ordering = buildOrderByClause(table.name, order);
4302
+ const params = [];
4303
+ const columns = buildSelectList(table, options.select, params);
4304
+ const rank = `ROW_NUMBER() OVER (PARTITION BY ${qualifyColumn(partition.table, partition.column)}${ordering}) AS ${quoteIdentifier(EAGER_ROW_NUMBER)}`;
4305
+ const sql = source(columns, rank, params);
4306
+ const offset = options.offset ?? 0;
4307
+ const upper = options.limit === undefined ? "" : ` AND ${quoteIdentifier(EAGER_ROW_NUMBER)} <= ${offset + options.limit}`;
4308
+ return {
4309
+ text: `SELECT * FROM (${sql}) AS ${quoteIdentifier("__strata_eager")} WHERE ${quoteIdentifier(EAGER_ROW_NUMBER)} > ${offset}${upper} ORDER BY ${quoteIdentifier(EAGER_ROW_NUMBER)}`,
4310
+ params
4311
+ };
4312
+ }
4313
+ function buildLimitedHasManyQuery(table, options, partition) {
4314
+ return buildLimitedRelationQuery(table, options, partition, (columns, rank, params) => {
4315
+ const { clause } = buildQueryWhereClause(table, options, options.whereNodes, params);
4316
+ const owner = partition.ownerAlias ? `, ${qualifyColumn(partition.table, partition.column)} AS ${quoteIdentifier(partition.ownerAlias)}` : "";
4317
+ return `SELECT ${columns}${owner}, ${rank} FROM ${quoteIdentifier(table.name)}${buildJoinClause(options.joins)}${clause}`;
4318
+ });
4319
+ }
4284
4320
  function buildCountQuery(table, where = {}, options = {}, whereNodes = []) {
4285
4321
  const params = [];
4286
4322
  const { clause, params: whereParams } = buildQueryWhereClause(table, {
@@ -4516,6 +4552,17 @@ function buildThroughWhere(table, options, parentIds) {
4516
4552
  function buildHasManyThroughQuery(table, relation, parentIds, options) {
4517
4553
  const throughParentKey = relation.throughParentKey ?? "__through_parent_id";
4518
4554
  const farTable = table.name;
4555
+ if (options.limit !== undefined || options.offset !== undefined) {
4556
+ return buildLimitedRelationQuery(table, options, { table: relation.throughTable, column: relation.firstKey }, (columns, rank, params) => {
4557
+ const placeholders = parentIds.map((id) => {
4558
+ params.push(id);
4559
+ return currentSqlDialect().placeholder(params.length);
4560
+ }).join(", ");
4561
+ const { clause } = buildQueryWhereClause(table, options, options.whereNodes, params);
4562
+ const extra = clause ? ` AND (${clause.replace(/^ WHERE /, "")})` : "";
4563
+ return `SELECT ${columns}, ${qualifyColumn(relation.throughTable, relation.firstKey)} AS ${quoteIdentifier(throughParentKey)}, ${rank} 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})${extra}`;
4564
+ });
4565
+ }
4519
4566
  const columns = table.columns.map((column) => `${qualifyColumn(farTable, column)}`).join(", ");
4520
4567
  const placeholders = parentIds.map((_, index) => currentSqlDialect().placeholder(index + 1)).join(", ");
4521
4568
  const { text: extraWhere, params: extraParams } = buildThroughWhere(table, options, parentIds);
@@ -5102,11 +5149,12 @@ class RepositoryQuery {
5102
5149
  return await this.attach(rows);
5103
5150
  }
5104
5151
  async paginate(options) {
5105
- return await this.repository.paginate({
5152
+ const page = await this.repository.paginate({
5106
5153
  ...this.buildOptions(),
5107
5154
  page: options.page,
5108
5155
  perPage: options.perPage
5109
5156
  });
5157
+ return { ...page, data: await this.attach(page.data) };
5110
5158
  }
5111
5159
  async chunk(count, callback) {
5112
5160
  await this.repository.chunk(count, async (rows) => callback(await this.attach(rows)), this.buildOptions());
@@ -5275,6 +5323,7 @@ function readOrder(order) {
5275
5323
  ...order.nulls === undefined ? {} : { nulls: order.nulls }
5276
5324
  };
5277
5325
  }
5326
+ var RELATION_WINDOW = Symbol("relationWindow");
5278
5327
 
5279
5328
  class BaseRepository {
5280
5329
  table;
@@ -5331,9 +5380,17 @@ class BaseRepository {
5331
5380
  if (options.lock && (!hasActiveTransaction() || this.connection !== repositoryConnection && !isActiveTransactionConnection(this.connection))) {
5332
5381
  throw new Error("Row locks require the framework active transaction connection.");
5333
5382
  }
5334
- const { whereNodes, ...queryOptions } = options;
5335
- const { text, params } = buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
5336
- return await this.connection.unsafe(text, params);
5383
+ const {
5384
+ whereNodes,
5385
+ [RELATION_WINDOW]: window,
5386
+ ...queryOptions
5387
+ } = options;
5388
+ const { text, params } = window ? buildLimitedHasManyQuery(this.table, { ...queryOptions, whereNodes }, window) : buildSelectQuery(this.table, queryOptions, whereNodes ?? []);
5389
+ const rows = await this.connection.unsafe(text, params);
5390
+ if (window)
5391
+ for (const row of rows)
5392
+ delete row[EAGER_ROW_NUMBER];
5393
+ return rows;
5337
5394
  });
5338
5395
  }
5339
5396
  async paginate(options) {
@@ -5819,9 +5876,8 @@ class BaseRepository {
5819
5876
  return indexHasManyRelation(parents, [], relation);
5820
5877
  }
5821
5878
  const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
5822
- const children = await this.findWhere({
5823
- [relation.foreignKey]: parentIds
5824
- }, options);
5879
+ const where = { [relation.foreignKey]: parentIds };
5880
+ const children = await this.findRelationRows(where, options, relation.foreignKey);
5825
5881
  return indexHasManyRelation(parents, children, relation);
5826
5882
  }
5827
5883
  async findHasManyThrough(parentId, relation, options = {}) {
@@ -5838,6 +5894,8 @@ class BaseRepository {
5838
5894
  const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
5839
5895
  const { text, params } = buildHasManyThroughQuery(this.table, relation, parentIds, options);
5840
5896
  const children = await this.connection.unsafe(text, params);
5897
+ for (const child of children)
5898
+ delete child[EAGER_ROW_NUMBER];
5841
5899
  return indexHasManyThroughRelation(parents, children, relation);
5842
5900
  }
5843
5901
  async loadBelongsToForParents(children, relation, parentRepository, options = {}) {
@@ -5855,12 +5913,21 @@ class BaseRepository {
5855
5913
  return indexMorphManyRelation(parents, [], relation);
5856
5914
  }
5857
5915
  const parentIds = [...new Set(parents.map((parent) => parent[relation.localKey]))];
5858
- const children = await this.findWhere({
5916
+ const children = await this.findRelationRows({
5859
5917
  [relation.morphTypeKey]: relation.morphType,
5860
5918
  [relation.morphIdKey]: parentIds
5861
- }, options);
5919
+ }, options, relation.morphIdKey);
5862
5920
  return indexMorphManyRelation(parents, children, relation);
5863
5921
  }
5922
+ async findRelationRows(where, options, foreignKey) {
5923
+ if (options.limit === undefined && options.offset === undefined)
5924
+ return this.findWhere(where, options);
5925
+ const bounded = {
5926
+ ...options,
5927
+ [RELATION_WINDOW]: { table: this.table.name, column: foreignKey }
5928
+ };
5929
+ return this.findWhere(where, bounded);
5930
+ }
5864
5931
  async loadMorphOneForParents(parents, relation, options = {}) {
5865
5932
  const grouped = await this.loadMorphManyForParents(parents, relation, options);
5866
5933
  const result = new Map;
@@ -5913,9 +5980,53 @@ class BaseRepository {
5913
5980
  const relatedIds = [
5914
5981
  ...new Set(pivotRows.map((row) => row[relation.relatedPivotKey]))
5915
5982
  ];
5983
+ const limited = options.limit !== undefined || options.offset !== undefined;
5984
+ const ownerAlias = "__strata_pivot_parent_id";
5985
+ const bounded = limited ? {
5986
+ ...options,
5987
+ joins: [
5988
+ ...options.joins ?? [],
5989
+ {
5990
+ type: "inner",
5991
+ table: relation.pivotTable,
5992
+ on: [
5993
+ {
5994
+ left: { table: relatedRepository.table.name, column: relation.relatedKey },
5995
+ right: { table: relation.pivotTable, column: relation.relatedPivotKey }
5996
+ }
5997
+ ]
5998
+ }
5999
+ ],
6000
+ whereNodes: [
6001
+ ...options.whereNodes ?? [],
6002
+ {
6003
+ kind: "and",
6004
+ where: {
6005
+ [`${relation.pivotTable}.${relation.foreignPivotKey}`]: parentIds
6006
+ }
6007
+ }
6008
+ ],
6009
+ [RELATION_WINDOW]: {
6010
+ table: relation.pivotTable,
6011
+ column: relation.foreignPivotKey,
6012
+ ownerAlias
6013
+ }
6014
+ } : options;
5916
6015
  const relatedRows = await relatedRepository.withConnection(this.connection).findWhere({
5917
6016
  [relation.relatedKey]: relatedIds
5918
- }, options);
6017
+ }, bounded);
6018
+ if (limited) {
6019
+ return indexHasManyThroughRelation(parents, relatedRows, {
6020
+ type: "hasManyThrough",
6021
+ name: relation.name,
6022
+ localKey: relation.parentKey,
6023
+ throughTable: relation.pivotTable,
6024
+ firstKey: relation.foreignPivotKey,
6025
+ secondLocalKey: relation.relatedPivotKey,
6026
+ secondKey: relation.relatedKey,
6027
+ throughParentKey: ownerAlias
6028
+ });
6029
+ }
5919
6030
  return indexBelongsToManyRelation(parents, pivotRows, relatedRows, relation);
5920
6031
  }
5921
6032
  }
@@ -6457,22 +6568,33 @@ class SimpleCache {
6457
6568
  this.evictOverflow();
6458
6569
  }
6459
6570
  async getOrSet(key, loader, ttlMs) {
6571
+ return this.getOrSetTagged(key, loader, [], ttlMs);
6572
+ }
6573
+ async getOrSetTagged(key, loader, tags, ttlMs) {
6460
6574
  this.pruneExpired();
6461
6575
  const cachedEntry = this.getFreshEntry(key);
6462
6576
  if (cachedEntry) {
6577
+ this.attachTags(key, tags);
6463
6578
  return cachedEntry.value;
6464
6579
  }
6465
6580
  const inflightRequest = this.inflight.get(key);
6466
6581
  if (inflightRequest) {
6582
+ this.attachTags(key, tags);
6467
6583
  return inflightRequest;
6468
6584
  }
6469
- const pendingRequest = loader().then((value) => {
6470
- this.set(key, value, ttlMs);
6585
+ const pendingRequest = Promise.resolve().then(loader).then((value) => {
6586
+ if (this.inflight.get(key) === pendingRequest)
6587
+ this.set(key, value, ttlMs);
6471
6588
  return value;
6472
6589
  }).finally(() => {
6473
- this.inflight.delete(key);
6590
+ if (this.inflight.get(key) === pendingRequest) {
6591
+ this.inflight.delete(key);
6592
+ if (!this.cache.has(key))
6593
+ this.detachKeyFromTags(key);
6594
+ }
6474
6595
  });
6475
6596
  this.inflight.set(key, pendingRequest);
6597
+ this.attachTags(key, tags);
6476
6598
  return pendingRequest;
6477
6599
  }
6478
6600
  attachTags(key, tags) {
@@ -6518,14 +6640,13 @@ class SimpleCache {
6518
6640
  }
6519
6641
  invalidate(key) {
6520
6642
  const removed = this.cache.delete(key);
6521
- if (removed) {
6522
- this.detachKeyFromTags(key);
6523
- }
6643
+ this.inflight.delete(key);
6644
+ this.detachKeyFromTags(key);
6524
6645
  return removed;
6525
6646
  }
6526
6647
  invalidateByPrefix(prefix) {
6527
6648
  let removed = 0;
6528
- for (const key of [...this.cache.keys()]) {
6649
+ for (const key of new Set([...this.cache.keys(), ...this.inflight.keys()])) {
6529
6650
  if (key === prefix || key.startsWith(`${prefix}?`)) {
6530
6651
  if (this.invalidate(key)) {
6531
6652
  removed += 1;
@@ -6616,6 +6737,9 @@ class SimpleCacheStore {
6616
6737
  getOrSet(key, loader, ttlMs) {
6617
6738
  return this.cache.getOrSet(key, loader, ttlMs);
6618
6739
  }
6740
+ getOrSetTagged(key, loader, tags, ttlMs) {
6741
+ return this.cache.getOrSetTagged(key, loader, tags, ttlMs);
6742
+ }
6619
6743
  attachTags(key, tags) {
6620
6744
  this.cache.attachTags(key, tags);
6621
6745
  return Promise.resolve();
@@ -9655,13 +9779,24 @@ class Model {
9655
9779
  const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
9656
9780
  const payload = await statics.dehydrateAttributes(withTimestamps);
9657
9781
  const pending = statics.newFromRecord({ ...payload }, false);
9782
+ const beforeObservers = snapshotAttributes(pending.attributes);
9658
9783
  if (await runObservers(pending, "saving") === false) {
9659
9784
  throw new Error(`${this.name}.create() was cancelled by an observer.`);
9660
9785
  }
9661
9786
  if (await runObservers(pending, "creating") === false) {
9662
9787
  throw new Error(`${this.name}.create() was cancelled by an observer.`);
9663
9788
  }
9664
- const record = await repository.create(payload);
9789
+ const edits = changedAttributes(pending.attributes, beforeObservers);
9790
+ const forcedKeys = new Set(Object.keys(forced));
9791
+ for (const key of forcedKeys)
9792
+ delete edits[key];
9793
+ let finalPayload = payload;
9794
+ if (Object.keys(edits).length > 0) {
9795
+ const changed = await statics.dehydrateAttributes(edits);
9796
+ const writeEdits = Object.fromEntries(Object.entries(changed).filter(([key]) => !forcedKeys.has(key)));
9797
+ finalPayload = { ...payload, ...writeEdits };
9798
+ }
9799
+ const record = await repository.create(finalPayload);
9665
9800
  const created = statics.fromRecord(record, repository, true);
9666
9801
  await runObservers(created, "created");
9667
9802
  await runObservers(created, "saved");
@@ -11707,6 +11842,10 @@ function currentRequestMeta() {
11707
11842
  userAgent: null
11708
11843
  };
11709
11844
  }
11845
+ function resolveRequestId(request) {
11846
+ const meta = currentRequestMeta();
11847
+ return (meta.request === request ? meta.requestId : undefined) ?? request.headers.get("x-request-id") ?? crypto.randomUUID();
11848
+ }
11710
11849
 
11711
11850
  // ../../src/core/http/safeInternalPath.ts
11712
11851
  var NESTED_REDIRECT_KEYS = new Set(["redirect", "next", "return", "returnTo", "return_to"]);
@@ -12974,8 +13113,8 @@ function composeMiddleware(...middleware) {
12974
13113
  };
12975
13114
  }
12976
13115
  async function requestIdMiddleware(request, next) {
12977
- const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
12978
- const response = await next();
13116
+ const requestId = resolveRequestId(request);
13117
+ const response = await runWithRequestMeta({ ...currentRequestMeta(), request, requestId }, next);
12979
13118
  const headers = new Headers(response.headers);
12980
13119
  headers.set("x-request-id", requestId);
12981
13120
  return new Response(response.body, {
@@ -14296,14 +14435,15 @@ function resetGracefulShutdownForTests() {
14296
14435
  function createRequestLoggingMiddleware() {
14297
14436
  return async (request, next) => {
14298
14437
  const ipAddress = readClientIp(request) ?? null;
14438
+ const requestId = resolveRequestId(request);
14299
14439
  return await runWithRequestMeta({
14300
14440
  ...currentRequestMeta(),
14301
14441
  ipAddress,
14302
14442
  userAgent: request.headers.get("user-agent"),
14303
- request
14443
+ request,
14444
+ requestId
14304
14445
  }, async () => {
14305
14446
  const startedAt = performance.now();
14306
- const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
14307
14447
  const response = await next();
14308
14448
  const durationMs = Math.round(performance.now() - startedAt);
14309
14449
  appLogger.info("HTTP request completed", {
@@ -14515,6 +14655,9 @@ class Notification {
14515
14655
  init_dialect();
14516
14656
  init_repositoryConnection();
14517
14657
 
14658
+ // ../../src/core/queue/failedJobRepository.ts
14659
+ init_dialect();
14660
+
14518
14661
  // ../../src/core/queue/failedJobTable.ts
14519
14662
  var failedJobTable = defineTable({
14520
14663
  name: "failed_job",
@@ -14528,6 +14671,27 @@ class FailedJobRepository extends BaseRepository {
14528
14671
  constructor() {
14529
14672
  super(failedJobTable);
14530
14673
  }
14674
+ async create(values) {
14675
+ const stored = {
14676
+ ...values,
14677
+ ...values.payload === undefined ? {} : { payload: JSON.stringify(values.payload) },
14678
+ ...values.failed_at === undefined ? {} : { failed_at: sqlTimestamp(values.failed_at) }
14679
+ };
14680
+ return hydrateFailure(await super.create(stored));
14681
+ }
14682
+ async findAll(options = {}) {
14683
+ const rows = await super.findAll(options);
14684
+ return options.select?.length ? rows : rows.map(hydrateFailure);
14685
+ }
14686
+ }
14687
+ function hydrateFailure(row) {
14688
+ const result = { ...row };
14689
+ if (typeof row.payload === "string")
14690
+ result.payload = JSON.parse(row.payload);
14691
+ if ("failed_at" in row && !(row.failed_at instanceof Date)) {
14692
+ result.failed_at = new Date(row.failed_at);
14693
+ }
14694
+ return result;
14531
14695
  }
14532
14696
  var failedJobRepository_default = FailedJobRepository;
14533
14697
 
@@ -14821,8 +14985,12 @@ async function runQueueJob(envelope, failedJobs, options = {}) {
14821
14985
  throw new Error(`Unknown job "${envelope.name}".`);
14822
14986
  }
14823
14987
  const attempts = envelope.attempts ?? 0;
14988
+ const context = options.context ?? {
14989
+ jobId: envelope.jobId ?? crypto.randomUUID(),
14990
+ signal: new AbortController().signal
14991
+ };
14824
14992
  try {
14825
- await job.handle(envelope.payload, options.context);
14993
+ await job.handle(envelope.payload, { ...context, attempt: attempts + 1 });
14826
14994
  } catch (error) {
14827
14995
  options.context?.signal.throwIfAborted();
14828
14996
  const nextAttempt = attempts + 1;
@@ -14830,19 +14998,19 @@ async function runQueueJob(envelope, failedJobs, options = {}) {
14830
14998
  if (nextAttempt < maxAttempts) {
14831
14999
  const backoffMs = job.backoffMs ?? queueConfig.backoffMs;
14832
15000
  if (options.deferRetry) {
14833
- await options.deferRetry({ ...envelope, attempts: nextAttempt }, backoffMs * nextAttempt);
15001
+ await options.deferRetry({ ...envelope, jobId: context.jobId, attempts: nextAttempt }, backoffMs * nextAttempt);
14834
15002
  return;
14835
15003
  }
14836
15004
  await delay(backoffMs * nextAttempt, undefined, { signal: options.context?.signal });
14837
15005
  await runQueueJob({
14838
15006
  ...envelope,
14839
15007
  attempts: nextAttempt
14840
- }, failedJobs, options);
15008
+ }, failedJobs, { ...options, context });
14841
15009
  return;
14842
15010
  }
14843
15011
  await failedJobs.recordFailure({
14844
15012
  jobName: envelope.name,
14845
- jobId: options.context?.jobId ?? envelope.jobId,
15013
+ jobId: context.jobId,
14846
15014
  payload: envelope.payload,
14847
15015
  exception: error instanceof Error ? error.stack ?? error.message : String(error)
14848
15016
  });
@@ -17644,6 +17812,7 @@ export {
17644
17812
  resolveOrganizationScope,
17645
17813
  resolveQualifiedColumn,
17646
17814
  resolveRepositoryConnection,
17815
+ resolveRequestId,
17647
17816
  resolveSafeOutboundTarget,
17648
17817
  resolveService,
17649
17818
  resolveSoftDeleteColumn,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/core",
3
- "version": "2.2.51",
3
+ "version": "2.2.52",
4
4
  "description": "Strata Bun framework public API",
5
5
  "type": "module",
6
6
  "license": "MIT",