@getstrata/core 2.2.50 → 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();
@@ -8316,10 +8440,27 @@ function flattenRelationNames(relations) {
8316
8440
  function isLoadableModel(value) {
8317
8441
  return Boolean(value && typeof value === "object" && typeof value.load === "function" && typeof value.loaded === "function" && typeof value.setLoaded === "function");
8318
8442
  }
8319
- async function eagerLoadOnModels(models, paths) {
8443
+ function resolveModelRelation(model, name) {
8444
+ const method = model[name];
8445
+ if (typeof method !== "function") {
8446
+ throw new Error(`${model.constructor.name} has no relation method ${name}().`);
8447
+ }
8448
+ return method.call(model);
8449
+ }
8450
+ async function eagerLoadOnModels(models, paths, knownAbsentMorphRoots = new Map) {
8320
8451
  if (models.length === 0 || paths.length === 0) {
8321
8452
  return;
8322
8453
  }
8454
+ const byModel = new Map;
8455
+ for (const model of models) {
8456
+ const group = byModel.get(model.constructor) ?? [];
8457
+ group.push(model);
8458
+ byModel.set(model.constructor, group);
8459
+ }
8460
+ if (byModel.size > 1) {
8461
+ await Promise.all([...byModel.values()].map((group) => eagerLoadOnModels(group, paths, knownAbsentMorphRoots)));
8462
+ return;
8463
+ }
8323
8464
  const grouped = new Map;
8324
8465
  for (const path of paths) {
8325
8466
  const [head, ...rest] = path.split(".");
@@ -8334,28 +8475,33 @@ async function eagerLoadOnModels(models, paths) {
8334
8475
  grouped.set(head, existing);
8335
8476
  }
8336
8477
  await Promise.all([...grouped.entries()].map(async ([head, nested]) => {
8337
- const unloaded = models.filter((model) => model.loaded(head) === undefined);
8478
+ const unloaded = models.filter((model) => model.loaded(head) === undefined && !knownAbsentMorphRoots.get(model)?.has(head));
8338
8479
  if (unloaded.length > 0) {
8339
8480
  const first = unloaded[0];
8340
8481
  if (!first) {
8341
8482
  return;
8342
8483
  }
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);
8484
+ const relationQuery = resolveModelRelation(first, head);
8348
8485
  const query = first.getRepository().query();
8349
8486
  relationQuery.applyEagerLoad(query, head);
8350
8487
  const attached = await query.attachToRows(unloaded.map((model) => model.toObject()));
8351
8488
  for (const [index, model] of unloaded.entries()) {
8352
8489
  const row = attached[index] ?? model.toObject();
8353
- model.setLoaded(head, relationQuery.hydrateEager(row, head));
8490
+ model.setLoaded(head, relationQuery.hydrateEager(row, head, nested.length > 0));
8354
8491
  }
8355
8492
  }
8356
8493
  if (nested.length === 0) {
8357
8494
  return;
8358
8495
  }
8496
+ for (const model of models) {
8497
+ const value = model.loaded(head);
8498
+ if (value && typeof value === "object" && !Array.isArray(value) && !isLoadableModel(value)) {
8499
+ const relationQuery = resolveModelRelation(model, head);
8500
+ if (relationQuery.kind === "morphTo") {
8501
+ model.setLoaded(head, relationQuery.hydrateEager({ ...model.toObject(), [head]: value }, head, true));
8502
+ }
8503
+ }
8504
+ }
8359
8505
  const children = models.flatMap((model) => {
8360
8506
  const loaded = model.loaded(head);
8361
8507
  return Array.isArray(loaded) ? loaded : loaded ? [loaded] : [];
@@ -8559,16 +8705,31 @@ class ModelQuery {
8559
8705
  async hydrateRows(rows) {
8560
8706
  const statics = modelStatics(this.modelClass);
8561
8707
  const models = [];
8708
+ const knownAbsentMorphRoots = new Map;
8709
+ const nested = this.eager.filter((item) => item.path.includes(".")).map((item) => item.path);
8710
+ const nestedRoots = new Set(this.eager.filter((item) => item.path.includes(".")).map((item) => item.name));
8562
8711
  for (const row of rows) {
8563
8712
  const model = statics.newFromRecord(row, true);
8713
+ const absentMorphRoots = new Set;
8564
8714
  for (const { name, relationQuery } of this.eager) {
8565
- model.setLoaded(name, relationQuery.hydrateEager(row, name));
8715
+ const value = relationQuery.hydrateEager(row, name, nestedRoots.has(name));
8716
+ model.setLoaded(name, value);
8717
+ if (relationQuery.kind === "morphTo" && value === undefined)
8718
+ absentMorphRoots.add(name);
8719
+ else
8720
+ absentMorphRoots.delete(name);
8566
8721
  }
8722
+ if (absentMorphRoots.size > 0)
8723
+ knownAbsentMorphRoots.set(model, absentMorphRoots);
8567
8724
  models.push(model);
8568
8725
  }
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);
8726
+ await Promise.all(models.map((model) => {
8727
+ if (getModelObservers(model.constructor)?.length) {
8728
+ knownAbsentMorphRoots.delete(model);
8729
+ }
8730
+ return runObservers(model, "retrieved");
8731
+ }));
8732
+ await eagerLoadOnModels(models.filter(isLoadableModel), nested, knownAbsentMorphRoots);
8572
8733
  return models;
8573
8734
  }
8574
8735
  async first() {
@@ -9254,8 +9415,13 @@ class MorphToRelationQuery {
9254
9415
  relatedOptions(model, this.extraWhere)
9255
9416
  ])));
9256
9417
  }
9257
- hydrateEager(row, alias) {
9258
- return row[alias];
9418
+ hydrateEager(row, alias, forNestedLoading = false) {
9419
+ const value = row[alias];
9420
+ if (!forNestedLoading || !value)
9421
+ return value;
9422
+ const type = row[this.relation.morphTypeKey];
9423
+ const related = type === undefined || type === null ? undefined : this.relatedByType[String(type)];
9424
+ return related ? related.newFromRecord(value) : value;
9259
9425
  }
9260
9426
  toExistsClause(parentTable) {
9261
9427
  const params = [];
@@ -9613,13 +9779,24 @@ class Model {
9613
9779
  const withTimestamps = applyTimestampsOnCreate(table.columns, assignable, timestamps);
9614
9780
  const payload = await statics.dehydrateAttributes(withTimestamps);
9615
9781
  const pending = statics.newFromRecord({ ...payload }, false);
9782
+ const beforeObservers = snapshotAttributes(pending.attributes);
9616
9783
  if (await runObservers(pending, "saving") === false) {
9617
9784
  throw new Error(`${this.name}.create() was cancelled by an observer.`);
9618
9785
  }
9619
9786
  if (await runObservers(pending, "creating") === false) {
9620
9787
  throw new Error(`${this.name}.create() was cancelled by an observer.`);
9621
9788
  }
9622
- 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);
9623
9800
  const created = statics.fromRecord(record, repository, true);
9624
9801
  await runObservers(created, "created");
9625
9802
  await runObservers(created, "saved");
@@ -11443,23 +11620,25 @@ var {S3Client } = globalThis.Bun;
11443
11620
 
11444
11621
  // ../../src/core/security/safePath.ts
11445
11622
  import { isAbsolute, resolve as resolve2, sep } from "path";
11446
- function assertPathUnderRoot(rootDirectory, userPath) {
11447
- const trimmed = userPath.trim();
11448
- if (trimmed.length === 0) {
11623
+ function resolvePathUnderRoot(rootDirectory, path) {
11624
+ if (path.length === 0) {
11449
11625
  throw new Error("Path must not be empty.");
11450
11626
  }
11451
- if (trimmed.includes("\x00")) {
11627
+ if (path.includes("\x00")) {
11452
11628
  throw new Error("Path must not contain a null byte.");
11453
11629
  }
11454
11630
  const root = resolve2(rootDirectory);
11455
- const candidate = isAbsolute(trimmed) ? resolve2(trimmed) : resolve2(root, trimmed.replace(/^\/+/u, ""));
11631
+ const candidate = isAbsolute(path) ? resolve2(path) : resolve2(root, path.replace(/^\/+/u, ""));
11456
11632
  if (candidate === root || candidate.startsWith(`${root}${sep}`)) {
11457
11633
  return candidate;
11458
11634
  }
11459
11635
  throw new Error("Path escapes the storage root.");
11460
11636
  }
11637
+ function assertPathUnderRoot(rootDirectory, userPath) {
11638
+ return resolvePathUnderRoot(rootDirectory, userPath.trim());
11639
+ }
11461
11640
  function assertUrlPathUnderRoot(rootDirectory, urlPathname) {
11462
- return assertPathUnderRoot(rootDirectory, urlPathname.replace(/^\/+/u, ""));
11641
+ return resolvePathUnderRoot(rootDirectory, decodeURIComponent(urlPathname).replace(/^\/+/u, ""));
11463
11642
  }
11464
11643
 
11465
11644
  // ../../src/core/storage/storage.ts
@@ -11663,6 +11842,10 @@ function currentRequestMeta() {
11663
11842
  userAgent: null
11664
11843
  };
11665
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
+ }
11666
11849
 
11667
11850
  // ../../src/core/http/safeInternalPath.ts
11668
11851
  var NESTED_REDIRECT_KEYS = new Set(["redirect", "next", "return", "returnTo", "return_to"]);
@@ -12930,8 +13113,8 @@ function composeMiddleware(...middleware) {
12930
13113
  };
12931
13114
  }
12932
13115
  async function requestIdMiddleware(request, next) {
12933
- const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
12934
- const response = await next();
13116
+ const requestId = resolveRequestId(request);
13117
+ const response = await runWithRequestMeta({ ...currentRequestMeta(), request, requestId }, next);
12935
13118
  const headers = new Headers(response.headers);
12936
13119
  headers.set("x-request-id", requestId);
12937
13120
  return new Response(response.body, {
@@ -14252,14 +14435,15 @@ function resetGracefulShutdownForTests() {
14252
14435
  function createRequestLoggingMiddleware() {
14253
14436
  return async (request, next) => {
14254
14437
  const ipAddress = readClientIp(request) ?? null;
14438
+ const requestId = resolveRequestId(request);
14255
14439
  return await runWithRequestMeta({
14256
14440
  ...currentRequestMeta(),
14257
14441
  ipAddress,
14258
14442
  userAgent: request.headers.get("user-agent"),
14259
- request
14443
+ request,
14444
+ requestId
14260
14445
  }, async () => {
14261
14446
  const startedAt = performance.now();
14262
- const requestId = request.headers.get("x-request-id") ?? crypto.randomUUID();
14263
14447
  const response = await next();
14264
14448
  const durationMs = Math.round(performance.now() - startedAt);
14265
14449
  appLogger.info("HTTP request completed", {
@@ -14471,6 +14655,9 @@ class Notification {
14471
14655
  init_dialect();
14472
14656
  init_repositoryConnection();
14473
14657
 
14658
+ // ../../src/core/queue/failedJobRepository.ts
14659
+ init_dialect();
14660
+
14474
14661
  // ../../src/core/queue/failedJobTable.ts
14475
14662
  var failedJobTable = defineTable({
14476
14663
  name: "failed_job",
@@ -14484,6 +14671,27 @@ class FailedJobRepository extends BaseRepository {
14484
14671
  constructor() {
14485
14672
  super(failedJobTable);
14486
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;
14487
14695
  }
14488
14696
  var failedJobRepository_default = FailedJobRepository;
14489
14697
 
@@ -14777,8 +14985,12 @@ async function runQueueJob(envelope, failedJobs, options = {}) {
14777
14985
  throw new Error(`Unknown job "${envelope.name}".`);
14778
14986
  }
14779
14987
  const attempts = envelope.attempts ?? 0;
14988
+ const context = options.context ?? {
14989
+ jobId: envelope.jobId ?? crypto.randomUUID(),
14990
+ signal: new AbortController().signal
14991
+ };
14780
14992
  try {
14781
- await job.handle(envelope.payload, options.context);
14993
+ await job.handle(envelope.payload, { ...context, attempt: attempts + 1 });
14782
14994
  } catch (error) {
14783
14995
  options.context?.signal.throwIfAborted();
14784
14996
  const nextAttempt = attempts + 1;
@@ -14786,19 +14998,19 @@ async function runQueueJob(envelope, failedJobs, options = {}) {
14786
14998
  if (nextAttempt < maxAttempts) {
14787
14999
  const backoffMs = job.backoffMs ?? queueConfig.backoffMs;
14788
15000
  if (options.deferRetry) {
14789
- await options.deferRetry({ ...envelope, attempts: nextAttempt }, backoffMs * nextAttempt);
15001
+ await options.deferRetry({ ...envelope, jobId: context.jobId, attempts: nextAttempt }, backoffMs * nextAttempt);
14790
15002
  return;
14791
15003
  }
14792
15004
  await delay(backoffMs * nextAttempt, undefined, { signal: options.context?.signal });
14793
15005
  await runQueueJob({
14794
15006
  ...envelope,
14795
15007
  attempts: nextAttempt
14796
- }, failedJobs, options);
15008
+ }, failedJobs, { ...options, context });
14797
15009
  return;
14798
15010
  }
14799
15011
  await failedJobs.recordFailure({
14800
15012
  jobName: envelope.name,
14801
- jobId: options.context?.jobId ?? envelope.jobId,
15013
+ jobId: context.jobId,
14802
15014
  payload: envelope.payload,
14803
15015
  exception: error instanceof Error ? error.stack ?? error.message : String(error)
14804
15016
  });
@@ -17600,6 +17812,7 @@ export {
17600
17812
  resolveOrganizationScope,
17601
17813
  resolveQualifiedColumn,
17602
17814
  resolveRepositoryConnection,
17815
+ resolveRequestId,
17603
17816
  resolveSafeOutboundTarget,
17604
17817
  resolveService,
17605
17818
  resolveSoftDeleteColumn,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/core",
3
- "version": "2.2.50",
3
+ "version": "2.2.52",
4
4
  "description": "Strata Bun framework public API",
5
5
  "type": "module",
6
6
  "license": "MIT",