@orieljs/framework 0.1.0-alpha.14 → 0.1.0-alpha.15

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
@@ -22,7 +22,7 @@ import {
22
22
  renderToString,
23
23
  styleString,
24
24
  view
25
- } from "./chunk-X4N74JDO.js";
25
+ } from "./chunk-GCMPAXIK.js";
26
26
  import {
27
27
  API_ROUTES_STUB,
28
28
  Application as Application2,
@@ -150,7 +150,7 @@ import {
150
150
  vite,
151
151
  viteReactRefresh,
152
152
  writeResponse
153
- } from "./chunk-UBSIBGXR.js";
153
+ } from "./chunk-7GPMFMS7.js";
154
154
  import {
155
155
  Arr,
156
156
  BindingResolutionError,
@@ -175,11 +175,12 @@ import {
175
175
  fileType_exports,
176
176
  importOptional,
177
177
  inject,
178
+ isPublicAsset,
178
179
  now,
179
180
  retry,
180
181
  tap,
181
182
  value
182
- } from "./chunk-4NCMY3ZS.js";
183
+ } from "./chunk-FVI6X3VJ.js";
183
184
  import {
184
185
  Application,
185
186
  AuthFactory,
@@ -665,12 +666,7 @@ var SessionGuard = class {
665
666
  const user = await this.provider.retrieveByCredentials(credentials);
666
667
  this.#lastAttempted = user;
667
668
  if (user !== void 0 && await this.#hasValidCredentials(user, credentials)) {
668
- if (this.options.rehashOnLogin !== false) {
669
- await this.provider.rehashPasswordIfRequired?.(
670
- user,
671
- credentials
672
- );
673
- }
669
+ await this.rehashIfRequired(user, credentials);
674
670
  await this.login(user, remember);
675
671
  return true;
676
672
  }
@@ -773,6 +769,28 @@ var SessionGuard = class {
773
769
  this.#queueRecallerCookie(user);
774
770
  }
775
771
  }
772
+ /**
773
+ * @internal After the password checked out: rehash it when the hasher's settings changed (hashing.rehash_on_login).
774
+ * attempt() and the two-factor sign-in both call it.
775
+ */
776
+ async rehashIfRequired(user, credentials) {
777
+ if (this.options.rehashOnLogin === false) return;
778
+ await this.provider.rehashPasswordIfRequired?.(user, credentials);
779
+ }
780
+ /**
781
+ * @internal A saved model that is this guard's user (same class and key) with a different password becomes the user,
782
+ * so a password saved on a freshly loaded instance, not on request().user(), is the one this session keeps.
783
+ */
784
+ takeSavedUser(model) {
785
+ const user = this.#user;
786
+ if (user === void 0 || model === user || typeof model !== "object" || model === null) return;
787
+ if (model.constructor !== user.constructor) return;
788
+ const saved = model;
789
+ if (String(saved.getAuthIdentifier()) !== String(user.getAuthIdentifier())) return;
790
+ if (saved.wasChanged?.(saved.getAuthPasswordName?.() ?? "password") !== true) return;
791
+ const hash2 = saved.getAuthPassword();
792
+ if (hash2 !== "" && hash2 !== user.getAuthPassword()) this.#user = saved;
793
+ }
776
794
  hasUser() {
777
795
  return this.#user !== void 0;
778
796
  }
@@ -970,7 +988,7 @@ var TokenRepository = class {
970
988
  }
971
989
  const id = plainText.slice(0, separator);
972
990
  const secret = plainText.slice(separator + 1);
973
- if (id === "" || secret === "") return void 0;
991
+ if (!/^\d{1,18}$/.test(id) || secret === "") return void 0;
974
992
  const row = await this.#query().where("id", id).first();
975
993
  if (row === void 0 || typeof row.token !== "string" || !equals(row.token, sha256(secret))) return void 0;
976
994
  return new PersonalAccessToken(row, this);
@@ -1139,6 +1157,16 @@ var AuthManager = class {
1139
1157
  createUserProvider(name) {
1140
1158
  return this.#createUserProvider(name, true);
1141
1159
  }
1160
+ /**
1161
+ * @internal A model saved in the current scope (a request, a job): each session guard already resolved there takes it
1162
+ * when it is its signed-in user with a new password, so `auth.session` keeps the hash the request saved. Resolves no
1163
+ * guard of its own.
1164
+ */
1165
+ userSaved(model) {
1166
+ for (const guard2 of this.#scopes.get(this.#container())?.guards.values() ?? []) {
1167
+ if (guard2 instanceof SessionGuard) guard2.takeSavedUser(model);
1168
+ }
1169
+ }
1142
1170
  /** Forget the resolved guards of the current scope (tests). */
1143
1171
  forgetGuards() {
1144
1172
  this.#scopes.delete(this.#container());
@@ -2078,6 +2106,7 @@ function otpauthUrl(options) {
2078
2106
  }
2079
2107
  var PENDING_LOGIN = "oriel.two_factor.login";
2080
2108
  var pendingKey = (nonce) => `oriel:two-factor:pending:${nonce}`;
2109
+ var attemptsKey = (nonce) => `oriel:two-factor:attempts:${nonce}`;
2081
2110
  var emailKey = (id) => `oriel:two-factor:email:${String(id)}`;
2082
2111
  var stepKey = (id) => `oriel:two-factor:totp:${String(id)}`;
2083
2112
  function maskEmail(email) {
@@ -2107,13 +2136,14 @@ var TwoFactorManager = class {
2107
2136
  await this.#dispatch(new Failed(guardName, user, credentials));
2108
2137
  return false;
2109
2138
  }
2139
+ await guard2.rehashIfRequired?.(user, credentials);
2110
2140
  const method = this.#store().method(user);
2111
2141
  if (method === void 0 || !await (this.#requireWhen?.(user) ?? true)) {
2112
2142
  await guard2.login(user, remember);
2113
2143
  return "authenticated";
2114
2144
  }
2115
2145
  const nonce = randomBytes2(16).toString("hex");
2116
- const record = { id: user.getAuthIdentifier(), remember, method, expires: Date.now() + config2.pending_ttl * 1e3, attempts: 0, nonce };
2146
+ const record = { id: user.getAuthIdentifier(), remember, method, expires: Date.now() + config2.pending_ttl * 1e3, nonce };
2117
2147
  inject(Session).put(PENDING_LOGIN, record);
2118
2148
  await inject(CacheManager).put(pendingKey(nonce), true, config2.pending_ttl);
2119
2149
  if (method === "email") await this.#sendCode(user);
@@ -2131,6 +2161,12 @@ var TwoFactorManager = class {
2131
2161
  const pending = await this.#pending();
2132
2162
  if (pending === void 0) return false;
2133
2163
  const { record, user } = pending;
2164
+ const attempts = await this.#countAttempt(record);
2165
+ const max = this.#config().max_attempts;
2166
+ if (attempts > max) {
2167
+ await this.#end(record);
2168
+ return false;
2169
+ }
2134
2170
  const typed = normalizeCode(code);
2135
2171
  let used;
2136
2172
  if (/^\d{6}$/.test(typed)) {
@@ -2139,10 +2175,8 @@ var TwoFactorManager = class {
2139
2175
  used = "recovery";
2140
2176
  }
2141
2177
  if (used === void 0) {
2142
- record.attempts++;
2143
2178
  await this.#dispatch(new TwoFactorFailed(user, record.method));
2144
- if (record.attempts >= this.#config().max_attempts) await this.#end(record);
2145
- else inject(Session).put(PENDING_LOGIN, record);
2179
+ if (attempts >= max) await this.#end(record);
2146
2180
  return false;
2147
2181
  }
2148
2182
  await this.#end(record);
@@ -2245,9 +2279,18 @@ var TwoFactorManager = class {
2245
2279
  }
2246
2280
  return { record, user };
2247
2281
  }
2282
+ /** Counts an attempt at the pending login and returns the count so far, starting from an older record's own. */
2283
+ async #countAttempt(record) {
2284
+ const cache2 = inject(CacheManager);
2285
+ const ttl = Math.max(1, Math.ceil((record.expires - Date.now()) / 1e3));
2286
+ await cache2.add(attemptsKey(record.nonce), record.attempts ?? 0, ttl);
2287
+ return cache2.increment(attemptsKey(record.nonce));
2288
+ }
2248
2289
  async #end(record) {
2249
2290
  inject(Session).forget(PENDING_LOGIN);
2250
- await inject(CacheManager).forget(pendingKey(record.nonce));
2291
+ const cache2 = inject(CacheManager);
2292
+ await cache2.forget(pendingKey(record.nonce));
2293
+ await cache2.forget(attemptsKey(record.nonce));
2251
2294
  }
2252
2295
  #hash(code) {
2253
2296
  return createHmac4("sha256", inject(Encrypter).getKey()).update(code).digest("hex");
@@ -2324,7 +2367,13 @@ var AuthServiceProvider = class extends ServiceProvider {
2324
2367
  if (this.app.bound(Router)) {
2325
2368
  this.app.make(Router).aliasMiddleware("auth", Authenticate).aliasMiddleware("auth.session", AuthenticateSession).aliasMiddleware("guest", RedirectIfAuthenticated).aliasMiddleware("can", Authorize).aliasMiddleware("verified", EnsureEmailIsVerified).aliasMiddleware("two-factor.challenge", TwoFactorChallenge);
2326
2369
  }
2327
- if (this.app.bound(EventDispatcher)) this.app.make(EventDispatcher).listen(Registered, SendEmailVerificationNotification);
2370
+ if (this.app.bound(EventDispatcher)) {
2371
+ const events = this.app.make(EventDispatcher);
2372
+ events.listen(Registered, SendEmailVerificationNotification);
2373
+ const auth2 = this.app.make(AuthFactory);
2374
+ const onSaved = (_event, payload) => auth2.userSaved(payload[0]);
2375
+ events.listen("eloquent.saved: *", onSaved);
2376
+ }
2328
2377
  await discoverPolicies(this.app.appPath("Policies"), this.app.make(Gate));
2329
2378
  if (this.app.bound(ConsoleKernel)) {
2330
2379
  const app2 = this.app;
@@ -3315,9 +3364,19 @@ var DatabaseStore = class {
3315
3364
  const deleted = await this.connection.table(this.table).where("key", this.k(key)).delete();
3316
3365
  return deleted > 0;
3317
3366
  }
3367
+ /**
3368
+ * Deletes this store's keys: those starting with its prefix (every row without one). The prefix's `%` and `_` are
3369
+ * escaped, so another app's keys in the same table, `appXcache_…` beside `app_cache_…`, stay.
3370
+ */
3318
3371
  async flush() {
3319
- if (this.keyPrefix) await this.connection.table(this.table).where("key", "like", `${this.keyPrefix}%`).delete();
3320
- else await this.connection.table(this.table).delete();
3372
+ if (!this.keyPrefix) {
3373
+ await this.connection.table(this.table).delete();
3374
+ return true;
3375
+ }
3376
+ const column = this.connection.getDriverName() === "mysql" ? "`key`" : '"key"';
3377
+ const pattern = `${this.keyPrefix.replace(/[!%_]/g, (character) => `!${character}`)}%`;
3378
+ const query = this.connection.table(this.table);
3379
+ await query.whereRaw(`${column} like ? escape '!'`, [pattern]).delete();
3321
3380
  return true;
3322
3381
  }
3323
3382
  };
@@ -5342,7 +5401,7 @@ async function repeatEvents(repeating, io, startedAt, clock, background) {
5342
5401
  const endOfMinute = (Math.floor(startedAt.getTime() / 6e4) + 1) * 6e4;
5343
5402
  while (clock.now() < endOfMinute) {
5344
5403
  for (const event2 of repeating) {
5345
- if (await interrupted()) return;
5404
+ if (clock.stopped?.() || await interrupted()) return;
5346
5405
  const now5 = clock.now();
5347
5406
  if (event2.shouldRepeatNow(now5)) await start(event2, io, startedAt, new Date(now5), background);
5348
5407
  }
@@ -5355,7 +5414,10 @@ async function runSchedule(events, io, startedAt, clock) {
5355
5414
  if (repeating.length > 0) await clearInterrupt();
5356
5415
  const background = [];
5357
5416
  try {
5358
- for (const event2 of due) await start(event2, io, startedAt, new Date(clock.now()), background);
5417
+ for (const event2 of due) {
5418
+ if (clock.stopped?.()) break;
5419
+ await start(event2, io, startedAt, new Date(clock.now()), background);
5420
+ }
5359
5421
  if (repeating.length > 0) await repeatEvents(repeating, io, startedAt, clock, background);
5360
5422
  } finally {
5361
5423
  await Promise.allSettled(background);
@@ -5431,27 +5493,54 @@ var ScheduleWorkCommand = class extends Command {
5431
5493
  workOptions;
5432
5494
  signature = "schedule:work";
5433
5495
  description = "Start the schedule worker";
5496
+ /**
5497
+ * Ctrl-C (SIGINT) or a deploy's SIGTERM stops it: no task starts after the signal, the overlap locks of the tasks still
5498
+ * running are released, and the command ends with 0. A task still running isn't waited for.
5499
+ */
5434
5500
  async handle() {
5435
5501
  const schedule = inject(Schedule);
5502
+ const signals = this.workOptions.signals ?? process;
5503
+ let stopped = false;
5504
+ let stop;
5505
+ const stopping = new Promise((resolve5) => stop = resolve5);
5506
+ const onSignal = () => {
5507
+ stopped = true;
5508
+ stop();
5509
+ };
5510
+ signals.once("SIGINT", onSignal);
5511
+ signals.once("SIGTERM", onSignal);
5512
+ try {
5513
+ await Promise.race([this.work(schedule, () => stopped), stopping]);
5514
+ if (stopped) {
5515
+ for (const event2 of schedule.events()) await event2.releaseOverlapLock?.();
5516
+ this.info("Stopped.");
5517
+ }
5518
+ } finally {
5519
+ signals.off("SIGINT", onSignal);
5520
+ signals.off("SIGTERM", onSignal);
5521
+ }
5522
+ return 0;
5523
+ }
5524
+ async work(schedule, stopped) {
5436
5525
  const sleep5 = this.workOptions.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
5437
5526
  const clock = this.workOptions.now ?? Date.now;
5438
5527
  this.info("Running scheduled tasks every minute.");
5439
5528
  let lastMinute;
5440
- while (!this.workOptions.signal?.aborted) {
5529
+ while (!this.workOptions.signal?.aborted && !stopped()) {
5441
5530
  const time = clock();
5442
5531
  const minute = Math.floor(time / 6e4);
5443
5532
  if (minute !== lastMinute) {
5444
5533
  lastMinute = minute;
5445
5534
  const now5 = new Date(time);
5446
5535
  try {
5447
- await runSchedule(schedule.dueEvents(now5), this, now5, { now: clock, sleep: sleep5 });
5536
+ await runSchedule(schedule.dueEvents(now5), this, now5, { now: clock, sleep: sleep5, stopped });
5448
5537
  } catch (error) {
5449
5538
  this.error(`The scheduled run failed: ${error instanceof Error ? error.message : String(error)}`);
5450
5539
  }
5451
5540
  }
5541
+ if (stopped()) return;
5452
5542
  await sleep5(Math.max(0, (minute + 1) * 6e4 - clock()) + 10);
5453
5543
  }
5454
- return 0;
5455
5544
  }
5456
5545
  };
5457
5546
  var defaultSpawner = (command, args) => spawn(command, args, { stdio: "inherit", shell: process.platform === "win32" });
@@ -5773,6 +5862,8 @@ var ScheduledEventImpl = class {
5773
5862
  /** The minute slot this server won with onOneServer(): its repetitions in that minute keep it. */
5774
5863
  wonServerSlot;
5775
5864
  overlapExpiryMinutes;
5865
+ /** The overlap lock a run in progress holds, so schedule:work can release it when it is stopped. */
5866
+ heldOverlapLock;
5776
5867
  oneServer = false;
5777
5868
  background = false;
5778
5869
  eventName;
@@ -6102,6 +6193,7 @@ var ScheduledEventImpl = class {
6102
6193
  if (this.overlapExpiryMinutes !== void 0) {
6103
6194
  overlapLock = this.acquireLock(this.mutexName(), this.overlapExpiryMinutes * 60);
6104
6195
  if (overlapLock && !await overlapLock.get()) return;
6196
+ this.heldOverlapLock = overlapLock;
6105
6197
  }
6106
6198
  try {
6107
6199
  for (const callback of this.beforeCallbacks) await callback();
@@ -6109,9 +6201,21 @@ var ScheduledEventImpl = class {
6109
6201
  for (const callback of this.afterCallbacks) await callback(failure === void 0);
6110
6202
  if (failure !== void 0) throw failure.error;
6111
6203
  } finally {
6112
- if (overlapLock) await overlapLock.release();
6204
+ if (overlapLock && this.heldOverlapLock === overlapLock) {
6205
+ this.heldOverlapLock = void 0;
6206
+ await overlapLock.release();
6207
+ }
6113
6208
  }
6114
6209
  }
6210
+ /**
6211
+ * @internal schedule:work, stopped by a signal while this event runs: releases the overlap lock the run holds, so the
6212
+ * next start isn't blocked until the lock expires (24 hours by default).
6213
+ */
6214
+ async releaseOverlapLock() {
6215
+ const lock = this.heldOverlapLock;
6216
+ this.heldOverlapLock = void 0;
6217
+ if (lock) await lock.release();
6218
+ }
6115
6219
  /**
6116
6220
  * Runs the event and says whether it failed. A command fails when it exits non-zero, and a closure when it throws or
6117
6221
  * returns false, as Laravel's CallbackEvent does. A job whose handler returns false failing is Oriel's own choice:
@@ -6508,12 +6612,13 @@ import { Kysely, sql as sql7 } from "kysely";
6508
6612
  import { sql as sql6 } from "kysely";
6509
6613
  import { sql as sql4 } from "kysely";
6510
6614
  import { sql as sql5 } from "kysely";
6511
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
6615
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
6616
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
6512
6617
  import { isDeepStrictEqual } from "util";
6513
6618
  import { existsSync as existsSync5, readdirSync as readdirSync3 } from "fs";
6514
6619
  import { join as join43 } from "path";
6515
6620
  import { pathToFileURL as pathToFileURL3 } from "url";
6516
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
6621
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
6517
6622
  import { existsSync as existsSync23, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
6518
6623
  import { join as join52 } from "path";
6519
6624
  import { existsSync as existsSync32, readdirSync as readdirSync22 } from "fs";
@@ -7236,10 +7341,33 @@ var Grammar = class {
7236
7341
  columnize(columns) {
7237
7342
  return join9(columns.map((column) => this.wrap(column)));
7238
7343
  }
7239
- compileSelect(query) {
7240
- const columns = query.columns.length ? join9(query.columns.map((column) => typeof column === "object" && "query" in column ? sql2`${sql2.raw(column.exists ? "exists " : "")}(${this.compileSelect(column.query)}) as ${sql2.id(column.as)}` : this.wrap(column))) : sql2.raw("*");
7344
+ compileSelect(query, extraColumn) {
7345
+ if (query.groupLimit && extraColumn === void 0) return this.compileGroupLimit(query);
7346
+ const list32 = query.columns.length ? query.columns.map((column) => typeof column === "object" && "query" in column ? sql2`${sql2.raw(column.exists ? "exists " : "")}(${this.compileSelect(column.query)}) as ${sql2.id(column.as)}` : this.wrap(column)) : [sql2.raw("*")];
7347
+ const columns = join9(extraColumn ? [...list32, extraColumn] : list32);
7241
7348
  return clauses([query.distinctRows ? sql2`select distinct ${columns}` : sql2`select ${columns}`, this.compileComponents(query)]);
7242
7349
  }
7350
+ /**
7351
+ * Laravel 11's compileGroupLimit(): the query numbers its rows per `column` in its own order, and an outer query keeps
7352
+ * those inside the limit and offset, in row-number order. SQLite 3.25+, MySQL 8 and PostgreSQL have window functions.
7353
+ */
7354
+ compileGroupLimit(query) {
7355
+ const { column, limit, offset } = query.groupLimit;
7356
+ const inner = query.clone();
7357
+ inner.groupLimit = void 0;
7358
+ inner.orders = [];
7359
+ const order = this.compileOrders(query);
7360
+ const over = order ? sql2`partition by ${this.wrap(column)} ${order}` : sql2`partition by ${this.wrap(column)}`;
7361
+ const row = sql2.id(GROUP_ROW);
7362
+ const kept = [];
7363
+ if (offset !== void 0 && offset > 0) kept.push(sql2`${row} > ${sql2.lit(offset)}`);
7364
+ if (limit !== void 0) kept.push(sql2`${row} <= ${sql2.lit((offset ?? 0) + limit)}`);
7365
+ return clauses([
7366
+ sql2`select * from (${this.compileSelect(inner, sql2`row_number() over (${over}) as ${row}`)}) as ${sql2.id("oriel_table")}`,
7367
+ kept.length ? sql2`where ${join9(kept, " and ")}` : void 0,
7368
+ sql2`order by ${row}`
7369
+ ]);
7370
+ }
7243
7371
  /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
7244
7372
  compileComponents(query) {
7245
7373
  return clauses([
@@ -7266,7 +7394,9 @@ var Grammar = class {
7266
7394
  switch (where.type) {
7267
7395
  case "basic": {
7268
7396
  const column = typeof where.column === "object" && !(where.column instanceof Expression) ? sql2`(${this.compileSelect(where.column)})` : this.wrap(where.column);
7269
- return sql2`${column} ${sql2.raw(this.operator(where.operator))} ${this.parameter(where.value)}`;
7397
+ const operator = this.operator(where.operator);
7398
+ if (this.driver === "pgsql" && /like/i.test(operator)) return sql2`${column}::text ${sql2.raw(operator)} ${this.parameter(where.value)}`;
7399
+ return sql2`${column} ${sql2.raw(operator)} ${this.parameter(where.value)}`;
7270
7400
  }
7271
7401
  case "in": {
7272
7402
  const keyword = sql2.raw(where.not ? "not in" : "in");
@@ -7345,7 +7475,10 @@ var Grammar = class {
7345
7475
  if (mode === "update") return sql2.raw("for update");
7346
7476
  return sql2.raw(this.driver === "pgsql" ? "for share" : "lock in share mode");
7347
7477
  }
7348
- /** `select count(*) as aggregate …`. Orders, limit and offset are dropped; grouped or distinct queries are wrapped. */
7478
+ /**
7479
+ * `select count(*) as aggregate …`. Orders, limit and offset are dropped. Grouped or distinct queries, and those with a
7480
+ * `having` (which may name a selected alias, withCount()'s `comments_count`), are wrapped, keeping their columns.
7481
+ */
7349
7482
  compileAggregate(query, fn, column) {
7350
7483
  const inner = query.clone();
7351
7484
  inner.orders = [];
@@ -7353,7 +7486,7 @@ var Grammar = class {
7353
7486
  inner.offsetValue = void 0;
7354
7487
  inner.lockMode = void 0;
7355
7488
  const target = column === "*" ? sql2.raw("*") : this.wrap(column);
7356
- if (inner.groups.length || inner.distinctRows) {
7489
+ if (inner.groups.length || inner.distinctRows || inner.havings.length) {
7357
7490
  if (fn === "count") return sql2`select count(*) as ${sql2.id("aggregate")} from (${this.compileSelect(inner)}) as ${sql2.id("temp_table")}`;
7358
7491
  if (column instanceof Expression) {
7359
7492
  throw new LogicError(`${fn}() can't target a raw expression over a distinct or grouped query: select it as an aliased column instead.`);
@@ -7439,6 +7572,7 @@ var Grammar = class {
7439
7572
  ];
7440
7573
  }
7441
7574
  };
7575
+ var GROUP_ROW = "oriel_row";
7442
7576
  async function* chunksOf(query, chunkSize) {
7443
7577
  for (let page = 1; ; page++) {
7444
7578
  const results = await query.clone().forPage(page, chunkSize).runSelect();
@@ -7499,6 +7633,8 @@ var Builder = class _Builder {
7499
7633
  orders = [];
7500
7634
  limitValue;
7501
7635
  offsetValue;
7636
+ /** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */
7637
+ groupLimit;
7502
7638
  lockMode;
7503
7639
  // ---------------------------------------------------------------- building
7504
7640
  from(table) {
@@ -7787,7 +7923,20 @@ var Builder = class _Builder {
7787
7923
  }
7788
7924
  /** The raw rows, without a Collection around them. */
7789
7925
  async runSelect() {
7790
- return (await this.connection.execute(this.grammar.compileSelect(this))).rows;
7926
+ const rows = (await this.connection.execute(this.grammar.compileSelect(this))).rows;
7927
+ if (this.groupLimit) for (const row of rows) delete row[GROUP_ROW];
7928
+ return rows;
7929
+ }
7930
+ /**
7931
+ * @internal Eager loading (Laravel 11's groupLimit()): the limit and offset set so far apply to each value of `column`,
7932
+ * the parent's key, instead of to the whole query. Compiled as row_number() over (partition by …).
7933
+ */
7934
+ limitPerGroup(column) {
7935
+ if (this.limitValue === void 0 && this.offsetValue === void 0) return this;
7936
+ this.groupLimit = { column, limit: this.limitValue, offset: this.offsetValue };
7937
+ this.limitValue = void 0;
7938
+ this.offsetValue = void 0;
7939
+ return this;
7791
7940
  }
7792
7941
  async first() {
7793
7942
  const rows = await this.clone().limit(1).runSelect();
@@ -9504,6 +9653,7 @@ var Connection = class {
9504
9653
  db;
9505
9654
  context = new AsyncLocalStorage();
9506
9655
  pinned = [];
9656
+ savepoints = 0;
9507
9657
  loggingQueries = false;
9508
9658
  queryLog = [];
9509
9659
  getName() {
@@ -9623,18 +9773,32 @@ var Connection = class {
9623
9773
  }
9624
9774
  async open() {
9625
9775
  const parent = this.current();
9626
- if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1 };
9776
+ if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve() };
9777
+ const previous = parent.turn;
9778
+ let endTurn;
9779
+ parent.turn = new Promise((resolve5) => endTurn = resolve5);
9780
+ await previous;
9627
9781
  const level2 = parent.level + 1;
9628
- await sql7.raw(`SAVEPOINT trans${level2}`).execute(parent.trx);
9629
- return { trx: parent.trx, level: level2 };
9782
+ const savepoint = `trans${level2}_${++this.savepoints}`;
9783
+ try {
9784
+ await sql7.raw(`SAVEPOINT ${savepoint}`).execute(parent.trx);
9785
+ } catch (error) {
9786
+ endTurn();
9787
+ throw error;
9788
+ }
9789
+ return { trx: parent.trx, level: level2, savepoint, turn: Promise.resolve(), endTurn };
9630
9790
  }
9631
9791
  async close(frame, action) {
9632
- if (frame.level === 1) {
9633
- await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
9634
- } else if (action === "commit") {
9635
- await sql7.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx);
9636
- } else {
9637
- await sql7.raw(`ROLLBACK TO SAVEPOINT trans${frame.level}`).execute(frame.trx);
9792
+ try {
9793
+ if (frame.level === 1) {
9794
+ await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
9795
+ } else if (action === "commit") {
9796
+ await sql7.raw(`RELEASE SAVEPOINT ${frame.savepoint}`).execute(frame.trx);
9797
+ } else {
9798
+ await sql7.raw(`ROLLBACK TO SAVEPOINT ${frame.savepoint}`).execute(frame.trx);
9799
+ }
9800
+ } finally {
9801
+ frame.endTurn?.();
9638
9802
  }
9639
9803
  }
9640
9804
  };
@@ -9646,6 +9810,8 @@ var DatabaseManagerImpl = class {
9646
9810
  config;
9647
9811
  connections = /* @__PURE__ */ new Map();
9648
9812
  defaultName;
9813
+ /** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */
9814
+ using = new AsyncLocalStorage2();
9649
9815
  settings() {
9650
9816
  return typeof this.config === "function" ? this.config() : this.config;
9651
9817
  }
@@ -9662,25 +9828,19 @@ var DatabaseManagerImpl = class {
9662
9828
  return connection;
9663
9829
  }
9664
9830
  getDefaultConnection() {
9665
- return this.defaultName ?? this.settings().default;
9831
+ return this.using.getStore() ?? this.defaultName ?? this.settings().default;
9666
9832
  }
9667
9833
  /** Overrides config('database.default'); undefined clears the override. */
9668
9834
  setDefaultConnection(name) {
9669
9835
  this.defaultName = name;
9670
9836
  }
9671
9837
  /**
9672
- * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), then restores the previous
9673
- * override, or none, so the default follows config('database.default') again. Without a name, just runs it.
9838
+ * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), for the callback's own async
9839
+ * context only: other requests running meanwhile keep their default. Without a name, just runs it.
9674
9840
  */
9675
9841
  async usingConnection(name, callback) {
9676
9842
  if (!name) return callback();
9677
- const previous = this.defaultName;
9678
- this.defaultName = name;
9679
- try {
9680
- return await callback();
9681
- } finally {
9682
- this.defaultName = previous;
9683
- }
9843
+ return this.using.run(name, callback);
9684
9844
  }
9685
9845
  /** The connections opened so far. */
9686
9846
  getConnections() {
@@ -10004,7 +10164,7 @@ var Builder2 = class extends Builder {
10004
10164
  if (models.length && this.model.hasModelListeners("retrieved")) {
10005
10165
  for (const model of models) await model.fireModelEvent("retrieved", false);
10006
10166
  }
10007
- if (models.length && this.eagerLoad.size) await this.eagerLoadRelations(models);
10167
+ if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models);
10008
10168
  return models;
10009
10169
  }
10010
10170
  // ---------------------------------------------------------------- eager loading
@@ -10045,6 +10205,7 @@ var Builder2 = class extends Builder {
10045
10205
  const relation = this.getRelation(name);
10046
10206
  relation.addEagerConstraints(models);
10047
10207
  constraint?.(relation);
10208
+ relation.limitEagerPerParent();
10048
10209
  const nested = this.relationsNestedUnder(name);
10049
10210
  if (Object.keys(nested).length) relation.with(nested);
10050
10211
  relation.initRelation(models, name);
@@ -10117,9 +10278,10 @@ var Builder2 = class extends Builder {
10117
10278
  const [rawName = "", as] = spec.split(/\s+as\s+/i);
10118
10279
  const name = rawName.trim();
10119
10280
  const relation = this.getRelation(name);
10120
- const target = column instanceof Expression ? column : new Expression(column === "*" ? "*" : this.connection.compile(this.grammar.wrap(relation.getRelated().qualifyColumn(column))).sql);
10281
+ const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this);
10282
+ const target = column instanceof Expression ? column : new Expression(column === "*" ? "*" : this.connection.compile(this.grammar.wrap(query.getModel().qualifyColumn(column))).sql);
10121
10283
  const expression = fn && fn !== "exists" ? new Expression(`${fn}(${target.value})`, target.bindings) : target;
10122
- const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this, [expression]);
10284
+ query.select(expression);
10123
10285
  query.wheres.push(...relation.wheres);
10124
10286
  if (constraint) query.callScope((q) => constraint(q));
10125
10287
  const scoped = query.applyScopes();
@@ -10219,8 +10381,8 @@ var Builder2 = class extends Builder {
10219
10381
  isMalformedKey(id) {
10220
10382
  return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id);
10221
10383
  }
10222
- /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
10223
10384
  async find(id) {
10385
+ if (Array.isArray(id)) return this.findMany(id);
10224
10386
  if (this.isMalformedKey(id)) return void 0;
10225
10387
  return this.clone().whereKey(id).first();
10226
10388
  }
@@ -10707,6 +10869,7 @@ function resolveMorphClass(type) {
10707
10869
  if (known) return known;
10708
10870
  throw new LogicError(`Class [${type}] not found for a morphTo relation. Add it to Relation.morphMap().`);
10709
10871
  }
10872
+ var selfAliases = 0;
10710
10873
  var Relation = class extends Builder2 {
10711
10874
  constructor(related, parent) {
10712
10875
  super(related);
@@ -10730,6 +10893,32 @@ var Relation = class extends Builder2 {
10730
10893
  getRelated() {
10731
10894
  return this.model;
10732
10895
  }
10896
+ /**
10897
+ * When the related table is the parent's own (a category's children, a user's followers), the existence query reads it
10898
+ * under an alias, `oriel_reserved_<n>`, so its columns aren't the outer row's. The related model takes the alias as its
10899
+ * table, so its qualified columns (keys, soft deletes, a constraint's qualifyColumn()) follow. Returns the alias, or
10900
+ * undefined when the tables differ.
10901
+ */
10902
+ aliasSelfTable(query) {
10903
+ const table = query.getModel().getTable();
10904
+ if (table !== this.parent.getTable()) return void 0;
10905
+ const alias = `oriel_reserved_${selfAliases++}`;
10906
+ query.from(`${table} as ${alias}`);
10907
+ query.getModel().setTable(alias);
10908
+ return alias;
10909
+ }
10910
+ /**
10911
+ * @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,
10912
+ * on the relations that know the column holding the parent's key.
10913
+ */
10914
+ limitEagerPerParent() {
10915
+ const column = this.eagerPartitionColumn();
10916
+ if (column !== void 0) this.limitPerGroup(column);
10917
+ }
10918
+ /** The column of the eager query holding each row's parent key; undefined where a per-parent limit makes no sense. */
10919
+ eagerPartitionColumn() {
10920
+ return void 0;
10921
+ }
10733
10922
  /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
10734
10923
  init() {
10735
10924
  if (relationConstraintsEnabled()) this.addConstraints();
@@ -10812,6 +11001,7 @@ var BelongsTo = class extends Relation {
10812
11001
  return this.associate(null);
10813
11002
  }
10814
11003
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
11004
+ this.aliasSelfTable(query);
10815
11005
  return query.select(...columns).whereColumn(this.getQualifiedForeignKeyName(), "=", this.getQualifiedOwnerKeyName());
10816
11006
  }
10817
11007
  /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */
@@ -10903,7 +11093,11 @@ var BelongsToMany = class extends Relation {
10903
11093
  for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []));
10904
11094
  return models;
10905
11095
  }
11096
+ eagerPartitionColumn() {
11097
+ return this.qualifyPivotColumn(this.foreignPivotKey);
11098
+ }
10906
11099
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
11100
+ this.aliasSelfTable(query);
10907
11101
  return query.select(...columns).join(this.table, this.model.qualifyColumn(this.relatedKey), "=", this.qualifyPivotColumn(this.relatedPivotKey)).whereColumn(this.parent.qualifyColumn(this.parentKey), "=", this.qualifyPivotColumn(this.foreignPivotKey));
10908
11102
  }
10909
11103
  // ---------------------------------------------------------------- the pivot table
@@ -11182,9 +11376,17 @@ var HasOneOrMany = class extends Relation {
11182
11376
  for (const record of records) created.push(await this.create(record));
11183
11377
  return created;
11184
11378
  }
11379
+ eagerPartitionColumn() {
11380
+ return this.foreignKey;
11381
+ }
11185
11382
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
11186
- query.select(...columns).whereColumn(this.getQualifiedParentKeyName(), "=", this.foreignKey);
11187
- if (this.morph) query.where(this.morph.type, "=", this.morph.value);
11383
+ const alias = this.aliasSelfTable(query);
11384
+ const foreignKey = alias === void 0 ? this.foreignKey : `${alias}.${this.getForeignKeyName()}`;
11385
+ query.select(...columns).whereColumn(this.getQualifiedParentKeyName(), "=", foreignKey);
11386
+ if (this.morph) {
11387
+ const type = alias === void 0 ? this.morph.type : `${alias}.${this.morph.type.slice(this.morph.type.lastIndexOf(".") + 1)}`;
11388
+ query.where(type, "=", this.morph.value);
11389
+ }
11188
11390
  return query;
11189
11391
  }
11190
11392
  };
@@ -11323,7 +11525,11 @@ var Factory2 = class _Factory {
11323
11525
  const name = relationship ?? Str.camel(Str.plural(new factory.model().constructor.name));
11324
11526
  return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] });
11325
11527
  }
11326
- /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
11528
+ /**
11529
+ * Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). A factory parent is made
11530
+ * once per make()/create() call, for all of its models, and again by the next call, so a factory kept in a variable
11531
+ * never points at a parent an earlier test rolled back.
11532
+ */
11327
11533
  for(parent, relationship) {
11328
11534
  const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor;
11329
11535
  return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str.camel(cls.name) }] });
@@ -11337,7 +11543,8 @@ var Factory2 = class _Factory {
11337
11543
  /** The attributes only, without a model (a Row, or a Row[] after count()). */
11338
11544
  async raw(attributes = {}) {
11339
11545
  const rows = [];
11340
- for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index));
11546
+ const parents = /* @__PURE__ */ new Map();
11547
+ for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index, parents));
11341
11548
  return this.countValue === void 0 ? rows[0] : rows;
11342
11549
  }
11343
11550
  /** Unsaved models (afterMaking callbacks run). */
@@ -11375,20 +11582,21 @@ var Factory2 = class _Factory {
11375
11582
  }
11376
11583
  async makeModels(attributes) {
11377
11584
  const models = [];
11585
+ const parents = /* @__PURE__ */ new Map();
11378
11586
  for (let index = 0; index < (this.countValue ?? 1); index++) {
11379
- const model = new this.model().forceFill(await this.attributesFor(attributes, index));
11587
+ const model = new this.model().forceFill(await this.attributesFor(attributes, index, parents));
11380
11588
  for (const callback of this.afterMakingCallbacks) await callback(model);
11381
11589
  models.push(model);
11382
11590
  }
11383
11591
  return models;
11384
11592
  }
11385
11593
  /** definition() + states + overrides + for() parents, with factory and function values expanded. */
11386
- async attributesFor(overrides, index) {
11594
+ async attributesFor(overrides, index, parents = /* @__PURE__ */ new Map()) {
11387
11595
  const context = { index, count: this.countValue ?? 1 };
11388
11596
  let attributes = this.definition();
11389
11597
  for (const state of this.states) attributes = { ...attributes, ...typeof state === "function" ? state(attributes, context) : state };
11390
11598
  attributes = { ...attributes, ...overrides };
11391
- for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent));
11599
+ for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent, parents));
11392
11600
  const expanded = {};
11393
11601
  for (const [key, value2] of Object.entries(attributes)) {
11394
11602
  if (value2 instanceof _Factory) expanded[key] = (await value2.createOne()).getKey();
@@ -11398,8 +11606,12 @@ var Factory2 = class _Factory {
11398
11606
  }
11399
11607
  return expanded;
11400
11608
  }
11401
- async parentAttributes(parent) {
11402
- const resolved = parent.resolved ??= parent.parent instanceof Model ? parent.parent : await parent.parent.createOne();
11609
+ async parentAttributes(parent, parents) {
11610
+ let resolved = parents.get(parent);
11611
+ if (resolved === void 0) {
11612
+ resolved = parent.parent instanceof Model ? parent.parent : await parent.parent.createOne();
11613
+ parents.set(parent, resolved);
11614
+ }
11403
11615
  const relation = this.relationOn(new this.model(), parent.relationship);
11404
11616
  if (relation instanceof MorphTo) {
11405
11617
  return { [relation.getForeignKeyName()]: resolved.getKey(), [relation.getMorphType()]: resolved.getMorphClass() };
@@ -11456,7 +11668,7 @@ var MODEL_EVENTS = [
11456
11668
  "forceDeleting",
11457
11669
  "forceDeleted"
11458
11670
  ];
11459
- var muted = new AsyncLocalStorage2();
11671
+ var muted = new AsyncLocalStorage3();
11460
11672
  function modelEventName(event2, className) {
11461
11673
  return `eloquent.${event2}: ${className}`;
11462
11674
  }
@@ -11669,7 +11881,7 @@ var prototypes = /* @__PURE__ */ new Map();
11669
11881
  var unguardedGlobally = { value: false };
11670
11882
  var addingDefaultCounts = /* @__PURE__ */ new Set();
11671
11883
  var PLAIN_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/;
11672
- var unguardedScope = new AsyncLocalStorage3();
11884
+ var unguardedScope = new AsyncLocalStorage4();
11673
11885
  var globalScopes = /* @__PURE__ */ new Map();
11674
11886
  var anonymousScopes = 0;
11675
11887
  function installScopeProxies(cls) {
@@ -12698,8 +12910,11 @@ var Model = class _Model {
12698
12910
  }
12699
12911
  async incrementOrDecrement(column, amount, extra) {
12700
12912
  if (!this.exists) return this.newQueryWithoutRelationships().increment(column, amount, extra);
12701
- const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
12702
12913
  this.forceFill({ ...extra, [column]: Number(this.getAttribute(column) ?? 0) + amount });
12914
+ if (await this.fireModelEvent("updating") === false) return 0;
12915
+ const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
12916
+ this.syncChanges();
12917
+ await this.fireModelEvent("updated", false);
12703
12918
  this.syncOriginalAttributes(column, ...Object.keys(extra));
12704
12919
  return affected;
12705
12920
  }
@@ -13537,12 +13752,14 @@ var TypeGenerator = class {
13537
13752
  const members = attributes.filter(([column]) => !(column in instance));
13538
13753
  const extra = accessors(model).filter(([attribute2]) => !columns.some((column) => column.name === attribute2) && !(attribute2 in instance));
13539
13754
  const statics = scopes(model).filter(([method]) => !(method in Model));
13755
+ const hidden = instance.getHidden().filter((column) => columns.some(({ name: columnName }) => columnName === column));
13540
13756
  const lines = [
13541
13757
  `declare module '${this.modulePath(file)}' {`,
13542
13758
  ` interface ${name} {`,
13543
13759
  " $attributes?: {",
13544
13760
  ...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),
13545
13761
  " }",
13762
+ ...hidden.length ? [` $hidden?: ${hidden.map((column) => `'${column}'`).join(" | ")}`] : [],
13546
13763
  ...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),
13547
13764
  ...extra.map(([attribute2, method]) => ` ${this.key(attribute2)}: ReturnType<${name}['${method}']>`),
13548
13765
  " }"
@@ -17120,7 +17337,7 @@ function registerInertiaCommands(kernel, app2, gateway, options = {}) {
17120
17337
  const runtime = optionText(this.option("runtime")) ?? config2("inertia.ssr.runtime", "node");
17121
17338
  const child = (options.spawn ?? spawn2)(runtime, [bundle], { stdio: "inherit", env: { ...process.env, INERTIA_SSR_PORT: port } });
17122
17339
  return await new Promise((resolve5) => {
17123
- child.on("exit", (code) => resolve5(code ?? 0));
17340
+ child.on("exit", (code, signal) => resolve5(code ?? (signal ? 1 : 0)));
17124
17341
  child.on("error", (error) => {
17125
17342
  this.error(`Could not start the SSR server: ${error.message}`);
17126
17343
  resolve5(1);
@@ -17128,6 +17345,10 @@ function registerInertiaCommands(kernel, app2, gateway, options = {}) {
17128
17345
  });
17129
17346
  }).purpose("Start the Inertia SSR server");
17130
17347
  kernel.command("inertia:stop-ssr", async function() {
17348
+ if (!await gateway.isHealthy()) {
17349
+ this.error("Unable to connect to Inertia SSR server.");
17350
+ return 1;
17351
+ }
17131
17352
  try {
17132
17353
  await fetch(`${gateway.productionUrl()}/shutdown`);
17133
17354
  } catch {
@@ -17906,13 +18127,18 @@ var FailoverTransport = class {
17906
18127
  throw new AllMailersFailedError(this.names, causes);
17907
18128
  }
17908
18129
  };
17909
- var defaultFactory = (config2) => nodemailer.createTransport({
17910
- host: config2.host,
17911
- port: config2.port,
17912
- secure: config2.encryption === "ssl",
17913
- requireTLS: config2.encryption === "tls",
17914
- auth: config2.username ? { user: config2.username, pass: config2.password } : void 0
17915
- });
18130
+ function smtpOptions(config2) {
18131
+ return {
18132
+ host: config2.host,
18133
+ port: config2.port,
18134
+ // With no encryption set, `secure` stays out: nodemailer then speaks TLS on port 465 and STARTTLS where offered.
18135
+ // Port 465 speaks TLS from the start, also when MAIL_ENCRYPTION says 'tls' (as Laravel takes it, smtps).
18136
+ secure: config2.encryption === "ssl" || config2.encryption === "tls" && config2.port === 465 ? true : config2.encryption === "tls" ? false : void 0,
18137
+ requireTLS: config2.encryption === "tls" && config2.port !== 465 ? true : void 0,
18138
+ auth: config2.username ? { user: config2.username, pass: config2.password } : void 0
18139
+ };
18140
+ }
18141
+ var defaultFactory = (config2) => nodemailer.createTransport(smtpOptions(config2));
17916
18142
  var SmtpTransport = class {
17917
18143
  transporter;
17918
18144
  constructor(config2, factory = defaultFactory) {
@@ -19065,14 +19291,14 @@ var PipelineServiceProvider = class {
19065
19291
  import { Buffer as Buffer2 } from "buffer";
19066
19292
  import { randomUUID as randomUUID5 } from "crypto";
19067
19293
  import { randomUUID as randomUUID24 } from "crypto";
19294
+ import { existsSync as existsSync8, readdirSync as readdirSync7, statSync as statSync3 } from "fs";
19295
+ import { dirname as dirname7, join as join13, relative as relative6, sep as sep5 } from "path";
19296
+ import { pathToFileURL as pathToFileURL6 } from "url";
19068
19297
  import { Redis as Redis2 } from "ioredis";
19069
19298
  import { randomUUID as randomUUID32 } from "crypto";
19070
19299
  import { setTimeout as sleep4 } from "timers/promises";
19071
19300
  import { spawn as spawnProcess } from "child_process";
19072
19301
  import { setTimeout as sleep22 } from "timers/promises";
19073
- import { existsSync as existsSync8, readdirSync as readdirSync7, statSync as statSync3 } from "fs";
19074
- import { join as join13 } from "path";
19075
- import { pathToFileURL as pathToFileURL6 } from "url";
19076
19302
  var QueueError = class extends Error {
19077
19303
  kind = "Server";
19078
19304
  status = 500;
@@ -19556,13 +19782,19 @@ var CallQueuedHandler = class {
19556
19782
  if (payload.batchId !== void 0 && payload.batchCallback !== true && this.container.bound(BatchRepository)) {
19557
19783
  await this.container.make(BatchRepository).recordFailedJob(payload.batchId, payload.uuid, error);
19558
19784
  }
19785
+ const chain = { connection: payload.chainConnection ?? job.getConnectionName(), queue: payload.chainQueue };
19559
19786
  for (const callback of payload.chainCatch ?? []) {
19560
- await this.dispatchCallback(await restoreJob(callback, this.container.make(ClassRegistry)));
19787
+ await this.dispatchCallback(await restoreJob(callback, this.container.make(ClassRegistry)), chain);
19561
19788
  }
19562
19789
  if (instance && typeof instance.failed === "function") await instance.failed(error);
19563
19790
  }
19564
- /** Dispatches a callback job (chain catch, batch then/catch/finally) through the Bus, or runs it inline. */
19565
- async dispatchCallback(callback) {
19791
+ /**
19792
+ * Dispatches a callback job (chain catch, batch then/catch/finally) through the Bus, or runs it inline. It goes to
19793
+ * `target`'s connection and queue (the chain's or the batch's) unless it names its own.
19794
+ */
19795
+ async dispatchCallback(callback, target = {}) {
19796
+ if (!callback.connection && target.connection) callback.connection = target.connection;
19797
+ if (!callback.queue && target.queue) callback.queue = target.queue;
19566
19798
  if (this.container.bound(BusDispatcher)) await this.container.make(BusDispatcher).dispatch(callback);
19567
19799
  else await callback.handle();
19568
19800
  }
@@ -19656,6 +19888,90 @@ var WithoutOverlapping = class {
19656
19888
  return void 0;
19657
19889
  }
19658
19890
  };
19891
+ var EXTENSIONS2 = [".ts", ".js", ".mts", ".mjs"];
19892
+ function files2(directory) {
19893
+ const found = [];
19894
+ for (const entry of readdirSync7(directory).sort()) {
19895
+ const path = join13(directory, entry);
19896
+ if (statSync3(path).isDirectory()) found.push(...files2(path));
19897
+ else if (EXTENSIONS2.some((extension) => entry.endsWith(extension)) && !entry.endsWith(".d.ts")) found.push(path);
19898
+ }
19899
+ return found;
19900
+ }
19901
+ var WORKER_DISCOVERY_DIRECTORIES = ["Events", "Listeners", "Mail", "Notifications"];
19902
+ var isClass2 = (value2) => typeof value2 === "function" && /^class[\s{]/.test(Function.prototype.toString.call(value2));
19903
+ var isJobClass = (value2) => typeof value2.prototype.handle === "function";
19904
+ async function discoverClasses(directory, registry2, filter = () => true) {
19905
+ if (!existsSync8(directory)) return [];
19906
+ const names = [];
19907
+ for (const file of files2(directory)) {
19908
+ const module = await import(pathToFileURL6(file).href);
19909
+ for (const exported of Object.values(module)) {
19910
+ if (isClass2(exported) && filter(exported)) names.push(classNameOf(registry2, exported));
19911
+ }
19912
+ }
19913
+ return names;
19914
+ }
19915
+ function discoverJobs(directory, registry2) {
19916
+ return discoverClasses(directory, registry2, isJobClass);
19917
+ }
19918
+ var ready = /* @__PURE__ */ new WeakMap();
19919
+ function registerAppClasses(appPath, registry2) {
19920
+ const running = discover(appPath, registry2);
19921
+ ready.set(registry2, running);
19922
+ return running;
19923
+ }
19924
+ async function discover(appPath, registry2) {
19925
+ const found = [];
19926
+ const seen = /* @__PURE__ */ new Set();
19927
+ for (const directory of ["Jobs", ...WORKER_DISCOVERY_DIRECTORIES]) {
19928
+ const root = join13(appPath, directory);
19929
+ if (!existsSync8(root)) continue;
19930
+ for (const file of files2(root)) {
19931
+ let module;
19932
+ try {
19933
+ module = await import(pathToFileURL6(file).href);
19934
+ } catch (error) {
19935
+ console.warn(`Oriel couldn't load ${relative6(appPath, file)} to name its classes for the queue: ${error instanceof Error ? error.message : String(error)}`);
19936
+ continue;
19937
+ }
19938
+ const folder = relative6(appPath, dirname7(file)).split(sep5).join(".");
19939
+ for (const exported of Object.values(module)) {
19940
+ if (!isClass2(exported) || seen.has(exported) || directory === "Jobs" && !isJobClass(exported)) continue;
19941
+ seen.add(exported);
19942
+ found.push({ cls: exported, folder });
19943
+ }
19944
+ }
19945
+ }
19946
+ const unnamed = found.filter(({ cls }) => registry2.nameOf(cls) === void 0);
19947
+ const sharing = /* @__PURE__ */ new Map();
19948
+ for (const { cls } of unnamed) sharing.set(cls.name, (sharing.get(cls.name) ?? 0) + 1);
19949
+ for (const { cls, folder } of unnamed) {
19950
+ if ((sharing.get(cls.name) ?? 0) > 1) {
19951
+ registry2.register(cls, `${folder}.${cls.name}`);
19952
+ continue;
19953
+ }
19954
+ try {
19955
+ classNameOf(registry2, cls);
19956
+ } catch (error) {
19957
+ if (!(error instanceof JobSerializationError)) throw error;
19958
+ registry2.register(cls, `${folder}.${cls.name}`);
19959
+ }
19960
+ }
19961
+ }
19962
+ async function ensureAppClasses(container) {
19963
+ const registry2 = container.make(ClassRegistry);
19964
+ let running = ready.get(registry2);
19965
+ if (running === void 0) {
19966
+ running = container.bound(Application) ? registerAppClasses(container.make(Application).appPath(), registry2) : Promise.resolve();
19967
+ running = running.catch((error) => {
19968
+ ready.delete(registry2);
19969
+ throw error;
19970
+ });
19971
+ ready.set(registry2, running);
19972
+ }
19973
+ await running;
19974
+ }
19659
19975
  var QueueBase = class {
19660
19976
  constructor(container, defaultQueue = "default") {
19661
19977
  this.container = container;
@@ -19680,10 +19996,12 @@ var QueueBase = class {
19680
19996
  createPayload(job) {
19681
19997
  return createPayload(job, this.container.make(ClassRegistry));
19682
19998
  }
19683
- push(job, queue) {
19999
+ async push(job, queue) {
20000
+ await ensureAppClasses(this.container);
19684
20001
  return this.pushRaw(this.createPayload(job), queue ?? (optionalString2(job.queue) || void 0));
19685
20002
  }
19686
- later(delaySeconds2, job, queue) {
20003
+ async later(delaySeconds2, job, queue) {
20004
+ await ensureAppClasses(this.container);
19687
20005
  return this.pushRaw(this.createPayload(job), queue ?? (optionalString2(job.queue) || void 0), delaySeconds2);
19688
20006
  }
19689
20007
  /** Closes network connections (redis). No-op by default. */
@@ -20329,6 +20647,7 @@ var DatabaseBatchRepository = class {
20329
20647
  handler;
20330
20648
  async store(options) {
20331
20649
  const id = randomUUID32();
20650
+ await ensureAppClasses(this.container);
20332
20651
  const registry2 = this.container.make(ClassRegistry);
20333
20652
  const payloads = (jobs) => jobs.map((job) => createPayload(job, registry2));
20334
20653
  const stored = {
@@ -20417,7 +20736,7 @@ var DatabaseBatchRepository = class {
20417
20736
  const job = await restoreJob(payload, registry2);
20418
20737
  job.batchId = batch.id;
20419
20738
  setSymbolValue(job, BATCH_CALLBACK, true);
20420
- await this.handler.dispatchCallback(job);
20739
+ await this.handler.dispatchCallback(job, { connection: batch.options.connection, queue: batch.options.queue });
20421
20740
  }
20422
20741
  }
20423
20742
  toBatch(row) {
@@ -20861,33 +21180,6 @@ var Listener = class _Listener {
20861
21180
  }
20862
21181
  }
20863
21182
  };
20864
- var EXTENSIONS2 = [".ts", ".js", ".mts", ".mjs"];
20865
- function files2(directory) {
20866
- const found = [];
20867
- for (const entry of readdirSync7(directory).sort()) {
20868
- const path = join13(directory, entry);
20869
- if (statSync3(path).isDirectory()) found.push(...files2(path));
20870
- else if (EXTENSIONS2.some((extension) => entry.endsWith(extension)) && !entry.endsWith(".d.ts")) found.push(path);
20871
- }
20872
- return found;
20873
- }
20874
- var WORKER_DISCOVERY_DIRECTORIES = ["Events", "Listeners", "Mail", "Notifications"];
20875
- var isClass2 = (value2) => typeof value2 === "function" && /^class[\s{]/.test(Function.prototype.toString.call(value2));
20876
- var isJobClass = (value2) => typeof value2.prototype.handle === "function";
20877
- async function discoverClasses(directory, registry2, filter = () => true) {
20878
- if (!existsSync8(directory)) return [];
20879
- const names = [];
20880
- for (const file of files2(directory)) {
20881
- const module = await import(pathToFileURL6(file).href);
20882
- for (const exported of Object.values(module)) {
20883
- if (isClass2(exported) && filter(exported)) names.push(classNameOf(registry2, exported));
20884
- }
20885
- }
20886
- return names;
20887
- }
20888
- function discoverJobs(directory, registry2) {
20889
- return discoverClasses(directory, registry2, isJobClass);
20890
- }
20891
21183
  var text3 = (value2) => optionalString2(value2) || void 0;
20892
21184
  var list4 = (value2) => Array.isArray(value2) ? value2.map(String) : text3(value2) ? [String(value2)] : [];
20893
21185
  var number2 = (value2, fallback) => {
@@ -20951,8 +21243,7 @@ function registerQueueCommands(kernel, context) {
20951
21243
  const connection = text3(out.argument("connection")) ?? defaultConnection();
20952
21244
  const queue = text3(out.option("queue")) ?? defaultQueue(connection);
20953
21245
  const registry2 = container.make(ClassRegistry);
20954
- await discoverJobs(context.app.appPath("Jobs"), registry2);
20955
- for (const directory of WORKER_DISCOVERY_DIRECTORIES) await discoverClasses(context.app.appPath(directory), registry2);
21246
+ await registerAppClasses(context.app.appPath(), registry2);
20956
21247
  const name = (job) => job.payload().displayName;
20957
21248
  const worker = new Worker(container.make(QueueManager), container, {
20958
21249
  processing: (job) => out.line(` ${localTimestamp()} ${name(job)} RUNNING`),
@@ -23993,8 +24284,8 @@ function resolveDateParam(ctx, rule, param, format2) {
23993
24284
  const parsed = readDate(fieldValue, ctx.getRule?.(param, "date_format")?.[0] ?? format2);
23994
24285
  if (!Number.isNaN(parsed)) return parsed;
23995
24286
  }
23996
- const relative9 = relativeDate(param);
23997
- if (relative9 !== void 0) return relative9;
24287
+ const relative10 = relativeDate(param);
24288
+ if (relative10 !== void 0) return relative10;
23998
24289
  const literal = readDate(param, format2);
23999
24290
  if (!Number.isNaN(literal)) return literal;
24000
24291
  if (FIELD_REFERENCE_RE.test(param)) return null;
@@ -25581,7 +25872,7 @@ var ValidationServiceProvider = class extends ServiceProvider {
25581
25872
  // ../Vercel/dist/index.js
25582
25873
  import { existsSync as existsSync9, readdirSync as readdirSync8, readFileSync as readFileSync3, realpathSync, statSync as statSync4 } from "fs";
25583
25874
  import { cp, mkdir as mkdir7, rm as rm4, writeFile as writeFile8 } from "fs/promises";
25584
- import { basename as basename3, dirname as dirname7, join as join15, relative as relative6, resolve as resolve4 } from "path";
25875
+ import { basename as basename3, dirname as dirname8, join as join15, relative as relative7, resolve as resolve4 } from "path";
25585
25876
  import { CronExpressionParser as CronExpressionParser2 } from "cron-parser";
25586
25877
  import { timingSafeEqual as timingSafeEqual8 } from "crypto";
25587
25878
  import { CronExpressionParser as CronExpressionParser3 } from "cron-parser";
@@ -25693,7 +25984,7 @@ async function buildVercelOutput(app2, options = {}) {
25693
25984
  const staticFolder = join15(output, "static");
25694
25985
  await mkdir7(staticFolder, { recursive: true });
25695
25986
  if (existsSync9(publicPath)) {
25696
- await cp(publicPath, staticFolder, { recursive: true, filter: (source) => basename3(source) !== "hot" && !isEnvFile(source) });
25987
+ await cp(publicPath, staticFolder, { recursive: true, filter: (source) => basename3(source) !== "hot" && !isEnvFile(source) && isPublicAsset(relative7(publicPath, source)) });
25697
25988
  }
25698
25989
  const fn = join15(output, "functions/index.func");
25699
25990
  for (const folder of APP_FOLDERS) {
@@ -25703,7 +25994,7 @@ async function buildVercelOutput(app2, options = {}) {
25703
25994
  for (const file of APP_FILES) if (existsSync9(join15(base, file))) await cp(join15(base, file), join15(fn, file));
25704
25995
  for (const file of BUILD_FILES) {
25705
25996
  const source = join15(publicPath, "build", file);
25706
- if (existsSync9(source)) await cp(source, join15(fn, relative6(base, publicPath), "build", file));
25997
+ if (existsSync9(source)) await cp(source, join15(fn, relative7(base, publicPath), "build", file));
25707
25998
  }
25708
25999
  await copyDependencies(base, fn);
25709
26000
  await writeFile8(join15(fn, "index.mjs"), LAUNCHER);
@@ -25780,10 +26071,10 @@ async function copyDependencies(base, fn) {
25780
26071
  for (const name of [...Object.keys(manifest.dependencies ?? {}), "tsx"]) await visit(name, base, join15(fn, "node_modules"));
25781
26072
  }
25782
26073
  function locate(name, from) {
25783
- for (let dir = from; ; dir = dirname7(dir)) {
26074
+ for (let dir = from; ; dir = dirname8(dir)) {
25784
26075
  const candidate = basename3(dir) === "node_modules" ? join15(dir, name) : join15(dir, "node_modules", name);
25785
26076
  if (existsSync9(join15(candidate, "package.json"))) return candidate;
25786
- if (dirname7(dir) === dir) return void 0;
26077
+ if (dirname8(dir) === dir) return void 0;
25787
26078
  }
25788
26079
  }
25789
26080
  function sizeOf2(folder) {
@@ -25823,16 +26114,16 @@ var VercelServiceProvider = class extends ServiceProvider {
25823
26114
 
25824
26115
  // ide/IdeInfoCommand.ts
25825
26116
  import { existsSync as existsSync11, readdirSync as readdirSync10, readFileSync as readFileSync4 } from "fs";
25826
- import { join as join17, relative as relative8, sep as sep6 } from "path";
26117
+ import { join as join17, relative as relative9, sep as sep7 } from "path";
25827
26118
 
25828
26119
  // ide/sections.ts
25829
26120
  import { existsSync as existsSync10, readdirSync as readdirSync9 } from "fs";
25830
- import { join as join16, relative as relative7, sep as sep5 } from "path";
26121
+ import { join as join16, relative as relative8, sep as sep6 } from "path";
25831
26122
  import { parse as parse2 } from "dotenv";
25832
26123
  var SECRET = /key|secret|password|token|credential|salt|private/i;
25833
26124
  var CREDENTIALS = /^[a-z][a-z0-9+.-]*:\/\/[^/?#\s]*@/i;
25834
26125
  var byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
25835
- var posix3 = (path) => path.split(sep5).join("/");
26126
+ var posix3 = (path) => path.split(sep6).join("/");
25836
26127
  function commandSection(all) {
25837
26128
  return Object.entries(all).map(([name, command]) => {
25838
26129
  const signature = parseSignature(command.signature);
@@ -25874,8 +26165,8 @@ function viewSection(paths, hints, extensions, basePath) {
25874
26165
  const extension = extensions.find((candidate) => item.name.endsWith(`.${candidate}`));
25875
26166
  if (extension === void 0) continue;
25876
26167
  const file = join16(item.parentPath, item.name);
25877
- const name = prefix + posix3(relative7(root, file)).slice(0, -(extension.length + 1)).split("/").join(".");
25878
- if (!views.has(name)) views.set(name, posix3(relative7(basePath, file)));
26168
+ const name = prefix + posix3(relative8(root, file)).slice(0, -(extension.length + 1)).split("/").join(".");
26169
+ if (!views.has(name)) views.set(name, posix3(relative8(basePath, file)));
25879
26170
  }
25880
26171
  };
25881
26172
  for (const path of paths) collect2(path, "");
@@ -25884,7 +26175,7 @@ function viewSection(paths, hints, extensions, basePath) {
25884
26175
  }
25885
26176
 
25886
26177
  // ide/IdeInfoCommand.ts
25887
- var posix4 = (path) => path.split(sep6).join("/");
26178
+ var posix4 = (path) => path.split(sep7).join("/");
25888
26179
  var read = (file) => existsSync11(file) ? readFileSync4(file, "utf8") : null;
25889
26180
  var IdeInfoCommand = class extends Command {
25890
26181
  signature = "ide:info {--pretty : Indent the JSON}";
@@ -25916,7 +26207,7 @@ function describe(app2, container) {
25916
26207
  const basePath = app2.basePath();
25917
26208
  const config2 = optional(ConfigRepository);
25918
26209
  const get = (key, fallback) => config2 ? config2.get(key, fallback) : fallback;
25919
- const relativeTo = (file) => posix4(relative8(basePath, file));
26210
+ const relativeTo = (file) => posix4(relative9(basePath, file));
25920
26211
  const configDirectory = app2.configPath();
25921
26212
  const configFiles = existsSync11(configDirectory) ? readdirSync10(configDirectory).filter((file) => /\.(ts|js|mjs)$/.test(file)).map((file) => relativeTo(join17(configDirectory, file))) : [];
25922
26213
  const factory = optional(ViewFactory);