@orieljs/framework 0.1.0-alpha.13 → 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.
Files changed (56) hide show
  1. package/dist/{chunk-OTCTQVDQ.js → chunk-7GPMFMS7.js} +349 -67
  2. package/dist/chunk-7GPMFMS7.js.map +1 -0
  3. package/dist/{chunk-CKH4KCYF.js → chunk-BKA5F3TH.js} +1 -1
  4. package/dist/{chunk-CKH4KCYF.js.map → chunk-BKA5F3TH.js.map} +1 -1
  5. package/dist/{chunk-6GMXKQ6O.js → chunk-FVI6X3VJ.js} +55 -2
  6. package/dist/chunk-FVI6X3VJ.js.map +1 -0
  7. package/dist/{chunk-ZRTWDJKD.js → chunk-GCMPAXIK.js} +98 -4
  8. package/dist/chunk-GCMPAXIK.js.map +1 -0
  9. package/dist/contracts.d.ts +4 -1
  10. package/dist/contracts.js +1 -1
  11. package/dist/{index.d-WQpfdIbG.d.ts → index.d-lffxurFs.d.ts} +10 -1
  12. package/dist/index.d.ts +233 -37
  13. package/dist/index.js +823 -307
  14. package/dist/index.js.map +1 -1
  15. package/dist/{jsx-runtime-6um4Mwfb.d.ts → jsx-runtime-Bc5KJzwb.d.ts} +1 -1
  16. package/dist/jsx-runtime.d.ts +2 -2
  17. package/dist/jsx-runtime.js +3 -3
  18. package/dist/{testing-B8NOiQC9.d.ts → testing-CVpo7aRl.d.ts} +41 -7
  19. package/dist/testing.d.ts +2 -2
  20. package/dist/testing.js +5 -3
  21. package/docs/authentication.md +40 -1
  22. package/docs/console.md +16 -5
  23. package/docs/database-testing.md +21 -0
  24. package/docs/database.md +17 -2
  25. package/docs/deployment.md +12 -3
  26. package/docs/eloquent-factories.md +3 -0
  27. package/docs/eloquent-observers.md +2 -0
  28. package/docs/eloquent-relationships.md +8 -0
  29. package/docs/eloquent.md +6 -0
  30. package/docs/encryption.md +2 -0
  31. package/docs/export.md +3 -3
  32. package/docs/inertia.md +2 -1
  33. package/docs/installation.md +4 -1
  34. package/docs/lifecycle.md +5 -4
  35. package/docs/live-tests.md +20 -0
  36. package/docs/live.md +2 -0
  37. package/docs/mail.md +4 -2
  38. package/docs/navigation.json +4 -0
  39. package/docs/pagination.md +10 -0
  40. package/docs/providers.md +1 -1
  41. package/docs/queues.md +6 -0
  42. package/docs/responses.md +2 -1
  43. package/docs/routing.md +33 -0
  44. package/docs/scheduling.md +2 -0
  45. package/docs/session.md +19 -2
  46. package/docs/starter-kits.md +4 -0
  47. package/docs/storage.md +21 -3
  48. package/docs/testing.md +9 -6
  49. package/docs/two-factor.md +14 -4
  50. package/docs/upgrade.md +73 -0
  51. package/docs/views.md +2 -0
  52. package/docs/vite.md +19 -1
  53. package/package.json +54 -38
  54. package/dist/chunk-6GMXKQ6O.js.map +0 -1
  55. package/dist/chunk-OTCTQVDQ.js.map +0 -1
  56. package/dist/chunk-ZRTWDJKD.js.map +0 -1
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  renderToString,
23
23
  styleString,
24
24
  view
25
- } from "./chunk-ZRTWDJKD.js";
25
+ } from "./chunk-GCMPAXIK.js";
26
26
  import {
27
27
  API_ROUTES_STUB,
28
28
  Application as Application2,
@@ -84,6 +84,7 @@ import {
84
84
  TrimStrings,
85
85
  UPDATE_URI,
86
86
  UPLOAD_URI,
87
+ UploadAlreadyStoredError,
87
88
  UploadValidationError,
88
89
  Vite,
89
90
  ViteError,
@@ -149,7 +150,7 @@ import {
149
150
  vite,
150
151
  viteReactRefresh,
151
152
  writeResponse
152
- } from "./chunk-OTCTQVDQ.js";
153
+ } from "./chunk-7GPMFMS7.js";
153
154
  import {
154
155
  Arr,
155
156
  BindingResolutionError,
@@ -160,6 +161,7 @@ import {
160
161
  ContainerNotAvailableError,
161
162
  ItemNotFoundError,
162
163
  LazyCollection,
164
+ MissingPackageError,
163
165
  MultipleItemsFoundError,
164
166
  ServiceProvider,
165
167
  Str,
@@ -171,12 +173,14 @@ import {
171
173
  currentContainer,
172
174
  facade,
173
175
  fileType_exports,
176
+ importOptional,
174
177
  inject,
178
+ isPublicAsset,
175
179
  now,
176
180
  retry,
177
181
  tap,
178
182
  value
179
- } from "./chunk-6GMXKQ6O.js";
183
+ } from "./chunk-FVI6X3VJ.js";
180
184
  import {
181
185
  Application,
182
186
  AuthFactory,
@@ -218,25 +222,26 @@ import {
218
222
  ValidationFactory,
219
223
  ViewFactory,
220
224
  token
221
- } from "./chunk-CKH4KCYF.js";
225
+ } from "./chunk-BKA5F3TH.js";
222
226
 
223
227
  // ../Auth/dist/index.js
224
228
  import { createHash } from "crypto";
225
229
  import { createHash as createHash2 } from "crypto";
226
230
  import { timingSafeEqual } from "crypto";
227
231
  import { createHash as createHash3 } from "crypto";
228
- import { createHash as createHash4 } from "crypto";
229
232
  import { createHmac } from "crypto";
233
+ import { createHash as createHash4 } from "crypto";
234
+ import { createHmac as createHmac2 } from "crypto";
230
235
  import { readdir } from "fs/promises";
231
236
  import { join } from "path";
232
237
  import { pathToFileURL } from "url";
233
238
  import { relative } from "path";
234
239
  import { existsSync, mkdirSync, readdirSync, writeFileSync } from "fs";
235
240
  import { join as join2 } from "path";
236
- import { createHmac as createHmac3, randomBytes as randomBytes2, randomInt as randomInt2, timingSafeEqual as timingSafeEqual3 } from "crypto";
241
+ import { createHmac as createHmac4, randomBytes as randomBytes2, randomInt as randomInt2, timingSafeEqual as timingSafeEqual3 } from "crypto";
237
242
  import { renderSVG } from "uqr";
238
243
  import { randomInt } from "crypto";
239
- import { createHmac as createHmac2, randomBytes, timingSafeEqual as timingSafeEqual2 } from "crypto";
244
+ import { createHmac as createHmac3, randomBytes, timingSafeEqual as timingSafeEqual2 } from "crypto";
240
245
  var AuthenticationError = class extends Error {
241
246
  constructor(message = "Unauthenticated.", guards = [], redirectTo2) {
242
247
  super(message);
@@ -249,6 +254,18 @@ var AuthenticationError = class extends Error {
249
254
  status = 401;
250
255
  name = "AuthenticationError";
251
256
  };
257
+ var InvalidPasswordError = class extends Error {
258
+ name = "InvalidPasswordError";
259
+ constructor() {
260
+ super("The given password does not match the current password.");
261
+ }
262
+ };
263
+ var TwoFactorAppAlreadyEnabledError = class extends Error {
264
+ name = "TwoFactorAppAlreadyEnabledError";
265
+ constructor() {
266
+ super("This user's authenticator app is set up already. Call TwoFactor.disableApp(user) first to set up another.");
267
+ }
268
+ };
252
269
  var AuthorizationError = class extends Error {
253
270
  kind = "Authorization";
254
271
  name = "AuthorizationError";
@@ -306,6 +323,22 @@ var Logout = class {
306
323
  guard;
307
324
  user;
308
325
  };
326
+ var CurrentDeviceLogout = class {
327
+ constructor(guard2, user) {
328
+ this.guard = guard2;
329
+ this.user = user;
330
+ }
331
+ guard;
332
+ user;
333
+ };
334
+ var OtherDeviceLogout = class {
335
+ constructor(guard2, user) {
336
+ this.guard = guard2;
337
+ this.user = user;
338
+ }
339
+ guard;
340
+ user;
341
+ };
309
342
  var PasswordReset = class {
310
343
  constructor(user) {
311
344
  this.user = user;
@@ -572,6 +605,13 @@ var EloquentUserProvider = class {
572
605
  return this.model;
573
606
  }
574
607
  };
608
+ var passwordHashKey = (guard2) => `password_hash_${guard2}`;
609
+ function sessionPasswordHash(passwordHash, key) {
610
+ return createHmac("sha256", key).update(passwordHash).digest("hex");
611
+ }
612
+ function matchesSessionPasswordHash(passwordHash, stored, keys) {
613
+ return keys.some((key) => equals(sessionPasswordHash(passwordHash, key), stored));
614
+ }
575
615
  var GUARD_HASH = createHash3("sha1").update("Oriel\\Auth\\SessionGuard").digest("hex");
576
616
  var SessionGuard = class {
577
617
  constructor(name, provider, container, options = {}) {
@@ -626,12 +666,7 @@ var SessionGuard = class {
626
666
  const user = await this.provider.retrieveByCredentials(credentials);
627
667
  this.#lastAttempted = user;
628
668
  if (user !== void 0 && await this.#hasValidCredentials(user, credentials)) {
629
- if (this.options.rehashOnLogin !== false) {
630
- await this.provider.rehashPasswordIfRequired?.(
631
- user,
632
- credentials
633
- );
634
- }
669
+ await this.rehashIfRequired(user, credentials);
635
670
  await this.login(user, remember);
636
671
  return true;
637
672
  }
@@ -665,15 +700,96 @@ var SessionGuard = class {
665
700
  /** Forgets the user, the session key and the remember cookie, and cycles the remember token. */
666
701
  async logout() {
667
702
  const user = await this.user();
668
- this.#session()?.forget(this.getName());
669
- const jar = this.#jar();
670
- if (jar !== void 0 && this.#request()?.cookie(this.getRecallerName()) !== void 0) {
671
- jar.queue(jar.forget(this.getRecallerName()));
672
- }
703
+ this.#forget();
673
704
  if (user !== void 0 && user.getRememberToken() !== void 0) await this.#cycleRememberToken(user);
674
705
  await this.#dispatch(new Logout(this.name, user));
675
- this.#user = void 0;
676
- this.#loggedOut = true;
706
+ this.#signedOut();
707
+ }
708
+ /** Logs out here only: the remember token isn't cycled, so the user's other remembered devices keep working. */
709
+ async logoutCurrentDevice() {
710
+ const user = await this.user();
711
+ this.#forget();
712
+ await this.#dispatch(new CurrentDeviceLogout(this.name, user));
713
+ this.#signedOut();
714
+ }
715
+ /**
716
+ * Ends the user's other sessions, on their next request through `auth.session`, by rehashing the password they gave.
717
+ * This session stays signed in, and so does this device's remember cookie. Undefined for a guest.
718
+ */
719
+ async logoutOtherDevices(password) {
720
+ const user = await this.user();
721
+ if (user === void 0) return void 0;
722
+ if (!await this.container.make(Hasher).check(password, user.getAuthPassword())) throw new InvalidPasswordError();
723
+ const provider = this.provider;
724
+ if (provider.rehashPasswordIfRequired === void 0) throw new Error(`The [${this.name}] guard's user provider can't rehash a password.`);
725
+ await provider.rehashPasswordIfRequired(user, { password }, true);
726
+ this.keepPasswordHash();
727
+ const recaller = this.getRecallerName();
728
+ const mine = (value2) => value2?.split("|")[0] === String(user.getAuthIdentifier());
729
+ const remembered = mine(this.#request()?.cookie(recaller)) || this.#jar()?.queued().some((cookie2) => cookie2.name === recaller && mine(cookie2.value)) === true;
730
+ if (remembered) this.#queueRecallerCookie(user);
731
+ await this.#dispatch(new OtherDeviceLogout(this.name, user));
732
+ return user;
733
+ }
734
+ /** @internal Whether this request has a session: a cached page's route leaves StartSession out. */
735
+ hasStartedSession() {
736
+ const session2 = this.#session();
737
+ return session2 !== void 0 && (session2.isStarted?.() ?? true);
738
+ }
739
+ /**
740
+ * @internal For `auth.session`: whether the signed-in user's password is the one this session and this device's remember
741
+ * cookie were made with. A session with no stored hash stores one and carries on.
742
+ */
743
+ passwordHashMatches() {
744
+ const user = this.#user;
745
+ if (user === void 0) return true;
746
+ if (this.#viaRemember) {
747
+ const remembered = this.#request()?.cookie(this.getRecallerName())?.split("|")[2];
748
+ if (remembered === void 0 || !equals(user.getAuthPassword(), remembered)) return false;
749
+ }
750
+ const stored = this.#session()?.get(passwordHashKey(this.name));
751
+ if (stored === void 0) {
752
+ this.keepPasswordHash();
753
+ return true;
754
+ }
755
+ return matchesSessionPasswordHash(user.getAuthPassword(), stored, this.#encryptionKeys());
756
+ }
757
+ /**
758
+ * @internal After a request: this session keeps the current password's hash, which covers a login and a new password,
759
+ * and `before` (the password the request began with) tells when this device's remember cookie needs the new one too.
760
+ */
761
+ keepPasswordHash(before) {
762
+ const user = this.#user;
763
+ if (user === void 0) return;
764
+ const hash2 = user.getAuthPassword();
765
+ if (hash2 === "") return;
766
+ this.#session()?.put(passwordHashKey(this.name), sessionPasswordHash(hash2, this.#encryptionKeys()[0]));
767
+ const recaller = this.#request()?.cookie(this.getRecallerName());
768
+ if (before !== void 0 && before !== hash2 && recaller?.split("|")[0] === String(user.getAuthIdentifier())) {
769
+ this.#queueRecallerCookie(user);
770
+ }
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;
677
793
  }
678
794
  hasUser() {
679
795
  return this.#user !== void 0;
@@ -697,6 +813,23 @@ var SessionGuard = class {
697
813
  getRecallerName() {
698
814
  return `remember_${this.name}_${GUARD_HASH}`;
699
815
  }
816
+ /** Forgets the session key and, when this request had one, the remember cookie. */
817
+ #forget() {
818
+ this.#session()?.forget(this.getName());
819
+ const jar = this.#jar();
820
+ if (jar !== void 0 && this.#request()?.cookie(this.getRecallerName()) !== void 0) {
821
+ jar.queue(jar.forget(this.getRecallerName()));
822
+ }
823
+ }
824
+ #signedOut() {
825
+ this.#user = void 0;
826
+ this.#loggedOut = true;
827
+ }
828
+ /** The app's keys, the current one first. */
829
+ #encryptionKeys() {
830
+ const encrypter = this.container.make(Encrypter);
831
+ return encrypter.getAllKeys?.() ?? [encrypter.getKey()];
832
+ }
700
833
  async #hasValidCredentials(user, credentials) {
701
834
  const valid = user !== void 0 && await this.provider.validateCredentials(user, credentials);
702
835
  if (valid) await this.#dispatch(new Validated(this.name, user));
@@ -855,7 +988,7 @@ var TokenRepository = class {
855
988
  }
856
989
  const id = plainText.slice(0, separator);
857
990
  const secret = plainText.slice(separator + 1);
858
- if (id === "" || secret === "") return void 0;
991
+ if (!/^\d{1,18}$/.test(id) || secret === "") return void 0;
859
992
  const row = await this.#query().where("id", id).first();
860
993
  if (row === void 0 || typeof row.token !== "string" || !equals(row.token, sha256(secret))) return void 0;
861
994
  return new PersonalAccessToken(row, this);
@@ -1024,6 +1157,16 @@ var AuthManager = class {
1024
1157
  createUserProvider(name) {
1025
1158
  return this.#createUserProvider(name, true);
1026
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
+ }
1027
1170
  /** Forget the resolved guards of the current scope (tests). */
1028
1171
  forgetGuards() {
1029
1172
  this.#scopes.delete(this.#container());
@@ -1065,6 +1208,14 @@ var AuthManager = class {
1065
1208
  async logout() {
1066
1209
  return this.#stateful().logout();
1067
1210
  }
1211
+ /** Logs the default guard out on this device only (the remember token isn't cycled). */
1212
+ async logoutCurrentDevice() {
1213
+ return this.#deviceGuard().logoutCurrentDevice();
1214
+ }
1215
+ /** Ends the user's other sessions, on their next request through `auth.session`. This one stays signed in. */
1216
+ async logoutOtherDevices(password) {
1217
+ return this.#deviceGuard().logoutOtherDevices(password);
1218
+ }
1068
1219
  viaRemember() {
1069
1220
  const guard2 = this.guard();
1070
1221
  return guard2.viaRemember?.() ?? false;
@@ -1127,6 +1278,13 @@ var AuthManager = class {
1127
1278
  state.resolverInstalled = true;
1128
1279
  container.make(HttpRequest).setUserResolver((guard2) => this.guardIn(container, guard2).user());
1129
1280
  }
1281
+ #deviceGuard() {
1282
+ const guard2 = this.guard();
1283
+ if (typeof guard2.logoutOtherDevices !== "function") {
1284
+ throw new Error(`The [${guard2.name ?? this.#state(this.#container()).defaultGuard ?? this.getDefaultDriver()}] guard can't log out other devices.`);
1285
+ }
1286
+ return guard2;
1287
+ }
1130
1288
  #stateful() {
1131
1289
  const guard2 = this.guard();
1132
1290
  if (typeof guard2.attempt !== "function") {
@@ -1476,7 +1634,7 @@ var DatabaseTokenRepository = class {
1476
1634
  async create(user) {
1477
1635
  const email = user.getEmailForPasswordReset();
1478
1636
  await this.#query().where("email", email).delete();
1479
- const token2 = createHmac("sha256", this.hashKey).update(Str.random(40)).digest("hex");
1637
+ const token2 = createHmac2("sha256", this.hashKey).update(Str.random(40)).digest("hex");
1480
1638
  await this.#query().insert({ email, token: await this.hasher.make(token2), created_at: this.clock() });
1481
1639
  return token2;
1482
1640
  }
@@ -1591,6 +1749,11 @@ var PasswordBrokerManager = class {
1591
1749
  return new PasswordBroker2(tokens, auth2.createUserProvider(settings.provider));
1592
1750
  }
1593
1751
  };
1752
+ function guestRedirect(request2, config2) {
1753
+ const target = config2.get("http.redirect_guests_to");
1754
+ if (typeof target === "function") return String(target(request2));
1755
+ return typeof target === "string" && target !== "" ? target : void 0;
1756
+ }
1594
1757
  var Authenticate = class {
1595
1758
  auth = inject(AuthFactory);
1596
1759
  config = inject(ConfigRepository);
@@ -1612,9 +1775,25 @@ var Authenticate = class {
1612
1775
  }
1613
1776
  /** config('http.redirect_guests_to') (set by withMiddleware(m => m.redirectGuestsTo(...))); Http falls back to route('login'). */
1614
1777
  redirectTo(request2) {
1615
- const target = this.config.get("http.redirect_guests_to");
1616
- if (typeof target === "function") return String(target(request2));
1617
- return typeof target === "string" && target !== "" ? target : void 0;
1778
+ return guestRedirect(request2, this.config);
1779
+ }
1780
+ };
1781
+ var AuthenticateSession = class {
1782
+ auth = inject(AuthFactory);
1783
+ config = inject(ConfigRepository);
1784
+ async handle(request2, next) {
1785
+ const guard2 = this.auth.guard();
1786
+ if (guard2.hasStartedSession?.() !== true) return next(request2);
1787
+ const session2 = guard2;
1788
+ const before = (await session2.user())?.getAuthPassword();
1789
+ if (before !== void 0 && before !== "" && !session2.passwordHashMatches()) {
1790
+ await session2.logoutCurrentDevice();
1791
+ inject(Session).flush();
1792
+ throw new AuthenticationError("Unauthenticated.", [session2.name], request2.expectsJson() ? void 0 : guestRedirect(request2, this.config));
1793
+ }
1794
+ const response2 = await next(request2);
1795
+ session2.keepPasswordHash(before);
1796
+ return response2;
1618
1797
  }
1619
1798
  };
1620
1799
  async function redirectTo(container, request2, url2, guest = false) {
@@ -1907,7 +2086,7 @@ function generateSecret() {
1907
2086
  function totpCode(secret, at, step = Math.floor(at / 1e3 / STEP_SECONDS)) {
1908
2087
  const counter = Buffer.alloc(8);
1909
2088
  counter.writeBigUInt64BE(BigInt(step));
1910
- const hmac = createHmac2("sha1", base32Decode(secret)).update(counter).digest();
2089
+ const hmac = createHmac3("sha1", base32Decode(secret)).update(counter).digest();
1911
2090
  const offset = hmac[hmac.length - 1] & 15;
1912
2091
  const binary = (hmac[offset] & 127) << 24 | hmac[offset + 1] << 16 | hmac[offset + 2] << 8 | hmac[offset + 3];
1913
2092
  return String(binary % 1e6).padStart(6, "0");
@@ -1927,6 +2106,7 @@ function otpauthUrl(options) {
1927
2106
  }
1928
2107
  var PENDING_LOGIN = "oriel.two_factor.login";
1929
2108
  var pendingKey = (nonce) => `oriel:two-factor:pending:${nonce}`;
2109
+ var attemptsKey = (nonce) => `oriel:two-factor:attempts:${nonce}`;
1930
2110
  var emailKey = (id) => `oriel:two-factor:email:${String(id)}`;
1931
2111
  var stepKey = (id) => `oriel:two-factor:totp:${String(id)}`;
1932
2112
  function maskEmail(email) {
@@ -1956,13 +2136,14 @@ var TwoFactorManager = class {
1956
2136
  await this.#dispatch(new Failed(guardName, user, credentials));
1957
2137
  return false;
1958
2138
  }
2139
+ await guard2.rehashIfRequired?.(user, credentials);
1959
2140
  const method = this.#store().method(user);
1960
2141
  if (method === void 0 || !await (this.#requireWhen?.(user) ?? true)) {
1961
2142
  await guard2.login(user, remember);
1962
2143
  return "authenticated";
1963
2144
  }
1964
2145
  const nonce = randomBytes2(16).toString("hex");
1965
- 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 };
1966
2147
  inject(Session).put(PENDING_LOGIN, record);
1967
2148
  await inject(CacheManager).put(pendingKey(nonce), true, config2.pending_ttl);
1968
2149
  if (method === "email") await this.#sendCode(user);
@@ -1980,6 +2161,12 @@ var TwoFactorManager = class {
1980
2161
  const pending = await this.#pending();
1981
2162
  if (pending === void 0) return false;
1982
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
+ }
1983
2170
  const typed = normalizeCode(code);
1984
2171
  let used;
1985
2172
  if (/^\d{6}$/.test(typed)) {
@@ -1988,10 +2175,8 @@ var TwoFactorManager = class {
1988
2175
  used = "recovery";
1989
2176
  }
1990
2177
  if (used === void 0) {
1991
- record.attempts++;
1992
2178
  await this.#dispatch(new TwoFactorFailed(user, record.method));
1993
- if (record.attempts >= this.#config().max_attempts) await this.#end(record);
1994
- else inject(Session).put(PENDING_LOGIN, record);
2179
+ if (attempts >= max) await this.#end(record);
1995
2180
  return false;
1996
2181
  }
1997
2182
  await this.#end(record);
@@ -2018,15 +2203,21 @@ var TwoFactorManager = class {
2018
2203
  }
2019
2204
  /**
2020
2205
  * Starts setting up an authenticator app: a new secret (unconfirmed, so it doesn't count yet), the `otpauth://` URL
2021
- * and a QR code of it for the app to scan.
2206
+ * and a QR code of it for the app to scan. A user whose app already works must disableApp() first: a new secret would
2207
+ * stop the old app's codes without a word.
2022
2208
  */
2023
2209
  async enableApp(user) {
2210
+ if (this.#store().hasApp(user)) throw new TwoFactorAppAlreadyEnabledError();
2024
2211
  const secret = generateSecret();
2025
2212
  await this.#store().setSecret(user, secret);
2026
2213
  const issuer = this.#config().issuer ?? inject(ConfigRepository).get("app.name", "Oriel");
2027
2214
  const url2 = otpauthUrl({ secret, issuer, account: String(user.getAttribute("email") ?? user.getAuthIdentifier()) });
2028
2215
  return { secret, url: url2, svg: qrSvg(url2) };
2029
2216
  }
2217
+ /** Whether the user's authenticator app works: set up and confirmed. */
2218
+ hasApp(user) {
2219
+ return this.#store().hasApp(user);
2220
+ }
2030
2221
  /** Confirms the app with a code from it: then it counts, becomes the user's method, and recovery codes are made. */
2031
2222
  async confirmApp(user, code) {
2032
2223
  const store = this.#store();
@@ -2088,12 +2279,21 @@ var TwoFactorManager = class {
2088
2279
  }
2089
2280
  return { record, user };
2090
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
+ }
2091
2289
  async #end(record) {
2092
2290
  inject(Session).forget(PENDING_LOGIN);
2093
- 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));
2094
2294
  }
2095
2295
  #hash(code) {
2096
- return createHmac3("sha256", inject(Encrypter).getKey()).update(code).digest("hex");
2296
+ return createHmac4("sha256", inject(Encrypter).getKey()).update(code).digest("hex");
2097
2297
  }
2098
2298
  async #sendCode(user) {
2099
2299
  const config2 = this.#config();
@@ -2165,9 +2365,15 @@ var AuthServiceProvider = class extends ServiceProvider {
2165
2365
  }
2166
2366
  async boot() {
2167
2367
  if (this.app.bound(Router)) {
2168
- this.app.make(Router).aliasMiddleware("auth", Authenticate).aliasMiddleware("guest", RedirectIfAuthenticated).aliasMiddleware("can", Authorize).aliasMiddleware("verified", EnsureEmailIsVerified).aliasMiddleware("two-factor.challenge", TwoFactorChallenge);
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);
2369
+ }
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);
2169
2376
  }
2170
- if (this.app.bound(EventDispatcher)) this.app.make(EventDispatcher).listen(Registered, SendEmailVerificationNotification);
2171
2377
  await discoverPolicies(this.app.appPath("Policies"), this.app.make(Gate));
2172
2378
  if (this.app.bound(ConsoleKernel)) {
2173
2379
  const app2 = this.app;
@@ -2445,9 +2651,9 @@ var Dispatcher = class {
2445
2651
  }
2446
2652
  #afterResponseList() {
2447
2653
  const owner = currentContainer() ?? this.container;
2448
- let list6 = this.#afterResponse.get(owner);
2449
- if (list6 === void 0) this.#afterResponse.set(owner, list6 = []);
2450
- return list6;
2654
+ let list5 = this.#afterResponse.get(owner);
2655
+ if (list5 === void 0) this.#afterResponse.set(owner, list5 = []);
2656
+ return list5;
2451
2657
  }
2452
2658
  /** Runs the job (like dispatchSync) after the response is sent, or after the current queued job. */
2453
2659
  dispatchAfterResponse(job) {
@@ -3158,9 +3364,19 @@ var DatabaseStore = class {
3158
3364
  const deleted = await this.connection.table(this.table).where("key", this.k(key)).delete();
3159
3365
  return deleted > 0;
3160
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
+ */
3161
3371
  async flush() {
3162
- if (this.keyPrefix) await this.connection.table(this.table).where("key", "like", `${this.keyPrefix}%`).delete();
3163
- 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();
3164
3380
  return true;
3165
3381
  }
3166
3382
  };
@@ -3488,8 +3704,8 @@ var RedisRepository = class extends Repository2 {
3488
3704
  return quit;
3489
3705
  }
3490
3706
  tags(names) {
3491
- const list6 = Array.isArray(names) ? names : [names];
3492
- const taggedStore = this.redisStore.tags(list6);
3707
+ const list5 = Array.isArray(names) ? names : [names];
3708
+ const taggedStore = this.redisStore.tags(list5);
3493
3709
  const prefix = this.redisStore.getPrefix();
3494
3710
  return new Repository2(taggedStore, (_store, name, seconds, owner) => new RedisLock(this.redis, prefix + name, seconds, owner));
3495
3711
  }
@@ -3706,6 +3922,7 @@ var CacheServiceProvider = class extends ServiceProvider {
3706
3922
  };
3707
3923
 
3708
3924
  // ../Console/dist/index.js
3925
+ import { Writable } from "stream";
3709
3926
  import { existsSync as existsSync2 } from "fs";
3710
3927
  import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
3711
3928
  import { dirname as dirname2, join as join4, relative as relative2, sep } from "path";
@@ -3741,6 +3958,12 @@ var ScheduleNameRequiredError = class extends Error {
3741
3958
  super(`A scheduled event name is required to prevent overlapping. Use the 'name' method before '${method}'.`);
3742
3959
  }
3743
3960
  };
3961
+ var ConsoleAbortedError = class extends Error {
3962
+ name = "ConsoleAbortedError";
3963
+ constructor() {
3964
+ super("Aborted.");
3965
+ }
3966
+ };
3744
3967
  var NodeConsoleOutput = class {
3745
3968
  write(text4) {
3746
3969
  process.stdout.write(text4);
@@ -3779,18 +4002,32 @@ var NodeConsoleInput = class {
3779
4002
  lines = [];
3780
4003
  waiting = [];
3781
4004
  ended = false;
3782
- async question(prompt) {
4005
+ muted = false;
4006
+ async question(prompt, options = {}) {
3783
4007
  const rl = await this.open();
4008
+ const hide = options.hidden === true && this.isTerminal() && !this.ended;
3784
4009
  if (this.ended) {
3785
4010
  this.output.write(prompt);
4011
+ } else if (hide) {
4012
+ this.output.write(prompt);
4013
+ this.muted = true;
4014
+ rl.setPrompt("");
4015
+ rl.prompt();
3786
4016
  } else {
3787
4017
  rl.setPrompt(prompt);
3788
4018
  rl.prompt();
3789
4019
  }
3790
- const line = this.lines.shift();
3791
- if (line !== void 0) return line;
3792
- if (this.ended) throw new Error("Aborted.");
3793
- return new Promise((resolve5, reject) => this.waiting.push({ resolve: resolve5, reject }));
4020
+ try {
4021
+ const line = this.lines.shift();
4022
+ if (line !== void 0) return line;
4023
+ if (this.ended) throw new ConsoleAbortedError();
4024
+ return await new Promise((resolve5, reject) => this.waiting.push({ resolve: resolve5, reject }));
4025
+ } finally {
4026
+ if (hide) {
4027
+ this.muted = false;
4028
+ this.output.write("\n");
4029
+ }
4030
+ }
3794
4031
  }
3795
4032
  close() {
3796
4033
  const rl = this.rl;
@@ -3803,7 +4040,8 @@ var NodeConsoleInput = class {
3803
4040
  if (this.rl) return this.rl;
3804
4041
  const { createInterface } = await import("readline");
3805
4042
  if (this.rl) return this.rl;
3806
- const rl = createInterface({ input: this.input, output: this.output });
4043
+ const rl = createInterface({ input: this.input, output: this.screen(), terminal: this.isTerminal(), historySize: 0 });
4044
+ rl.on("SIGINT", () => rl.close());
3807
4045
  rl.on("line", (line) => {
3808
4046
  const next = this.waiting.shift();
3809
4047
  if (next) next.resolve(line);
@@ -3812,18 +4050,32 @@ var NodeConsoleInput = class {
3812
4050
  rl.on("close", () => {
3813
4051
  if (this.rl !== rl) return;
3814
4052
  this.ended = true;
3815
- for (const { reject } of this.waiting.splice(0)) reject(new Error("Aborted."));
4053
+ for (const { reject } of this.waiting.splice(0)) reject(new ConsoleAbortedError());
3816
4054
  });
3817
4055
  this.rl = rl;
3818
4056
  return rl;
3819
4057
  }
4058
+ isTerminal() {
4059
+ return this.input.isTTY === true;
4060
+ }
4061
+ /** What readline writes to: the real output, unless muted, with the width it wraps long lines at. */
4062
+ screen() {
4063
+ const screen = new Writable({
4064
+ write: (chunk, _encoding, done) => {
4065
+ if (!this.muted) this.output.write(chunk);
4066
+ done();
4067
+ }
4068
+ });
4069
+ Object.defineProperty(screen, "columns", { get: () => this.output.columns });
4070
+ return screen;
4071
+ }
3820
4072
  };
3821
4073
  var QueuedConsoleInput = class {
3822
4074
  queue;
3823
4075
  constructor(answers = []) {
3824
4076
  this.queue = [...answers];
3825
4077
  }
3826
- async question(_prompt) {
4078
+ async question(_prompt, _options) {
3827
4079
  if (this.queue.length === 0) throw new Error("QueuedConsoleInput ran out of answers.");
3828
4080
  return this.queue.shift();
3829
4081
  }
@@ -3892,9 +4144,9 @@ var Command = class {
3892
4144
  const answer = (await this.consoleInput.question(`${question}${suffix2}: `)).trim();
3893
4145
  return answer === "" && defaultValue !== void 0 ? defaultValue : answer;
3894
4146
  }
3895
- /** v1 simplification: reads through the same stream as ask(), without suppressing terminal echo. */
4147
+ /** Asks without showing what's typed, in a terminal. Unlike ask(), the answer isn't trimmed: a secret may start or end with a space. */
3896
4148
  async secret(question) {
3897
- return this.ask(question);
4149
+ return this.consoleInput.question(`${question}: `, { hidden: true });
3898
4150
  }
3899
4151
  async confirm(question, defaultValue = false) {
3900
4152
  const hint = defaultValue ? "Y/n" : "y/N";
@@ -5149,7 +5401,7 @@ async function repeatEvents(repeating, io, startedAt, clock, background) {
5149
5401
  const endOfMinute = (Math.floor(startedAt.getTime() / 6e4) + 1) * 6e4;
5150
5402
  while (clock.now() < endOfMinute) {
5151
5403
  for (const event2 of repeating) {
5152
- if (await interrupted()) return;
5404
+ if (clock.stopped?.() || await interrupted()) return;
5153
5405
  const now5 = clock.now();
5154
5406
  if (event2.shouldRepeatNow(now5)) await start(event2, io, startedAt, new Date(now5), background);
5155
5407
  }
@@ -5162,7 +5414,10 @@ async function runSchedule(events, io, startedAt, clock) {
5162
5414
  if (repeating.length > 0) await clearInterrupt();
5163
5415
  const background = [];
5164
5416
  try {
5165
- 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
+ }
5166
5421
  if (repeating.length > 0) await repeatEvents(repeating, io, startedAt, clock, background);
5167
5422
  } finally {
5168
5423
  await Promise.allSettled(background);
@@ -5238,36 +5493,65 @@ var ScheduleWorkCommand = class extends Command {
5238
5493
  workOptions;
5239
5494
  signature = "schedule:work";
5240
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
+ */
5241
5500
  async handle() {
5242
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) {
5243
5525
  const sleep5 = this.workOptions.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
5244
5526
  const clock = this.workOptions.now ?? Date.now;
5245
5527
  this.info("Running scheduled tasks every minute.");
5246
5528
  let lastMinute;
5247
- while (!this.workOptions.signal?.aborted) {
5529
+ while (!this.workOptions.signal?.aborted && !stopped()) {
5248
5530
  const time = clock();
5249
5531
  const minute = Math.floor(time / 6e4);
5250
5532
  if (minute !== lastMinute) {
5251
5533
  lastMinute = minute;
5252
5534
  const now5 = new Date(time);
5253
5535
  try {
5254
- await runSchedule(schedule.dueEvents(now5), this, now5, { now: clock, sleep: sleep5 });
5536
+ await runSchedule(schedule.dueEvents(now5), this, now5, { now: clock, sleep: sleep5, stopped });
5255
5537
  } catch (error) {
5256
5538
  this.error(`The scheduled run failed: ${error instanceof Error ? error.message : String(error)}`);
5257
5539
  }
5258
5540
  }
5541
+ if (stopped()) return;
5259
5542
  await sleep5(Math.max(0, (minute + 1) * 6e4 - clock()) + 10);
5260
5543
  }
5261
- return 0;
5262
5544
  }
5263
5545
  };
5264
5546
  var defaultSpawner = (command, args) => spawn(command, args, { stdio: "inherit", shell: process.platform === "win32" });
5265
5547
  var TestCommand = class extends Command {
5266
- constructor(spawner = defaultSpawner) {
5548
+ constructor(spawner = defaultSpawner, onBun = () => typeof process.versions.bun === "string") {
5267
5549
  super();
5268
5550
  this.spawner = spawner;
5551
+ this.onBun = onBun;
5269
5552
  }
5270
5553
  spawner;
5554
+ onBun;
5271
5555
  /** Paths are passed on to vitest; so is everything after `--` (`oriel test -- --coverage`). */
5272
5556
  signature = "test {args?*} {--filter=}";
5273
5557
  description = "Run the test suite";
@@ -5278,7 +5562,7 @@ var TestCommand = class extends Command {
5278
5562
  const extra = this.argument("args");
5279
5563
  if (Array.isArray(extra)) args.push(...extra);
5280
5564
  return new Promise((resolve5) => {
5281
- const child = this.spawner("npx", args);
5565
+ const child = this.onBun() ? this.spawner("bun", ["--bun", ...args]) : this.spawner("npx", args);
5282
5566
  child.on("error", (error) => {
5283
5567
  this.error(error.message);
5284
5568
  resolve5(1);
@@ -5322,8 +5606,8 @@ async function discoverCommands(kernel, directory) {
5322
5606
  if (typeof exported !== "function") continue;
5323
5607
  const prototype = exported.prototype;
5324
5608
  if (typeof prototype?.handle !== "function") continue;
5325
- const instance = new exported();
5326
- if (typeof instance.signature === "string") kernel.register(instance);
5609
+ const commandClass = exported;
5610
+ if (typeof new commandClass().signature === "string") kernel.register(commandClass);
5327
5611
  }
5328
5612
  }
5329
5613
  }
@@ -5404,6 +5688,8 @@ var Kernel2 = class {
5404
5688
  defaultInput;
5405
5689
  defaultOutput;
5406
5690
  lastOutput = "";
5691
+ /** The classes of the commands registered as classes: each run makes a new one. */
5692
+ classes = /* @__PURE__ */ new Map();
5407
5693
  running = 0;
5408
5694
  loader;
5409
5695
  bootstrapping;
@@ -5419,6 +5705,8 @@ var Kernel2 = class {
5419
5705
  const instance = typeof entry === "function" ? new entry() : entry;
5420
5706
  const name = parseSignature(instance.signature).name;
5421
5707
  this.commands.set(name, instance);
5708
+ if (typeof entry === "function") this.classes.set(name, entry);
5709
+ else this.classes.delete(name);
5422
5710
  }
5423
5711
  }
5424
5712
  command(signature, handler3) {
@@ -5432,9 +5720,9 @@ var Kernel2 = class {
5432
5720
  output() {
5433
5721
  return this.lastOutput;
5434
5722
  }
5435
- async call(command, parameters = {}) {
5723
+ async call(command, parameters = {}, options = {}) {
5436
5724
  const output = new BufferedConsoleOutput();
5437
- const code = await this.callWithIo(command, parameters, { input: new QueuedConsoleInput(), output });
5725
+ const code = await this.callWithIo(command, parameters, { input: new QueuedConsoleInput(options.answers), output });
5438
5726
  this.lastOutput = output.combined;
5439
5727
  return code;
5440
5728
  }
@@ -5460,6 +5748,11 @@ var Kernel2 = class {
5460
5748
  }
5461
5749
  }
5462
5750
  reportTopLevelError(error, output) {
5751
+ if (error instanceof ConsoleAbortedError) {
5752
+ output.writeError(`${error.message}
5753
+ `);
5754
+ return 130;
5755
+ }
5463
5756
  if (error instanceof CommandNotFoundError) {
5464
5757
  output.writeError(`${error.message}
5465
5758
  `);
@@ -5498,11 +5791,12 @@ var Kernel2 = class {
5498
5791
  }
5499
5792
  async execute(instance, signature, input, io) {
5500
5793
  validateRequiredArguments(signature, input);
5501
- const run = Object.create(instance);
5502
- run.bind?.(resolveArguments(signature, input), resolveOptions(signature, input), io);
5503
5794
  const scope = this.app.createScope();
5504
5795
  scope.instance(ConsoleKernel, this);
5505
5796
  return scope.run(async () => {
5797
+ const CommandClass = this.classes.get(signature.name);
5798
+ const run = CommandClass === void 0 ? Object.create(instance) : new CommandClass();
5799
+ run.bind?.(resolveArguments(signature, input), resolveOptions(signature, input), io);
5506
5800
  try {
5507
5801
  const result = await run.handle();
5508
5802
  return typeof result === "number" ? result : 0;
@@ -5568,6 +5862,8 @@ var ScheduledEventImpl = class {
5568
5862
  /** The minute slot this server won with onOneServer(): its repetitions in that minute keep it. */
5569
5863
  wonServerSlot;
5570
5864
  overlapExpiryMinutes;
5865
+ /** The overlap lock a run in progress holds, so schedule:work can release it when it is stopped. */
5866
+ heldOverlapLock;
5571
5867
  oneServer = false;
5572
5868
  background = false;
5573
5869
  eventName;
@@ -5897,6 +6193,7 @@ var ScheduledEventImpl = class {
5897
6193
  if (this.overlapExpiryMinutes !== void 0) {
5898
6194
  overlapLock = this.acquireLock(this.mutexName(), this.overlapExpiryMinutes * 60);
5899
6195
  if (overlapLock && !await overlapLock.get()) return;
6196
+ this.heldOverlapLock = overlapLock;
5900
6197
  }
5901
6198
  try {
5902
6199
  for (const callback of this.beforeCallbacks) await callback();
@@ -5904,9 +6201,21 @@ var ScheduledEventImpl = class {
5904
6201
  for (const callback of this.afterCallbacks) await callback(failure === void 0);
5905
6202
  if (failure !== void 0) throw failure.error;
5906
6203
  } finally {
5907
- if (overlapLock) await overlapLock.release();
6204
+ if (overlapLock && this.heldOverlapLock === overlapLock) {
6205
+ this.heldOverlapLock = void 0;
6206
+ await overlapLock.release();
6207
+ }
5908
6208
  }
5909
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
+ }
5910
6219
  /**
5911
6220
  * Runs the event and says whether it failed. A command fails when it exits non-zero, and a closure when it throws or
5912
6221
  * returns false, as Laravel's CallbackEvent does. A job whose handler returns false failing is Oriel's own choice:
@@ -6065,7 +6374,7 @@ async function runConsoleAndExit(app2, argv = process.argv.slice(2), exit = (cod
6065
6374
  }
6066
6375
 
6067
6376
  // ../Cookie/dist/index.js
6068
- import { createHmac as createHmac4, timingSafeEqual as timingSafeEqual4 } from "crypto";
6377
+ import { createHmac as createHmac5, timingSafeEqual as timingSafeEqual4 } from "crypto";
6069
6378
  var SAME_SITE = { lax: "Lax", strict: "Strict", none: "None" };
6070
6379
  function serializeCookie(cookie2, now5 = Date.now()) {
6071
6380
  const parts = [];
@@ -6119,7 +6428,7 @@ function withHeaders(response2, change) {
6119
6428
  }
6120
6429
  var CookieValuePrefix = {
6121
6430
  create(name, key) {
6122
- return `${createHmac4("sha1", key).update(`${name}v2`).digest("hex")}|`;
6431
+ return `${createHmac5("sha1", key).update(`${name}v2`).digest("hex")}|`;
6123
6432
  },
6124
6433
  remove(value2) {
6125
6434
  return value2.slice(41);
@@ -6219,7 +6528,11 @@ var EncryptCookies = class {
6219
6528
  }
6220
6529
  /** Subclasses list cookie names that are not encrypted. */
6221
6530
  except = [];
6222
- encrypter = inject(Encrypter);
6531
+ #encrypter;
6532
+ /** Resolved when there's a cookie to read or write, so a page that uses none works without APP_KEY. */
6533
+ get encrypter() {
6534
+ return this.#encrypter ??= inject(Encrypter);
6535
+ }
6223
6536
  isDisabled(name) {
6224
6537
  return this.except.includes(name) || neverEncrypt.has(name);
6225
6538
  }
@@ -6228,7 +6541,6 @@ var EncryptCookies = class {
6228
6541
  return this.encrypt(await next(request2));
6229
6542
  }
6230
6543
  decrypt(request2) {
6231
- const keys = this.encrypter.getAllKeys?.() ?? [this.encrypter.getKey()];
6232
6544
  const decrypted = {};
6233
6545
  for (const [name, value2] of Object.entries(parseCookieHeader(request2.header("cookie")))) {
6234
6546
  if (this.isDisabled(name)) {
@@ -6236,6 +6548,7 @@ var EncryptCookies = class {
6236
6548
  continue;
6237
6549
  }
6238
6550
  try {
6551
+ const keys = this.encrypter.getAllKeys?.() ?? [this.encrypter.getKey()];
6239
6552
  const plain2 = CookieValuePrefix.validate(name, this.encrypter.decrypt(value2, false), keys);
6240
6553
  if (plain2 !== void 0) decrypted[name] = plain2;
6241
6554
  } catch {
@@ -6299,12 +6612,13 @@ import { Kysely, sql as sql7 } from "kysely";
6299
6612
  import { sql as sql6 } from "kysely";
6300
6613
  import { sql as sql4 } from "kysely";
6301
6614
  import { sql as sql5 } from "kysely";
6302
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
6615
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
6616
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
6303
6617
  import { isDeepStrictEqual } from "util";
6304
6618
  import { existsSync as existsSync5, readdirSync as readdirSync3 } from "fs";
6305
6619
  import { join as join43 } from "path";
6306
6620
  import { pathToFileURL as pathToFileURL3 } from "url";
6307
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
6621
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
6308
6622
  import { existsSync as existsSync23, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
6309
6623
  import { join as join52 } from "path";
6310
6624
  import { existsSync as existsSync32, readdirSync as readdirSync22 } from "fs";
@@ -6424,9 +6738,11 @@ async function openSqlite(filename) {
6424
6738
  /* @vite-ignore */
6425
6739
  specifier
6426
6740
  );
6427
- return new BunSqliteDatabase(new Database2(filename));
6741
+ const database = new Database2(filename);
6742
+ database.prepare("PRAGMA busy_timeout = 5000").run();
6743
+ return new BunSqliteDatabase(database);
6428
6744
  }
6429
- const { default: Database } = await import("better-sqlite3");
6745
+ const { default: Database } = await importOptional("better-sqlite3", "The sqlite connection", () => import("better-sqlite3"));
6430
6746
  return new Database(filename);
6431
6747
  }
6432
6748
  var PG_INT8 = 20;
@@ -6486,7 +6802,7 @@ function createDialect(config2) {
6486
6802
  case "pgsql":
6487
6803
  return new PostgresDialect({
6488
6804
  pool: async () => {
6489
- const { default: pg } = await import("pg");
6805
+ const { default: pg } = await importOptional("pg", "The pgsql connection", () => import("pg"));
6490
6806
  return new pg.Pool({
6491
6807
  connectionString: config2.url,
6492
6808
  host: config2.host,
@@ -6514,7 +6830,7 @@ function createDialect(config2) {
6514
6830
  case "mysql":
6515
6831
  return new MysqlDialect({
6516
6832
  pool: async () => {
6517
- const { createPool } = await import("mysql2");
6833
+ const { createPool } = await importOptional("mysql2", "The mysql connection", () => import("mysql2"));
6518
6834
  return createPool(mysqlPoolOptions(config2));
6519
6835
  }
6520
6836
  });
@@ -7025,10 +7341,33 @@ var Grammar = class {
7025
7341
  columnize(columns) {
7026
7342
  return join9(columns.map((column) => this.wrap(column)));
7027
7343
  }
7028
- compileSelect(query) {
7029
- 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);
7030
7348
  return clauses([query.distinctRows ? sql2`select distinct ${columns}` : sql2`select ${columns}`, this.compileComponents(query)]);
7031
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
+ }
7032
7371
  /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
7033
7372
  compileComponents(query) {
7034
7373
  return clauses([
@@ -7055,7 +7394,9 @@ var Grammar = class {
7055
7394
  switch (where.type) {
7056
7395
  case "basic": {
7057
7396
  const column = typeof where.column === "object" && !(where.column instanceof Expression) ? sql2`(${this.compileSelect(where.column)})` : this.wrap(where.column);
7058
- 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)}`;
7059
7400
  }
7060
7401
  case "in": {
7061
7402
  const keyword = sql2.raw(where.not ? "not in" : "in");
@@ -7134,7 +7475,10 @@ var Grammar = class {
7134
7475
  if (mode === "update") return sql2.raw("for update");
7135
7476
  return sql2.raw(this.driver === "pgsql" ? "for share" : "lock in share mode");
7136
7477
  }
7137
- /** `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
+ */
7138
7482
  compileAggregate(query, fn, column) {
7139
7483
  const inner = query.clone();
7140
7484
  inner.orders = [];
@@ -7142,7 +7486,7 @@ var Grammar = class {
7142
7486
  inner.offsetValue = void 0;
7143
7487
  inner.lockMode = void 0;
7144
7488
  const target = column === "*" ? sql2.raw("*") : this.wrap(column);
7145
- if (inner.groups.length || inner.distinctRows) {
7489
+ if (inner.groups.length || inner.distinctRows || inner.havings.length) {
7146
7490
  if (fn === "count") return sql2`select count(*) as ${sql2.id("aggregate")} from (${this.compileSelect(inner)}) as ${sql2.id("temp_table")}`;
7147
7491
  if (column instanceof Expression) {
7148
7492
  throw new LogicError(`${fn}() can't target a raw expression over a distinct or grouped query: select it as an aliased column instead.`);
@@ -7228,6 +7572,7 @@ var Grammar = class {
7228
7572
  ];
7229
7573
  }
7230
7574
  };
7575
+ var GROUP_ROW = "oriel_row";
7231
7576
  async function* chunksOf(query, chunkSize) {
7232
7577
  for (let page = 1; ; page++) {
7233
7578
  const results = await query.clone().forPage(page, chunkSize).runSelect();
@@ -7288,6 +7633,8 @@ var Builder = class _Builder {
7288
7633
  orders = [];
7289
7634
  limitValue;
7290
7635
  offsetValue;
7636
+ /** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */
7637
+ groupLimit;
7291
7638
  lockMode;
7292
7639
  // ---------------------------------------------------------------- building
7293
7640
  from(table) {
@@ -7576,7 +7923,20 @@ var Builder = class _Builder {
7576
7923
  }
7577
7924
  /** The raw rows, without a Collection around them. */
7578
7925
  async runSelect() {
7579
- 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;
7580
7940
  }
7581
7941
  async first() {
7582
7942
  const rows = await this.clone().limit(1).runSelect();
@@ -7820,15 +8180,15 @@ var Builder = class _Builder {
7820
8180
  return [...this.connection.compile(this.grammar.compileSelect(this)).parameters];
7821
8181
  }
7822
8182
  clone() {
7823
- const copy2 = Object.create(Object.getPrototypeOf(this));
7824
- Object.assign(copy2, this);
7825
- copy2.columns = [...this.columns];
7826
- copy2.joins = [...this.joins];
7827
- copy2.wheres = [...this.wheres];
7828
- copy2.groups = [...this.groups];
7829
- copy2.havings = [...this.havings];
7830
- copy2.orders = [...this.orders];
7831
- return copy2;
8183
+ const copy = Object.create(Object.getPrototypeOf(this));
8184
+ Object.assign(copy, this);
8185
+ copy.columns = [...this.columns];
8186
+ copy.joins = [...this.joins];
8187
+ copy.wheres = [...this.wheres];
8188
+ copy.groups = [...this.groups];
8189
+ copy.havings = [...this.havings];
8190
+ copy.orders = [...this.orders];
8191
+ return copy;
7832
8192
  }
7833
8193
  /** A fresh builder on the same connection and table (for nested where groups). */
7834
8194
  newQuery() {
@@ -9293,6 +9653,7 @@ var Connection = class {
9293
9653
  db;
9294
9654
  context = new AsyncLocalStorage();
9295
9655
  pinned = [];
9656
+ savepoints = 0;
9296
9657
  loggingQueries = false;
9297
9658
  queryLog = [];
9298
9659
  getName() {
@@ -9412,18 +9773,32 @@ var Connection = class {
9412
9773
  }
9413
9774
  async open() {
9414
9775
  const parent = this.current();
9415
- 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;
9416
9781
  const level2 = parent.level + 1;
9417
- await sql7.raw(`SAVEPOINT trans${level2}`).execute(parent.trx);
9418
- 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 };
9419
9790
  }
9420
9791
  async close(frame, action) {
9421
- if (frame.level === 1) {
9422
- await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
9423
- } else if (action === "commit") {
9424
- await sql7.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx);
9425
- } else {
9426
- 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?.();
9427
9802
  }
9428
9803
  }
9429
9804
  };
@@ -9435,6 +9810,8 @@ var DatabaseManagerImpl = class {
9435
9810
  config;
9436
9811
  connections = /* @__PURE__ */ new Map();
9437
9812
  defaultName;
9813
+ /** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */
9814
+ using = new AsyncLocalStorage2();
9438
9815
  settings() {
9439
9816
  return typeof this.config === "function" ? this.config() : this.config;
9440
9817
  }
@@ -9451,25 +9828,19 @@ var DatabaseManagerImpl = class {
9451
9828
  return connection;
9452
9829
  }
9453
9830
  getDefaultConnection() {
9454
- return this.defaultName ?? this.settings().default;
9831
+ return this.using.getStore() ?? this.defaultName ?? this.settings().default;
9455
9832
  }
9456
9833
  /** Overrides config('database.default'); undefined clears the override. */
9457
9834
  setDefaultConnection(name) {
9458
9835
  this.defaultName = name;
9459
9836
  }
9460
9837
  /**
9461
- * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), then restores the previous
9462
- * 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.
9463
9840
  */
9464
9841
  async usingConnection(name, callback) {
9465
9842
  if (!name) return callback();
9466
- const previous = this.defaultName;
9467
- this.defaultName = name;
9468
- try {
9469
- return await callback();
9470
- } finally {
9471
- this.defaultName = previous;
9472
- }
9843
+ return this.using.run(name, callback);
9473
9844
  }
9474
9845
  /** The connections opened so far. */
9475
9846
  getConnections() {
@@ -9793,7 +10164,7 @@ var Builder2 = class extends Builder {
9793
10164
  if (models.length && this.model.hasModelListeners("retrieved")) {
9794
10165
  for (const model of models) await model.fireModelEvent("retrieved", false);
9795
10166
  }
9796
- if (models.length && this.eagerLoad.size) await this.eagerLoadRelations(models);
10167
+ if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models);
9797
10168
  return models;
9798
10169
  }
9799
10170
  // ---------------------------------------------------------------- eager loading
@@ -9834,6 +10205,7 @@ var Builder2 = class extends Builder {
9834
10205
  const relation = this.getRelation(name);
9835
10206
  relation.addEagerConstraints(models);
9836
10207
  constraint?.(relation);
10208
+ relation.limitEagerPerParent();
9837
10209
  const nested = this.relationsNestedUnder(name);
9838
10210
  if (Object.keys(nested).length) relation.with(nested);
9839
10211
  relation.initRelation(models, name);
@@ -9906,9 +10278,10 @@ var Builder2 = class extends Builder {
9906
10278
  const [rawName = "", as] = spec.split(/\s+as\s+/i);
9907
10279
  const name = rawName.trim();
9908
10280
  const relation = this.getRelation(name);
9909
- 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);
9910
10283
  const expression = fn && fn !== "exists" ? new Expression(`${fn}(${target.value})`, target.bindings) : target;
9911
- const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this, [expression]);
10284
+ query.select(expression);
9912
10285
  query.wheres.push(...relation.wheres);
9913
10286
  if (constraint) query.callScope((q) => constraint(q));
9914
10287
  const scoped = query.applyScopes();
@@ -10008,8 +10381,8 @@ var Builder2 = class extends Builder {
10008
10381
  isMalformedKey(id) {
10009
10382
  return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id);
10010
10383
  }
10011
- /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
10012
10384
  async find(id) {
10385
+ if (Array.isArray(id)) return this.findMany(id);
10013
10386
  if (this.isMalformedKey(id)) return void 0;
10014
10387
  return this.clone().whereKey(id).first();
10015
10388
  }
@@ -10134,12 +10507,12 @@ var Builder2 = class extends Builder {
10134
10507
  return Builder.prototype.getBindings.call(this.applyScopes());
10135
10508
  }
10136
10509
  clone() {
10137
- const copy2 = super.clone();
10138
- copy2.scopes = new Map(this.scopes);
10139
- copy2.removedScopes = [...this.removedScopes];
10140
- copy2.eagerLoad = new Map(this.eagerLoad);
10141
- copy2.selectCasts = { ...this.selectCasts };
10142
- return new Proxy(copy2, handler);
10510
+ const copy = super.clone();
10511
+ copy.scopes = new Map(this.scopes);
10512
+ copy.removedScopes = [...this.removedScopes];
10513
+ copy.eagerLoad = new Map(this.eagerLoad);
10514
+ copy.selectCasts = { ...this.selectCasts };
10515
+ return new Proxy(copy, handler);
10143
10516
  }
10144
10517
  /** Nested where groups get a builder of the same model (without global scopes), so local scopes work inside them. */
10145
10518
  newQuery() {
@@ -10449,11 +10822,11 @@ var EloquentCollection = class extends Collection {
10449
10822
  };
10450
10823
  async function loadMissingOn(models, paths) {
10451
10824
  for (const path of paths) {
10452
- const [head2 = "", ...rest] = path.split(".");
10453
- const missing = models.filter((model) => !model.relationLoaded(head2));
10825
+ const [head = "", ...rest] = path.split(".");
10826
+ const missing = models.filter((model) => !model.relationLoaded(head));
10454
10827
  if (missing.length) await missing[0].newQueryWithoutRelationships().with(path).eagerLoadRelations(missing);
10455
10828
  if (!rest.length) continue;
10456
- const related = models.flatMap((model) => relatedModels(model.getRelations()[head2]));
10829
+ const related = models.flatMap((model) => relatedModels(model.getRelations()[head]));
10457
10830
  if (related.length) await loadMissingOn(related, [rest.join(".")]);
10458
10831
  }
10459
10832
  }
@@ -10496,6 +10869,7 @@ function resolveMorphClass(type) {
10496
10869
  if (known) return known;
10497
10870
  throw new LogicError(`Class [${type}] not found for a morphTo relation. Add it to Relation.morphMap().`);
10498
10871
  }
10872
+ var selfAliases = 0;
10499
10873
  var Relation = class extends Builder2 {
10500
10874
  constructor(related, parent) {
10501
10875
  super(related);
@@ -10519,6 +10893,32 @@ var Relation = class extends Builder2 {
10519
10893
  getRelated() {
10520
10894
  return this.model;
10521
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
+ }
10522
10922
  /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
10523
10923
  init() {
10524
10924
  if (relationConstraintsEnabled()) this.addConstraints();
@@ -10601,6 +11001,7 @@ var BelongsTo = class extends Relation {
10601
11001
  return this.associate(null);
10602
11002
  }
10603
11003
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
11004
+ this.aliasSelfTable(query);
10604
11005
  return query.select(...columns).whereColumn(this.getQualifiedForeignKeyName(), "=", this.getQualifiedOwnerKeyName());
10605
11006
  }
10606
11007
  /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */
@@ -10692,7 +11093,11 @@ var BelongsToMany = class extends Relation {
10692
11093
  for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []));
10693
11094
  return models;
10694
11095
  }
11096
+ eagerPartitionColumn() {
11097
+ return this.qualifyPivotColumn(this.foreignPivotKey);
11098
+ }
10695
11099
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
11100
+ this.aliasSelfTable(query);
10696
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));
10697
11102
  }
10698
11103
  // ---------------------------------------------------------------- the pivot table
@@ -10971,9 +11376,17 @@ var HasOneOrMany = class extends Relation {
10971
11376
  for (const record of records) created.push(await this.create(record));
10972
11377
  return created;
10973
11378
  }
11379
+ eagerPartitionColumn() {
11380
+ return this.foreignKey;
11381
+ }
10974
11382
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
10975
- query.select(...columns).whereColumn(this.getQualifiedParentKeyName(), "=", this.foreignKey);
10976
- 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
+ }
10977
11390
  return query;
10978
11391
  }
10979
11392
  };
@@ -11112,7 +11525,11 @@ var Factory2 = class _Factory {
11112
11525
  const name = relationship ?? Str.camel(Str.plural(new factory.model().constructor.name));
11113
11526
  return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] });
11114
11527
  }
11115
- /** 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
+ */
11116
11533
  for(parent, relationship) {
11117
11534
  const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor;
11118
11535
  return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str.camel(cls.name) }] });
@@ -11126,7 +11543,8 @@ var Factory2 = class _Factory {
11126
11543
  /** The attributes only, without a model (a Row, or a Row[] after count()). */
11127
11544
  async raw(attributes = {}) {
11128
11545
  const rows = [];
11129
- 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));
11130
11548
  return this.countValue === void 0 ? rows[0] : rows;
11131
11549
  }
11132
11550
  /** Unsaved models (afterMaking callbacks run). */
@@ -11158,26 +11576,27 @@ var Factory2 = class _Factory {
11158
11576
  return new Collection(created);
11159
11577
  }
11160
11578
  newInstance(changes) {
11161
- const copy2 = Object.create(Object.getPrototypeOf(this));
11162
- Object.assign(copy2, this, changes);
11163
- return copy2;
11579
+ const copy = Object.create(Object.getPrototypeOf(this));
11580
+ Object.assign(copy, this, changes);
11581
+ return copy;
11164
11582
  }
11165
11583
  async makeModels(attributes) {
11166
11584
  const models = [];
11585
+ const parents = /* @__PURE__ */ new Map();
11167
11586
  for (let index = 0; index < (this.countValue ?? 1); index++) {
11168
- const model = new this.model().forceFill(await this.attributesFor(attributes, index));
11587
+ const model = new this.model().forceFill(await this.attributesFor(attributes, index, parents));
11169
11588
  for (const callback of this.afterMakingCallbacks) await callback(model);
11170
11589
  models.push(model);
11171
11590
  }
11172
11591
  return models;
11173
11592
  }
11174
11593
  /** definition() + states + overrides + for() parents, with factory and function values expanded. */
11175
- async attributesFor(overrides, index) {
11594
+ async attributesFor(overrides, index, parents = /* @__PURE__ */ new Map()) {
11176
11595
  const context = { index, count: this.countValue ?? 1 };
11177
11596
  let attributes = this.definition();
11178
11597
  for (const state of this.states) attributes = { ...attributes, ...typeof state === "function" ? state(attributes, context) : state };
11179
11598
  attributes = { ...attributes, ...overrides };
11180
- 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));
11181
11600
  const expanded = {};
11182
11601
  for (const [key, value2] of Object.entries(attributes)) {
11183
11602
  if (value2 instanceof _Factory) expanded[key] = (await value2.createOne()).getKey();
@@ -11187,8 +11606,12 @@ var Factory2 = class _Factory {
11187
11606
  }
11188
11607
  return expanded;
11189
11608
  }
11190
- async parentAttributes(parent) {
11191
- 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
+ }
11192
11615
  const relation = this.relationOn(new this.model(), parent.relationship);
11193
11616
  if (relation instanceof MorphTo) {
11194
11617
  return { [relation.getForeignKeyName()]: resolved.getKey(), [relation.getMorphType()]: resolved.getMorphClass() };
@@ -11245,7 +11668,7 @@ var MODEL_EVENTS = [
11245
11668
  "forceDeleting",
11246
11669
  "forceDeleted"
11247
11670
  ];
11248
- var muted = new AsyncLocalStorage2();
11671
+ var muted = new AsyncLocalStorage3();
11249
11672
  function modelEventName(event2, className) {
11250
11673
  return `eloquent.${event2}: ${className}`;
11251
11674
  }
@@ -11458,7 +11881,7 @@ var prototypes = /* @__PURE__ */ new Map();
11458
11881
  var unguardedGlobally = { value: false };
11459
11882
  var addingDefaultCounts = /* @__PURE__ */ new Set();
11460
11883
  var PLAIN_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/;
11461
- var unguardedScope = new AsyncLocalStorage3();
11884
+ var unguardedScope = new AsyncLocalStorage4();
11462
11885
  var globalScopes = /* @__PURE__ */ new Map();
11463
11886
  var anonymousScopes = 0;
11464
11887
  function installScopeProxies(cls) {
@@ -12487,8 +12910,11 @@ var Model = class _Model {
12487
12910
  }
12488
12911
  async incrementOrDecrement(column, amount, extra) {
12489
12912
  if (!this.exists) return this.newQueryWithoutRelationships().increment(column, amount, extra);
12490
- const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
12491
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);
12492
12918
  this.syncOriginalAttributes(column, ...Object.keys(extra));
12493
12919
  return affected;
12494
12920
  }
@@ -13326,12 +13752,14 @@ var TypeGenerator = class {
13326
13752
  const members = attributes.filter(([column]) => !(column in instance));
13327
13753
  const extra = accessors(model).filter(([attribute2]) => !columns.some((column) => column.name === attribute2) && !(attribute2 in instance));
13328
13754
  const statics = scopes(model).filter(([method]) => !(method in Model));
13755
+ const hidden = instance.getHidden().filter((column) => columns.some(({ name: columnName }) => columnName === column));
13329
13756
  const lines = [
13330
13757
  `declare module '${this.modulePath(file)}' {`,
13331
13758
  ` interface ${name} {`,
13332
13759
  " $attributes?: {",
13333
13760
  ...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),
13334
13761
  " }",
13762
+ ...hidden.length ? [` $hidden?: ${hidden.map((column) => `'${column}'`).join(" | ")}`] : [],
13335
13763
  ...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),
13336
13764
  ...extra.map(([attribute2, method]) => ` ${this.key(attribute2)}: ReturnType<${name}['${method}']>`),
13337
13765
  " }"
@@ -14015,7 +14443,7 @@ var DatabaseServiceProvider = class extends ServiceProvider {
14015
14443
  };
14016
14444
 
14017
14445
  // ../Encryption/dist/index.js
14018
- import { createCipheriv, createDecipheriv, createHmac as createHmac5, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual5 } from "crypto";
14446
+ import { createCipheriv, createDecipheriv, createHmac as createHmac6, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual5 } from "crypto";
14019
14447
  import { readFile as readFile2, writeFile as writeFile4 } from "fs/promises";
14020
14448
  var EncryptionFailure = class extends Error {
14021
14449
  kind = "Server";
@@ -14147,7 +14575,7 @@ var Encrypter2 = class _Encrypter {
14147
14575
  return this;
14148
14576
  }
14149
14577
  #hash(iv, value2, key) {
14150
- return createHmac5("sha256", key).update(iv + value2).digest("hex");
14578
+ return createHmac6("sha256", key).update(iv + value2).digest("hex");
14151
14579
  }
14152
14580
  #decryptWith(key, iv, value2, tag) {
14153
14581
  try {
@@ -14227,8 +14655,8 @@ function decrypt(payload, unserialize = true) {
14227
14655
  return inject(Encrypter).decrypt(payload, unserialize);
14228
14656
  }
14229
14657
  function previousKeys(value2) {
14230
- const list6 = Array.isArray(value2) ? value2 : typeof value2 === "string" ? value2.split(",") : [];
14231
- return list6.map((key) => String(key).trim()).filter((key) => key !== "");
14658
+ const list5 = Array.isArray(value2) ? value2 : typeof value2 === "string" ? value2.split(",") : [];
14659
+ return list5.map((key) => String(key).trim()).filter((key) => key !== "");
14232
14660
  }
14233
14661
  var EncryptionServiceProvider = class extends ServiceProvider {
14234
14662
  register() {
@@ -14431,9 +14859,9 @@ var Dispatcher2 = class {
14431
14859
  throw new InvalidListenerError(label);
14432
14860
  }
14433
14861
  for (const event2 of Array.isArray(events) ? events : [events]) {
14434
- const list6 = this.listeners.get(event2) ?? [];
14435
- list6.push(listener);
14436
- this.listeners.set(event2, list6);
14862
+ const list5 = this.listeners.get(event2) ?? [];
14863
+ list5.push(listener);
14864
+ this.listeners.set(event2, list5);
14437
14865
  }
14438
14866
  }
14439
14867
  hasListeners(event2) {
@@ -14445,12 +14873,12 @@ var Dispatcher2 = class {
14445
14873
  }
14446
14874
  /** Laravel's getRawListeners(): each event's listeners as registered (closures, classes, [class, method]). A copy. */
14447
14875
  getRawListeners() {
14448
- return new Map([...this.listeners].map(([event2, list6]) => [event2, [...list6]]));
14876
+ return new Map([...this.listeners].map(([event2, list5]) => [event2, [...list5]]));
14449
14877
  }
14450
14878
  /** Introspection for the event:list command. Not part of the EventDispatcher contract. */
14451
14879
  registeredEvents() {
14452
14880
  const rows = [];
14453
- for (const [key, list6] of this.listeners) rows.push({ event: nameOf(key), listeners: list6.length });
14881
+ for (const [key, list5] of this.listeners) rows.push({ event: nameOf(key), listeners: list5.length });
14454
14882
  return rows.sort((a, b) => a.event.localeCompare(b.event));
14455
14883
  }
14456
14884
  subscribe(subscriber) {
@@ -14494,8 +14922,8 @@ var Dispatcher2 = class {
14494
14922
  const exact = [...this.listeners.get(key) ?? []];
14495
14923
  const wildcardLists = typeof key === "string" ? this.wildcardPatternsFor(key).map((pattern) => [...this.listeners.get(pattern) ?? []]) : [];
14496
14924
  for (const listener of exact) yield { listener, wildcard: false };
14497
- for (const list6 of wildcardLists) {
14498
- for (const listener of list6) yield { listener, wildcard: true };
14925
+ for (const list5 of wildcardLists) {
14926
+ for (const listener of list5) yield { listener, wildcard: true };
14499
14927
  }
14500
14928
  }
14501
14929
  wildcardPatternsFor(event2) {
@@ -14577,7 +15005,6 @@ var EventServiceProvider = class extends ServiceProvider {
14577
15005
  };
14578
15006
 
14579
15007
  // ../Filesystem/dist/index.js
14580
- import { S3Client } from "@aws-sdk/client-s3";
14581
15008
  import { createReadStream, createWriteStream } from "fs";
14582
15009
  import { chmod, copyFile, mkdir as mkdir4, readFile as readFile3, readdir as readdir2, rename as rename2, rm as rm2, stat as stat2, writeFile as writeFile5 } from "fs/promises";
14583
15010
  import { dirname as dirname4, extname as extname2, resolve as resolve2 } from "path";
@@ -14585,16 +15012,6 @@ import { Readable } from "stream";
14585
15012
  import { pipeline } from "stream/promises";
14586
15013
  import { resolve, sep as sep3 } from "path";
14587
15014
  import { posix } from "path";
14588
- import {
14589
- CopyObjectCommand,
14590
- DeleteObjectCommand,
14591
- GetObjectCommand,
14592
- HeadObjectCommand,
14593
- ListObjectsV2Command,
14594
- PutObjectCommand
14595
- } from "@aws-sdk/client-s3";
14596
- import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
14597
- import { copy, del, head, list as list4, put } from "@vercel/blob";
14598
15015
  import { posix as posix2 } from "path";
14599
15016
  import { lstat, mkdir as mkdir23, symlink, unlink } from "fs/promises";
14600
15017
  import { dirname as dirname23, relative as relative4 } from "path";
@@ -14884,6 +15301,7 @@ var LocalFilesystem = class {
14884
15301
  await chmod(full, mode);
14885
15302
  }
14886
15303
  };
15304
+ var loadSdk = () => importOptional("@aws-sdk/client-s3", "The s3 disk", () => import("@aws-sdk/client-s3"));
14887
15305
  var isNotFound = (error) => {
14888
15306
  const name = error.name;
14889
15307
  const status = error.$metadata?.httpStatusCode;
@@ -14911,14 +15329,24 @@ async function collectStream(stream) {
14911
15329
  return result;
14912
15330
  }
14913
15331
  var S3Filesystem = class {
15332
+ /** `client` is the client, or what builds it on the first operation. */
14914
15333
  constructor(client, config2) {
14915
15334
  this.client = client;
14916
15335
  this.config = config2;
14917
15336
  }
14918
15337
  client;
14919
15338
  config;
15339
+ #client;
15340
+ resolveClient() {
15341
+ const { client } = this;
15342
+ return this.#client ??= typeof client === "function" ? client() : Promise.resolve(client);
15343
+ }
15344
+ async send(command, input) {
15345
+ const sdk = await loadSdk();
15346
+ return (await this.resolveClient()).send(new sdk[command](input));
15347
+ }
14920
15348
  async head(key) {
14921
- return await this.client.send(new HeadObjectCommand({ Bucket: this.config.bucket, Key: key }));
15349
+ return await this.send("HeadObjectCommand", { Bucket: this.config.bucket, Key: key });
14922
15350
  }
14923
15351
  async exists(path) {
14924
15352
  try {
@@ -14934,7 +15362,7 @@ var S3Filesystem = class {
14934
15362
  }
14935
15363
  async getObject(path) {
14936
15364
  try {
14937
- return await this.client.send(new GetObjectCommand({ Bucket: this.config.bucket, Key: path }));
15365
+ return await this.send("GetObjectCommand", { Bucket: this.config.bucket, Key: path });
14938
15366
  } catch (error) {
14939
15367
  if (isNotFound(error)) throw new FileNotFoundError(path);
14940
15368
  throw error;
@@ -14973,27 +15401,23 @@ var S3Filesystem = class {
14973
15401
  return path;
14974
15402
  }
14975
15403
  async putObject(path, body, contentType, options) {
14976
- await this.client.send(
14977
- new PutObjectCommand({
14978
- Bucket: this.config.bucket,
14979
- Key: path,
14980
- Body: body,
14981
- ContentType: contentType,
14982
- ACL: options?.visibility === "public" ? "public-read" : void 0
14983
- })
14984
- );
15404
+ await this.send("PutObjectCommand", {
15405
+ Bucket: this.config.bucket,
15406
+ Key: path,
15407
+ Body: body,
15408
+ ContentType: contentType,
15409
+ ACL: options?.visibility === "public" ? "public-read" : void 0
15410
+ });
14985
15411
  }
14986
15412
  async delete(paths) {
14987
15413
  for (const path of Array.isArray(paths) ? paths : [paths]) {
14988
- await this.client.send(new DeleteObjectCommand({ Bucket: this.config.bucket, Key: path }));
15414
+ await this.send("DeleteObjectCommand", { Bucket: this.config.bucket, Key: path });
14989
15415
  }
14990
15416
  return true;
14991
15417
  }
14992
15418
  async copy(from, to) {
14993
15419
  try {
14994
- await this.client.send(
14995
- new CopyObjectCommand({ Bucket: this.config.bucket, Key: to, CopySource: `${this.config.bucket}/${encodeURIComponent(from)}` })
14996
- );
15420
+ await this.send("CopyObjectCommand", { Bucket: this.config.bucket, Key: to, CopySource: `${this.config.bucket}/${encodeURIComponent(from)}` });
14997
15421
  } catch (error) {
14998
15422
  if (isNotFound(error)) throw new FileNotFoundError(from);
14999
15423
  throw error;
@@ -15044,9 +15468,11 @@ var S3Filesystem = class {
15044
15468
  return this.config.usePathStyleEndpoint ? `${endpoint}/${this.config.bucket}/${key}` : `${endpoint.replace(/^https?:\/\//, (proto) => `${proto}${this.config.bucket}.`)}/${key}`;
15045
15469
  }
15046
15470
  async temporaryUrl(path, expiresAt) {
15471
+ const { GetObjectCommand } = await loadSdk();
15472
+ const { getSignedUrl } = await importOptional("@aws-sdk/s3-request-presigner", "The s3 disk's temporaryUrl()", () => import("@aws-sdk/s3-request-presigner"));
15047
15473
  const command = new GetObjectCommand({ Bucket: this.config.bucket, Key: path });
15048
15474
  const expiresIn = Math.max(1, Math.round((expiresAt.getTime() - Date.now()) / 1e3));
15049
- return getSignedUrl(this.client, command, { expiresIn });
15475
+ return getSignedUrl(await this.resolveClient(), command, { expiresIn });
15050
15476
  }
15051
15477
  async files(directory = "", recursive = false) {
15052
15478
  const { objects } = await this.list(directory, recursive);
@@ -15058,13 +15484,13 @@ var S3Filesystem = class {
15058
15484
  }
15059
15485
  async makeDirectory(path) {
15060
15486
  const key = path.endsWith("/") ? path : `${path}/`;
15061
- await this.client.send(new PutObjectCommand({ Bucket: this.config.bucket, Key: key, Body: new Uint8Array() }));
15487
+ await this.send("PutObjectCommand", { Bucket: this.config.bucket, Key: key, Body: new Uint8Array() });
15062
15488
  return true;
15063
15489
  }
15064
15490
  async deleteDirectory(path) {
15065
15491
  const prefix = path === "" ? "" : path.endsWith("/") ? path : `${path}/`;
15066
15492
  const keys = await this.listAllKeys(prefix);
15067
- for (const key of keys) await this.client.send(new DeleteObjectCommand({ Bucket: this.config.bucket, Key: key }));
15493
+ for (const key of keys) await this.send("DeleteObjectCommand", { Bucket: this.config.bucket, Key: key });
15068
15494
  return true;
15069
15495
  }
15070
15496
  path(_path) {
@@ -15074,9 +15500,7 @@ var S3Filesystem = class {
15074
15500
  const keys = [];
15075
15501
  let continuationToken;
15076
15502
  do {
15077
- const page = await this.client.send(
15078
- new ListObjectsV2Command({ Bucket: this.config.bucket, Prefix: prefix, ContinuationToken: continuationToken })
15079
- );
15503
+ const page = await this.send("ListObjectsV2Command", { Bucket: this.config.bucket, Prefix: prefix, ContinuationToken: continuationToken });
15080
15504
  for (const object of page.Contents ?? []) if (object.Key) keys.push(object.Key);
15081
15505
  continuationToken = page.IsTruncated ? page.NextContinuationToken : void 0;
15082
15506
  } while (continuationToken);
@@ -15093,9 +15517,7 @@ var S3Filesystem = class {
15093
15517
  const prefixes = [];
15094
15518
  let continuationToken;
15095
15519
  do {
15096
- const page = await this.client.send(
15097
- new ListObjectsV2Command({ Bucket: this.config.bucket, Prefix: prefix, Delimiter: "/", ContinuationToken: continuationToken })
15098
- );
15520
+ const page = await this.send("ListObjectsV2Command", { Bucket: this.config.bucket, Prefix: prefix, Delimiter: "/", ContinuationToken: continuationToken });
15099
15521
  for (const key of (page.Contents ?? []).map((o) => o.Key)) if (key && key !== prefix) objects2.push(key);
15100
15522
  for (const p of (page.CommonPrefixes ?? []).map((c) => c.Prefix)) if (p) prefixes.push(p.replace(/\/$/, ""));
15101
15523
  continuationToken = page.IsTruncated ? page.NextContinuationToken : void 0;
@@ -15118,13 +15540,14 @@ var S3Filesystem = class {
15118
15540
  }
15119
15541
  };
15120
15542
  var asBody = (body) => body instanceof Uint8Array && !Buffer.isBuffer(body) ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : body;
15543
+ var blob = () => importOptional("@vercel/blob", "The blob disk", () => import("@vercel/blob"));
15121
15544
  function vercelBlobClient(token2) {
15122
15545
  return {
15123
- put: (pathname, body, options) => put(pathname, asBody(body), { ...options, token: token2 }),
15124
- head: (pathname) => head(pathname, { token: token2 }),
15125
- del: (pathnames) => del(pathnames, { token: token2 }),
15126
- list: (options) => list4({ ...options, token: token2 }),
15127
- copy: (from, to, options) => copy(from, to, { ...options, token: token2 }),
15546
+ put: async (pathname, body, options) => (await blob()).put(pathname, asBody(body), { ...options, token: token2 }),
15547
+ head: async (pathname) => (await blob()).head(pathname, { token: token2 }),
15548
+ del: async (pathnames) => (await blob()).del(pathnames, { token: token2 }),
15549
+ list: async (options) => (await blob()).list({ ...options, token: token2 }),
15550
+ copy: async (from, to, options) => (await blob()).copy(from, to, { ...options, token: token2 }),
15128
15551
  fetch: (url2) => fetch(url2)
15129
15552
  };
15130
15553
  }
@@ -15206,8 +15629,8 @@ var VercelBlobFilesystem = class {
15206
15629
  await this.client.put(this.key(path), body, { ...CREATE, ...contentType === void 0 ? {} : { contentType } });
15207
15630
  }
15208
15631
  async delete(paths) {
15209
- const list23 = Array.isArray(paths) ? paths : [paths];
15210
- if (list23.length > 0) await this.client.del(list23.map((path) => this.key(path)));
15632
+ const list5 = Array.isArray(paths) ? paths : [paths];
15633
+ if (list5.length > 0) await this.client.del(list5.map((path) => this.key(path)));
15211
15634
  return true;
15212
15635
  }
15213
15636
  async copy(from, to) {
@@ -15280,7 +15703,7 @@ var VercelBlobFilesystem = class {
15280
15703
  let cursor;
15281
15704
  do {
15282
15705
  const page = await this.client.list({ prefix, cursor, mode: recursive ? "expanded" : "folded" });
15283
- blobs.push(...page.blobs.map((blob) => blob.pathname));
15706
+ blobs.push(...page.blobs.map((blob2) => blob2.pathname));
15284
15707
  folders.push(...page.folders ?? []);
15285
15708
  cursor = page.hasMore ? page.cursor : void 0;
15286
15709
  } while (cursor !== void 0);
@@ -15298,7 +15721,7 @@ var FilesystemManager2 = class {
15298
15721
  visibility: config2.visibility
15299
15722
  })
15300
15723
  );
15301
- this.drivers.set("s3", (config2) => new S3Filesystem(this.buildS3Client(config2), this.s3Config(config2)));
15724
+ this.drivers.set("s3", (config2) => new S3Filesystem(() => this.buildS3Client(config2), this.s3Config(config2)));
15302
15725
  this.drivers.set("vercel-blob", (config2) => {
15303
15726
  const token2 = config2.token ?? process.env.BLOB_READ_WRITE_TOKEN;
15304
15727
  return new VercelBlobFilesystem(vercelBlobClient(token2), {
@@ -15312,7 +15735,8 @@ var FilesystemManager2 = class {
15312
15735
  container;
15313
15736
  disks = /* @__PURE__ */ new Map();
15314
15737
  drivers = /* @__PURE__ */ new Map();
15315
- buildS3Client(config2) {
15738
+ async buildS3Client(config2) {
15739
+ const { S3Client } = await importOptional("@aws-sdk/client-s3", "The s3 disk", () => import("@aws-sdk/client-s3"));
15316
15740
  const key = config2.key;
15317
15741
  const secret = config2.secret;
15318
15742
  return new S3Client({
@@ -16609,8 +17033,8 @@ var InertiaMiddleware = class {
16609
17033
  bag,
16610
17034
  Object.fromEntries(
16611
17035
  Object.entries(fields ?? {}).map(([field, messages]) => {
16612
- const list6 = Array.isArray(messages) ? messages.map(String) : [String(messages)];
16613
- return [field, this.withAllErrors ? list6 : list6[0] ?? ""];
17036
+ const list5 = Array.isArray(messages) ? messages.map(String) : [String(messages)];
17037
+ return [field, this.withAllErrors ? list5 : list5[0] ?? ""];
16614
17038
  })
16615
17039
  )
16616
17040
  ])
@@ -16913,7 +17337,7 @@ function registerInertiaCommands(kernel, app2, gateway, options = {}) {
16913
17337
  const runtime = optionText(this.option("runtime")) ?? config2("inertia.ssr.runtime", "node");
16914
17338
  const child = (options.spawn ?? spawn2)(runtime, [bundle], { stdio: "inherit", env: { ...process.env, INERTIA_SSR_PORT: port } });
16915
17339
  return await new Promise((resolve5) => {
16916
- child.on("exit", (code) => resolve5(code ?? 0));
17340
+ child.on("exit", (code, signal) => resolve5(code ?? (signal ? 1 : 0)));
16917
17341
  child.on("error", (error) => {
16918
17342
  this.error(`Could not start the SSR server: ${error.message}`);
16919
17343
  resolve5(1);
@@ -16921,6 +17345,10 @@ function registerInertiaCommands(kernel, app2, gateway, options = {}) {
16921
17345
  });
16922
17346
  }).purpose("Start the Inertia SSR server");
16923
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
+ }
16924
17352
  try {
16925
17353
  await fetch(`${gateway.productionUrl()}/shutdown`);
16926
17354
  } catch {
@@ -17093,7 +17521,7 @@ var InertiaServiceProvider = class extends ServiceProvider {
17093
17521
  import pino2 from "pino";
17094
17522
  import { createWriteStream as createWriteStream2, mkdirSync as mkdirSync3, readdirSync as readdirSync6, rmSync } from "fs";
17095
17523
  import { basename as basename2, dirname as dirname6, extname as extname3, join as join12 } from "path";
17096
- import { Writable } from "stream";
17524
+ import { Writable as Writable2 } from "stream";
17097
17525
  import "pino";
17098
17526
  var rootKey = {};
17099
17527
  var contexts = /* @__PURE__ */ new WeakMap();
@@ -17213,7 +17641,7 @@ function localDay(date) {
17213
17641
  return `${date.getFullYear()}-${month}-${day}`;
17214
17642
  }
17215
17643
  var DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
17216
- var DailyRotatingStream = class extends Writable {
17644
+ var DailyRotatingStream = class extends Writable2 {
17217
17645
  constructor(basePath, days, now5 = () => /* @__PURE__ */ new Date()) {
17218
17646
  super();
17219
17647
  this.days = days;
@@ -17631,8 +18059,8 @@ function normalizeAddress(recipient) {
17631
18059
  }
17632
18060
  function normalizeAddresses(recipients) {
17633
18061
  if (recipients === void 0) return [];
17634
- const list6 = Array.isArray(recipients) ? recipients : [recipients];
17635
- return list6.map(normalizeAddress);
18062
+ const list5 = Array.isArray(recipients) ? recipients : [recipients];
18063
+ return list5.map(normalizeAddress);
17636
18064
  }
17637
18065
  function formatAddress(address) {
17638
18066
  return address.name ? `${address.name} <${address.address}>` : address.address;
@@ -17699,13 +18127,18 @@ var FailoverTransport = class {
17699
18127
  throw new AllMailersFailedError(this.names, causes);
17700
18128
  }
17701
18129
  };
17702
- var defaultFactory = (config2) => nodemailer.createTransport({
17703
- host: config2.host,
17704
- port: config2.port,
17705
- secure: config2.encryption === "ssl",
17706
- requireTLS: config2.encryption === "tls",
17707
- auth: config2.username ? { user: config2.username, pass: config2.password } : void 0
17708
- });
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));
17709
18142
  var SmtpTransport = class {
17710
18143
  transporter;
17711
18144
  constructor(config2, factory = defaultFactory) {
@@ -17933,7 +18366,7 @@ function copyShouldQueueFields(target, source) {
17933
18366
  }
17934
18367
  function recipientsHash(to = [], cc = [], bcc = []) {
17935
18368
  if (to.length + cc.length + bcc.length === 0) return void 0;
17936
- const addresses = (list6) => list6.map((recipient) => recipient.address);
18369
+ const addresses = (list5) => list5.map((recipient) => recipient.address);
17937
18370
  const recipients = JSON.stringify({ to: addresses(to), cc: addresses(cc), bcc: addresses(bcc) });
17938
18371
  return createHash8("sha1").update(recipients).digest("hex");
17939
18372
  }
@@ -18654,9 +19087,9 @@ function isQueueableNotification(notification) {
18654
19087
  }
18655
19088
  function forNotifiable(notification) {
18656
19089
  if (notification.id) return notification;
18657
- const copy2 = Object.assign(Object.create(Object.getPrototypeOf(notification)), notification);
18658
- copy2.id = randomUUID23();
18659
- return copy2;
19090
+ const copy = Object.assign(Object.create(Object.getPrototypeOf(notification)), notification);
19091
+ copy.id = randomUUID23();
19092
+ return copy;
18660
19093
  }
18661
19094
  function toNotifiableList(notifiables) {
18662
19095
  if (Array.isArray(notifiables)) return notifiables;
@@ -18687,12 +19120,12 @@ var Dispatcher3 = class {
18687
19120
  return channel;
18688
19121
  }
18689
19122
  async send(notifiables, notification) {
18690
- const list6 = toNotifiableList(notifiables);
18691
- if (list6.length === 0) return;
19123
+ const list5 = toNotifiableList(notifiables);
19124
+ if (list5.length === 0) return;
18692
19125
  if (isQueueableNotification(notification)) {
18693
19126
  if (!this.container.bound(BusDispatcher)) throw new NotificationQueueUnavailableError();
18694
19127
  const bus = this.container.make(BusDispatcher);
18695
- for (const notifiable of list6) {
19128
+ for (const notifiable of list5) {
18696
19129
  const own = forNotifiable(notification);
18697
19130
  for (const channel of notification.via(notifiable)) {
18698
19131
  await bus.dispatch(new SendQueuedNotifications([notifiable], own, [channel]));
@@ -18700,11 +19133,11 @@ var Dispatcher3 = class {
18700
19133
  }
18701
19134
  return;
18702
19135
  }
18703
- await this.sendNow(list6, notification);
19136
+ await this.sendNow(list5, notification);
18704
19137
  }
18705
19138
  async sendNow(notifiables, notification, channels) {
18706
- const list6 = toNotifiableList(notifiables);
18707
- for (const notifiable of list6) {
19139
+ const list5 = toNotifiableList(notifiables);
19140
+ for (const notifiable of list5) {
18708
19141
  const own = forNotifiable(notification);
18709
19142
  const names = channels ?? notification.via(notifiable);
18710
19143
  for (const name of names) {
@@ -18858,14 +19291,14 @@ var PipelineServiceProvider = class {
18858
19291
  import { Buffer as Buffer2 } from "buffer";
18859
19292
  import { randomUUID as randomUUID5 } from "crypto";
18860
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";
18861
19297
  import { Redis as Redis2 } from "ioredis";
18862
19298
  import { randomUUID as randomUUID32 } from "crypto";
18863
19299
  import { setTimeout as sleep4 } from "timers/promises";
18864
19300
  import { spawn as spawnProcess } from "child_process";
18865
19301
  import { setTimeout as sleep22 } from "timers/promises";
18866
- import { existsSync as existsSync8, readdirSync as readdirSync7, statSync as statSync3 } from "fs";
18867
- import { join as join13 } from "path";
18868
- import { pathToFileURL as pathToFileURL6 } from "url";
18869
19302
  var QueueError = class extends Error {
18870
19303
  kind = "Server";
18871
19304
  status = 500;
@@ -19349,13 +19782,19 @@ var CallQueuedHandler = class {
19349
19782
  if (payload.batchId !== void 0 && payload.batchCallback !== true && this.container.bound(BatchRepository)) {
19350
19783
  await this.container.make(BatchRepository).recordFailedJob(payload.batchId, payload.uuid, error);
19351
19784
  }
19785
+ const chain = { connection: payload.chainConnection ?? job.getConnectionName(), queue: payload.chainQueue };
19352
19786
  for (const callback of payload.chainCatch ?? []) {
19353
- await this.dispatchCallback(await restoreJob(callback, this.container.make(ClassRegistry)));
19787
+ await this.dispatchCallback(await restoreJob(callback, this.container.make(ClassRegistry)), chain);
19354
19788
  }
19355
19789
  if (instance && typeof instance.failed === "function") await instance.failed(error);
19356
19790
  }
19357
- /** Dispatches a callback job (chain catch, batch then/catch/finally) through the Bus, or runs it inline. */
19358
- 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;
19359
19798
  if (this.container.bound(BusDispatcher)) await this.container.make(BusDispatcher).dispatch(callback);
19360
19799
  else await callback.handle();
19361
19800
  }
@@ -19449,6 +19888,90 @@ var WithoutOverlapping = class {
19449
19888
  return void 0;
19450
19889
  }
19451
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
+ }
19452
19975
  var QueueBase = class {
19453
19976
  constructor(container, defaultQueue = "default") {
19454
19977
  this.container = container;
@@ -19473,10 +19996,12 @@ var QueueBase = class {
19473
19996
  createPayload(job) {
19474
19997
  return createPayload(job, this.container.make(ClassRegistry));
19475
19998
  }
19476
- push(job, queue) {
19999
+ async push(job, queue) {
20000
+ await ensureAppClasses(this.container);
19477
20001
  return this.pushRaw(this.createPayload(job), queue ?? (optionalString2(job.queue) || void 0));
19478
20002
  }
19479
- later(delaySeconds2, job, queue) {
20003
+ async later(delaySeconds2, job, queue) {
20004
+ await ensureAppClasses(this.container);
19480
20005
  return this.pushRaw(this.createPayload(job), queue ?? (optionalString2(job.queue) || void 0), delaySeconds2);
19481
20006
  }
19482
20007
  /** Closes network connections (redis). No-op by default. */
@@ -20122,6 +20647,7 @@ var DatabaseBatchRepository = class {
20122
20647
  handler;
20123
20648
  async store(options) {
20124
20649
  const id = randomUUID32();
20650
+ await ensureAppClasses(this.container);
20125
20651
  const registry2 = this.container.make(ClassRegistry);
20126
20652
  const payloads = (jobs) => jobs.map((job) => createPayload(job, registry2));
20127
20653
  const stored = {
@@ -20210,7 +20736,7 @@ var DatabaseBatchRepository = class {
20210
20736
  const job = await restoreJob(payload, registry2);
20211
20737
  job.batchId = batch.id;
20212
20738
  setSymbolValue(job, BATCH_CALLBACK, true);
20213
- await this.handler.dispatchCallback(job);
20739
+ await this.handler.dispatchCallback(job, { connection: batch.options.connection, queue: batch.options.queue });
20214
20740
  }
20215
20741
  }
20216
20742
  toBatch(row) {
@@ -20654,35 +21180,8 @@ var Listener = class _Listener {
20654
21180
  }
20655
21181
  }
20656
21182
  };
20657
- var EXTENSIONS2 = [".ts", ".js", ".mts", ".mjs"];
20658
- function files2(directory) {
20659
- const found = [];
20660
- for (const entry of readdirSync7(directory).sort()) {
20661
- const path = join13(directory, entry);
20662
- if (statSync3(path).isDirectory()) found.push(...files2(path));
20663
- else if (EXTENSIONS2.some((extension) => entry.endsWith(extension)) && !entry.endsWith(".d.ts")) found.push(path);
20664
- }
20665
- return found;
20666
- }
20667
- var WORKER_DISCOVERY_DIRECTORIES = ["Events", "Listeners", "Mail", "Notifications"];
20668
- var isClass2 = (value2) => typeof value2 === "function" && /^class[\s{]/.test(Function.prototype.toString.call(value2));
20669
- var isJobClass = (value2) => typeof value2.prototype.handle === "function";
20670
- async function discoverClasses(directory, registry2, filter = () => true) {
20671
- if (!existsSync8(directory)) return [];
20672
- const names = [];
20673
- for (const file of files2(directory)) {
20674
- const module = await import(pathToFileURL6(file).href);
20675
- for (const exported of Object.values(module)) {
20676
- if (isClass2(exported) && filter(exported)) names.push(classNameOf(registry2, exported));
20677
- }
20678
- }
20679
- return names;
20680
- }
20681
- function discoverJobs(directory, registry2) {
20682
- return discoverClasses(directory, registry2, isJobClass);
20683
- }
20684
21183
  var text3 = (value2) => optionalString2(value2) || void 0;
20685
- var list5 = (value2) => Array.isArray(value2) ? value2.map(String) : text3(value2) ? [String(value2)] : [];
21184
+ var list4 = (value2) => Array.isArray(value2) ? value2.map(String) : text3(value2) ? [String(value2)] : [];
20686
21185
  var number2 = (value2, fallback) => {
20687
21186
  const parsed = Number(value2);
20688
21187
  return value2 === void 0 || value2 === null || value2 === "" || Number.isNaN(parsed) ? fallback : parsed;
@@ -20744,8 +21243,7 @@ function registerQueueCommands(kernel, context) {
20744
21243
  const connection = text3(out.argument("connection")) ?? defaultConnection();
20745
21244
  const queue = text3(out.option("queue")) ?? defaultQueue(connection);
20746
21245
  const registry2 = container.make(ClassRegistry);
20747
- await discoverJobs(context.app.appPath("Jobs"), registry2);
20748
- for (const directory of WORKER_DISCOVERY_DIRECTORIES) await discoverClasses(context.app.appPath(directory), registry2);
21246
+ await registerAppClasses(context.app.appPath(), registry2);
20749
21247
  const name = (job) => job.payload().displayName;
20750
21248
  const worker = new Worker(container.make(QueueManager), container, {
20751
21249
  processing: (job) => out.line(` ${localTimestamp()} ${name(job)} RUNNING`),
@@ -20807,7 +21305,7 @@ function registerQueueCommands(kernel, context) {
20807
21305
  'queue:retry {id?* : The ID of the failed job or "all" to retry all jobs} {--queue= : Retry all of the failed jobs for the specified queue}',
20808
21306
  "Retry a failed queue job",
20809
21307
  async (out) => {
20810
- const ids = await retryableIds(list5(out.argument("id")), text3(out.option("queue")));
21308
+ const ids = await retryableIds(list4(out.argument("id")), text3(out.option("queue")));
20811
21309
  if (ids.length === 0) {
20812
21310
  out.info("No retryable jobs found.");
20813
21311
  return 0;
@@ -20920,7 +21418,7 @@ var QueueServiceProvider = class extends ServiceProvider {
20920
21418
  };
20921
21419
 
20922
21420
  // ../Routing/dist/index.js
20923
- import { createHmac as createHmac6, timingSafeEqual as timingSafeEqual6 } from "crypto";
21421
+ import { createHmac as createHmac7, timingSafeEqual as timingSafeEqual6 } from "crypto";
20924
21422
  import { pathToFileURL as pathToFileURL7 } from "url";
20925
21423
  import { createHash as createHash10 } from "crypto";
20926
21424
  import { createHash as createHash23 } from "crypto";
@@ -21685,20 +22183,20 @@ var BaseRouter = class {
21685
22183
  return this;
21686
22184
  }
21687
22185
  pushMiddlewareToGroup(group, middleware) {
21688
- const list6 = this.#groups[group] ??= [];
21689
- if (!list6.includes(middleware)) list6.push(middleware);
22186
+ const list5 = this.#groups[group] ??= [];
22187
+ if (!list5.includes(middleware)) list5.push(middleware);
21690
22188
  return this;
21691
22189
  }
21692
22190
  prependMiddlewareToGroup(group, middleware) {
21693
- const list6 = this.#groups[group] ??= [];
21694
- if (!list6.includes(middleware)) list6.unshift(middleware);
22191
+ const list5 = this.#groups[group] ??= [];
22192
+ if (!list5.includes(middleware)) list5.unshift(middleware);
21695
22193
  return this;
21696
22194
  }
21697
22195
  hasMiddlewareGroup(name) {
21698
22196
  return Object.hasOwn(this.#groups, name);
21699
22197
  }
21700
22198
  getMiddlewareGroups() {
21701
- return Object.fromEntries(Object.entries(this.#groups).map(([name, list6]) => [name, [...list6]]));
22199
+ return Object.fromEntries(Object.entries(this.#groups).map(([name, list5]) => [name, [...list5]]));
21702
22200
  }
21703
22201
  /** Every route, in registration order. */
21704
22202
  getRoutes() {
@@ -21761,7 +22259,7 @@ function routeKey(value2, field) {
21761
22259
  return typeof model.getRouteKey === "function" ? model.getRouteKey() : value2;
21762
22260
  }
21763
22261
  function sign(url2, key) {
21764
- return createHmac6("sha256", key).update(url2).digest("hex");
22262
+ return createHmac7("sha256", key).update(url2).digest("hex");
21765
22263
  }
21766
22264
  function safeEquals(expected, given) {
21767
22265
  const a = Buffer.from(expected);
@@ -21997,9 +22495,9 @@ function withHeaders2(response2, headers) {
21997
22495
  for (const [name, value2] of Object.entries(headers)) response2.headers.set(name, value2);
21998
22496
  return response2;
21999
22497
  } catch {
22000
- const copy2 = new Headers(response2.headers);
22001
- for (const [name, value2] of Object.entries(headers)) copy2.set(name, value2);
22002
- return new Response(response2.body, { status: response2.status, statusText: response2.statusText, headers: copy2 });
22498
+ const copy = new Headers(response2.headers);
22499
+ for (const [name, value2] of Object.entries(headers)) copy.set(name, value2);
22500
+ return new Response(response2.body, { status: response2.status, statusText: response2.statusText, headers: copy });
22003
22501
  }
22004
22502
  }
22005
22503
  var ThrottleRequests = class {
@@ -22206,8 +22704,8 @@ var Store = class {
22206
22704
  for (const [name, item] of Object.entries(values)) Arr.set(this.#attributes, name, item);
22207
22705
  }
22208
22706
  push(key, value2) {
22209
- const list6 = this.get(key, []);
22210
- this.put(key, [...Array.isArray(list6) ? list6 : [list6], value2]);
22707
+ const list5 = this.get(key, []);
22708
+ this.put(key, [...Array.isArray(list5) ? list5 : [list5], value2]);
22211
22709
  }
22212
22710
  increment(key, amount = 1) {
22213
22711
  const value2 = Number(this.get(key, 0)) + amount;
@@ -22405,18 +22903,20 @@ var FileSessionHandler = class {
22405
22903
  }
22406
22904
  };
22407
22905
  var DatabaseSessionHandler = class {
22408
- constructor(connection, table, minutes, container = () => void 0, clock = Date.now) {
22906
+ constructor(connection, table, minutes, container = () => void 0, clock = Date.now, options = {}) {
22409
22907
  this.connection = connection;
22410
22908
  this.table = table;
22411
22909
  this.minutes = minutes;
22412
22910
  this.container = container;
22413
22911
  this.clock = clock;
22912
+ this.options = options;
22414
22913
  }
22415
22914
  connection;
22416
22915
  table;
22417
22916
  minutes;
22418
22917
  container;
22419
22918
  clock;
22919
+ options;
22420
22920
  #exists = false;
22421
22921
  async read(id) {
22422
22922
  const session2 = await this.#query().where("id", id).first();
@@ -22458,7 +22958,10 @@ var DatabaseSessionHandler = class {
22458
22958
  const payload = { payload: Buffer.from(data, "utf8").toString("base64"), last_activity: this.#now() };
22459
22959
  const container = this.container();
22460
22960
  if (container === void 0) return payload;
22461
- if (container.bound(HttpRequest)) {
22961
+ if (this.options.clientDetails !== true) {
22962
+ payload.ip_address = null;
22963
+ payload.user_agent = null;
22964
+ } else if (container.bound(HttpRequest)) {
22462
22965
  const request2 = container.make(HttpRequest);
22463
22966
  payload.ip_address = request2.ip() ?? null;
22464
22967
  payload.user_agent = (request2.header("user-agent") ?? "").slice(0, 500);
@@ -22590,7 +23093,9 @@ var SessionManager = class {
22590
23093
  () => container.make(DatabaseManager).connection(config2.connection ?? void 0),
22591
23094
  config2.table ?? "sessions",
22592
23095
  lifetime,
22593
- () => container
23096
+ () => container,
23097
+ void 0,
23098
+ { clientDetails: config2.client_details === true }
22594
23099
  );
22595
23100
  case "cookie":
22596
23101
  return new CookieSessionHandler(
@@ -22845,7 +23350,8 @@ var SessionServiceProvider = class extends ServiceProvider {
22845
23350
  domain: null,
22846
23351
  secure: null,
22847
23352
  http_only: true,
22848
- same_site: "lax"
23353
+ same_site: "lax",
23354
+ client_details: false
22849
23355
  },
22850
23356
  "session"
22851
23357
  );
@@ -22881,7 +23387,7 @@ var ValidationErrorImpl = class extends Error {
22881
23387
  var ValidationException = class _ValidationException extends ValidationErrorImpl {
22882
23388
  /** Messages per field, each a string or a list. */
22883
23389
  static withMessages(messages) {
22884
- const errors2 = Object.fromEntries(Object.entries(messages).map(([field, list6]) => [field, typeof list6 === "string" ? [list6] : [...list6]]));
23390
+ const errors2 = Object.fromEntries(Object.entries(messages).map(([field, list5]) => [field, typeof list5 === "string" ? [list5] : [...list5]]));
22885
23391
  return new _ValidationException(errors2);
22886
23392
  }
22887
23393
  constructor(errors2, errorBag = "default", redirectTo2) {
@@ -23778,8 +24284,8 @@ function resolveDateParam(ctx, rule, param, format2) {
23778
24284
  const parsed = readDate(fieldValue, ctx.getRule?.(param, "date_format")?.[0] ?? format2);
23779
24285
  if (!Number.isNaN(parsed)) return parsed;
23780
24286
  }
23781
- const relative9 = relativeDate(param);
23782
- if (relative9 !== void 0) return relative9;
24287
+ const relative10 = relativeDate(param);
24288
+ if (relative10 !== void 0) return relative10;
23783
24289
  const literal = readDate(param, format2);
23784
24290
  if (!Number.isNaN(literal)) return literal;
23785
24291
  if (FIELD_REFERENCE_RE.test(param)) return null;
@@ -24133,11 +24639,11 @@ var urlPatterns = /* @__PURE__ */ new Map();
24133
24639
  function isUrl(value2, protocols) {
24134
24640
  if (typeof value2 !== "string") return false;
24135
24641
  if (protocols.length === 0) return URL_RE.test(value2);
24136
- const list6 = protocols.join("|");
24137
- let pattern = urlPatterns.get(list6);
24642
+ const list5 = protocols.join("|");
24643
+ let pattern = urlPatterns.get(list5);
24138
24644
  if (pattern === void 0) {
24139
24645
  try {
24140
- pattern = urlPattern(list6);
24646
+ pattern = urlPattern(list5);
24141
24647
  } catch (error) {
24142
24648
  throw new InvalidRuleParameterError(
24143
24649
  "url",
@@ -24145,7 +24651,7 @@ function isUrl(value2, protocols) {
24145
24651
  error instanceof Error ? error.message : String(error)
24146
24652
  );
24147
24653
  }
24148
- urlPatterns.set(list6, pattern);
24654
+ urlPatterns.set(list5, pattern);
24149
24655
  }
24150
24656
  return pattern.test(value2);
24151
24657
  }
@@ -24571,11 +25077,11 @@ var sizeRules = {
24571
25077
  in: { validate: (ctx) => isListed(ctx.value, ctx.parameters, ctx.ruleNames), messageKey: () => "in" },
24572
25078
  not_in: { validate: (ctx) => !isListed(ctx.value, ctx.parameters, ctx.ruleNames), messageKey: () => "not_in" }
24573
25079
  };
24574
- function isListed(value2, list6, ruleNames) {
25080
+ function isListed(value2, list5, ruleNames) {
24575
25081
  if (Array.isArray(value2) && ruleNames.includes("array")) {
24576
- return value2.every((item) => (typeof item !== "object" || item === null) && list6.includes(String(item)));
25082
+ return value2.every((item) => (typeof item !== "object" || item === null) && list5.includes(String(item)));
24577
25083
  }
24578
- return (typeof value2 !== "object" || value2 === null) && list6.includes(String(value2));
25084
+ return (typeof value2 !== "object" || value2 === null) && list5.includes(String(value2));
24579
25085
  }
24580
25086
  var REGIONS = ["Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Australia", "Europe", "Indian", "Pacific"];
24581
25087
  var ZONE_RE = /^[A-Z][A-Za-z_-]*(?:\/[A-Z][A-Za-z0-9_+-]*)+$/;
@@ -24724,13 +25230,13 @@ var PasswordRule = class _PasswordRule {
24724
25230
  if (this.#numbers && !/\p{N}/u.test(value2)) say("password.numbers");
24725
25231
  }
24726
25232
  #copy() {
24727
- const copy2 = new _PasswordRule(this.#min);
24728
- copy2.#max = this.#max;
24729
- copy2.#letters = this.#letters;
24730
- copy2.#mixedCase = this.#mixedCase;
24731
- copy2.#numbers = this.#numbers;
24732
- copy2.#symbols = this.#symbols;
24733
- return copy2;
25233
+ const copy = new _PasswordRule(this.#min);
25234
+ copy.#max = this.#max;
25235
+ copy.#letters = this.#letters;
25236
+ copy.#mixedCase = this.#mixedCase;
25237
+ copy.#numbers = this.#numbers;
25238
+ copy.#symbols = this.#symbols;
25239
+ return copy;
24734
25240
  }
24735
25241
  };
24736
25242
  var BuiltinRuleObject = class {
@@ -25080,10 +25586,10 @@ function withoutPaths(data, paths) {
25080
25586
  node = void 0;
25081
25587
  break;
25082
25588
  }
25083
- const copy2 = copies.has(child) ? child : Array.isArray(child) ? [...child] : { ...child };
25084
- copies.add(copy2);
25085
- node[part2] = copy2;
25086
- node = copy2;
25589
+ const copy = copies.has(child) ? child : Array.isArray(child) ? [...child] : { ...child };
25590
+ copies.add(copy);
25591
+ node[part2] = copy;
25592
+ node = copy;
25087
25593
  }
25088
25594
  if (node === void 0 || !Object.hasOwn(node, leaf)) continue;
25089
25595
  if (Array.isArray(node)) node[Number(leaf)] = EXCLUDED;
@@ -25366,7 +25872,7 @@ var ValidationServiceProvider = class extends ServiceProvider {
25366
25872
  // ../Vercel/dist/index.js
25367
25873
  import { existsSync as existsSync9, readdirSync as readdirSync8, readFileSync as readFileSync3, realpathSync, statSync as statSync4 } from "fs";
25368
25874
  import { cp, mkdir as mkdir7, rm as rm4, writeFile as writeFile8 } from "fs/promises";
25369
- 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";
25370
25876
  import { CronExpressionParser as CronExpressionParser2 } from "cron-parser";
25371
25877
  import { timingSafeEqual as timingSafeEqual8 } from "crypto";
25372
25878
  import { CronExpressionParser as CronExpressionParser3 } from "cron-parser";
@@ -25478,7 +25984,7 @@ async function buildVercelOutput(app2, options = {}) {
25478
25984
  const staticFolder = join15(output, "static");
25479
25985
  await mkdir7(staticFolder, { recursive: true });
25480
25986
  if (existsSync9(publicPath)) {
25481
- 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)) });
25482
25988
  }
25483
25989
  const fn = join15(output, "functions/index.func");
25484
25990
  for (const folder of APP_FOLDERS) {
@@ -25488,7 +25994,7 @@ async function buildVercelOutput(app2, options = {}) {
25488
25994
  for (const file of APP_FILES) if (existsSync9(join15(base, file))) await cp(join15(base, file), join15(fn, file));
25489
25995
  for (const file of BUILD_FILES) {
25490
25996
  const source = join15(publicPath, "build", file);
25491
- 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));
25492
25998
  }
25493
25999
  await copyDependencies(base, fn);
25494
26000
  await writeFile8(join15(fn, "index.mjs"), LAUNCHER);
@@ -25565,10 +26071,10 @@ async function copyDependencies(base, fn) {
25565
26071
  for (const name of [...Object.keys(manifest.dependencies ?? {}), "tsx"]) await visit(name, base, join15(fn, "node_modules"));
25566
26072
  }
25567
26073
  function locate(name, from) {
25568
- for (let dir = from; ; dir = dirname7(dir)) {
26074
+ for (let dir = from; ; dir = dirname8(dir)) {
25569
26075
  const candidate = basename3(dir) === "node_modules" ? join15(dir, name) : join15(dir, "node_modules", name);
25570
26076
  if (existsSync9(join15(candidate, "package.json"))) return candidate;
25571
- if (dirname7(dir) === dir) return void 0;
26077
+ if (dirname8(dir) === dir) return void 0;
25572
26078
  }
25573
26079
  }
25574
26080
  function sizeOf2(folder) {
@@ -25608,16 +26114,16 @@ var VercelServiceProvider = class extends ServiceProvider {
25608
26114
 
25609
26115
  // ide/IdeInfoCommand.ts
25610
26116
  import { existsSync as existsSync11, readdirSync as readdirSync10, readFileSync as readFileSync4 } from "fs";
25611
- 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";
25612
26118
 
25613
26119
  // ide/sections.ts
25614
26120
  import { existsSync as existsSync10, readdirSync as readdirSync9 } from "fs";
25615
- 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";
25616
26122
  import { parse as parse2 } from "dotenv";
25617
26123
  var SECRET = /key|secret|password|token|credential|salt|private/i;
25618
26124
  var CREDENTIALS = /^[a-z][a-z0-9+.-]*:\/\/[^/?#\s]*@/i;
25619
26125
  var byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
25620
- var posix3 = (path) => path.split(sep5).join("/");
26126
+ var posix3 = (path) => path.split(sep6).join("/");
25621
26127
  function commandSection(all) {
25622
26128
  return Object.entries(all).map(([name, command]) => {
25623
26129
  const signature = parseSignature(command.signature);
@@ -25659,8 +26165,8 @@ function viewSection(paths, hints, extensions, basePath) {
25659
26165
  const extension = extensions.find((candidate) => item.name.endsWith(`.${candidate}`));
25660
26166
  if (extension === void 0) continue;
25661
26167
  const file = join16(item.parentPath, item.name);
25662
- const name = prefix + posix3(relative7(root, file)).slice(0, -(extension.length + 1)).split("/").join(".");
25663
- 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)));
25664
26170
  }
25665
26171
  };
25666
26172
  for (const path of paths) collect2(path, "");
@@ -25669,7 +26175,7 @@ function viewSection(paths, hints, extensions, basePath) {
25669
26175
  }
25670
26176
 
25671
26177
  // ide/IdeInfoCommand.ts
25672
- var posix4 = (path) => path.split(sep6).join("/");
26178
+ var posix4 = (path) => path.split(sep7).join("/");
25673
26179
  var read = (file) => existsSync11(file) ? readFileSync4(file, "utf8") : null;
25674
26180
  var IdeInfoCommand = class extends Command {
25675
26181
  signature = "ide:info {--pretty : Indent the JSON}";
@@ -25701,7 +26207,7 @@ function describe(app2, container) {
25701
26207
  const basePath = app2.basePath();
25702
26208
  const config2 = optional(ConfigRepository);
25703
26209
  const get = (key, fallback) => config2 ? config2.get(key, fallback) : fallback;
25704
- const relativeTo = (file) => posix4(relative8(basePath, file));
26210
+ const relativeTo = (file) => posix4(relative9(basePath, file));
25705
26211
  const configDirectory = app2.configPath();
25706
26212
  const configFiles = existsSync11(configDirectory) ? readdirSync10(configDirectory).filter((file) => /\.(ts|js|mjs)$/.test(file)).map((file) => relativeTo(join17(configDirectory, file))) : [];
25707
26213
  const factory = optional(ViewFactory);
@@ -25818,6 +26324,7 @@ export {
25818
26324
  AuthServiceProvider,
25819
26325
  AuthenticatableModel,
25820
26326
  Authenticate,
26327
+ AuthenticateSession,
25821
26328
  AuthenticationError,
25822
26329
  Authorizable,
25823
26330
  AuthorizationError,
@@ -25866,6 +26373,7 @@ export {
25866
26373
  Computed,
25867
26374
  Config,
25868
26375
  Connection,
26376
+ ConsoleAbortedError,
25869
26377
  Kernel2 as ConsoleKernelImpl,
25870
26378
  ConsoleServiceProvider,
25871
26379
  Container2 as Container,
@@ -25880,6 +26388,7 @@ export {
25880
26388
  CookieValuePrefix,
25881
26389
  CorruptComponentPayloadError,
25882
26390
  Crypt,
26391
+ CurrentDeviceLogout,
25883
26392
  Cursor,
25884
26393
  CursorPaginator,
25885
26394
  DB,
@@ -25986,6 +26495,7 @@ export {
25986
26495
  InvalidListenerError,
25987
26496
  InvalidLiveRequestError,
25988
26497
  InvalidLogLevelError,
26498
+ InvalidPasswordError,
25989
26499
  InvalidRuleParameterError,
25990
26500
  InvalidSignatureError,
25991
26501
  InvalidUploadSignatureError,
@@ -26066,6 +26576,7 @@ export {
26066
26576
  Migrator,
26067
26577
  MissingAppKeyError,
26068
26578
  MissingModelError,
26579
+ MissingPackageError,
26069
26580
  MissingRecipientError,
26070
26581
  Model,
26071
26582
  ModelNotFoundError,
@@ -26095,6 +26606,7 @@ export {
26095
26606
  On,
26096
26607
  OnceProp,
26097
26608
  OptionalProp,
26609
+ OtherDeviceLogout,
26098
26610
  PERSISTENT_MIDDLEWARE,
26099
26611
  PERSONAL_ACCESS_TOKENS_MIGRATION,
26100
26612
  PREVIEW_URI,
@@ -26221,6 +26733,7 @@ export {
26221
26733
  TrimStrings,
26222
26734
  TsxView,
26223
26735
  TwoFactor,
26736
+ TwoFactorAppAlreadyEnabledError,
26224
26737
  TwoFactorAppDisabled,
26225
26738
  TwoFactorAppEnabled,
26226
26739
  TwoFactorAuthenticated,
@@ -26253,6 +26766,7 @@ export {
26253
26766
  UnrenderableNotificationMailError,
26254
26767
  UnsupportedCipherError,
26255
26768
  UnsupportedOperationError,
26769
+ UploadAlreadyStoredError,
26256
26770
  UploadValidationError,
26257
26771
  UrlGenerationError,
26258
26772
  VERCEL_FUNCTION_LIMIT,
@@ -26296,6 +26810,7 @@ export {
26296
26810
  auth,
26297
26811
  back,
26298
26812
  bcrypt3 as bcrypt,
26813
+ blobStoreUrl,
26299
26814
  buildVercelOutput,
26300
26815
  builtinRules,
26301
26816
  bunRuntime,
@@ -26500,6 +27015,7 @@ export {
26500
27015
  toResponse,
26501
27016
  toWebRequest,
26502
27017
  tokenableType,
27018
+ totpCode,
26503
27019
  transformLeaves,
26504
27020
  url,
26505
27021
  usePaginationResolvers,