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

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 (68) hide show
  1. package/dist/{chunk-GCMPAXIK.js → chunk-3QHTNAMZ.js} +6 -4
  2. package/dist/{chunk-GCMPAXIK.js.map → chunk-3QHTNAMZ.js.map} +1 -1
  3. package/dist/{chunk-BKA5F3TH.js → chunk-6AXJB4CD.js} +5 -1
  4. package/dist/chunk-6AXJB4CD.js.map +1 -0
  5. package/dist/{chunk-7GPMFMS7.js → chunk-MG4YEWMV.js} +1239 -488
  6. package/dist/chunk-MG4YEWMV.js.map +1 -0
  7. package/dist/{chunk-FVI6X3VJ.js → chunk-YNDMTTWL.js} +114 -8
  8. package/dist/chunk-YNDMTTWL.js.map +1 -0
  9. package/dist/contracts.d.ts +112 -1
  10. package/dist/contracts.js +5 -1
  11. package/dist/{index.d-lffxurFs.d.ts → index.d-DA-Iu2a2.d.ts} +39 -2
  12. package/dist/index.d.ts +2780 -2137
  13. package/dist/index.js +1410 -543
  14. package/dist/index.js.map +1 -1
  15. package/dist/{jsx-runtime-Bc5KJzwb.d.ts → jsx-runtime-CenT41Y0.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-CVpo7aRl.d.ts → testing-B8J_HhF4.d.ts} +6 -2
  19. package/dist/testing.d.ts +2 -2
  20. package/dist/testing.js +3 -3
  21. package/docs/authentication.md +45 -3
  22. package/docs/authorization.md +2 -4
  23. package/docs/cache.md +29 -5
  24. package/docs/configuration.md +84 -7
  25. package/docs/console.md +41 -2
  26. package/docs/container.md +4 -0
  27. package/docs/csrf.md +2 -2
  28. package/docs/database.md +22 -0
  29. package/docs/deployment.md +39 -17
  30. package/docs/eloquent-factories.md +4 -3
  31. package/docs/eloquent-mutators.md +2 -1
  32. package/docs/eloquent-relationships.md +28 -3
  33. package/docs/eloquent-resources.md +253 -0
  34. package/docs/eloquent.md +41 -0
  35. package/docs/errors.md +12 -3
  36. package/docs/events.md +3 -1
  37. package/docs/facades.md +1 -0
  38. package/docs/helpers.md +33 -2
  39. package/docs/inertia.md +11 -2
  40. package/docs/installation.md +4 -2
  41. package/docs/laravel.md +71 -0
  42. package/docs/lifecycle.md +5 -2
  43. package/docs/live.md +88 -8
  44. package/docs/mail.md +28 -3
  45. package/docs/middleware.md +20 -12
  46. package/docs/navigation.json +8 -0
  47. package/docs/notifications.md +22 -0
  48. package/docs/pagination.md +4 -0
  49. package/docs/passwords.md +4 -6
  50. package/docs/providers.md +3 -5
  51. package/docs/queues.md +64 -2
  52. package/docs/requests.md +42 -3
  53. package/docs/responses.md +7 -4
  54. package/docs/routing.md +85 -7
  55. package/docs/scheduling.md +25 -0
  56. package/docs/session.md +2 -2
  57. package/docs/starter-kits.md +26 -7
  58. package/docs/storage.md +10 -4
  59. package/docs/testing.md +10 -2
  60. package/docs/two-factor.md +34 -1
  61. package/docs/upgrade.md +111 -2
  62. package/docs/validation.md +70 -9
  63. package/docs/views.md +1 -0
  64. package/docs/vite.md +2 -1
  65. package/package.json +43 -35
  66. package/dist/chunk-7GPMFMS7.js.map +0 -1
  67. package/dist/chunk-BKA5F3TH.js.map +0 -1
  68. package/dist/chunk-FVI6X3VJ.js.map +0 -1
package/dist/index.js CHANGED
@@ -22,14 +22,13 @@ import {
22
22
  renderToString,
23
23
  styleString,
24
24
  view
25
- } from "./chunk-GCMPAXIK.js";
25
+ } from "./chunk-3QHTNAMZ.js";
26
26
  import {
27
- API_ROUTES_STUB,
27
+ AnonymousResourceCollection,
28
28
  Application as Application2,
29
29
  ApplicationBuilder,
30
30
  BusFake,
31
31
  ClassNameMap,
32
- ClosureKernel,
33
32
  Component,
34
33
  Computed,
35
34
  Config,
@@ -42,6 +41,7 @@ import {
42
41
  ExportError,
43
42
  FileNotPreviewableError,
44
43
  FormUploadedFile,
44
+ HandleCors,
45
45
  HttpException,
46
46
  HttpRedirectResponse,
47
47
  HttpRedirector,
@@ -52,6 +52,7 @@ import {
52
52
  IncomingRequest,
53
53
  InvalidLiveRequestError,
54
54
  InvalidUploadSignatureError,
55
+ JsonResource,
55
56
  Kernel,
56
57
  Live,
57
58
  LiveComponentManager,
@@ -62,18 +63,22 @@ import {
62
63
  MailFake,
63
64
  MethodNotCallableError,
64
65
  MiddlewareConfiguration,
66
+ MissingValue,
65
67
  NotificationFake,
66
68
  On,
67
69
  PERSISTENT_MIDDLEWARE,
68
70
  PREVIEW_URI,
69
71
  Pagination,
70
72
  PendingEvent,
73
+ PreventRequestsDuringMaintenance,
71
74
  PropertyNotUpdatableError,
72
75
  ProviderBootError,
73
76
  ProviderRegisterError,
74
77
  QueueFake,
75
78
  RenameClasses,
76
79
  Repository,
80
+ ResourceCollection,
81
+ ResourceResponse,
77
82
  SESSION_URI,
78
83
  StorageFake,
79
84
  TEMPORARY_UPLOAD_DEFAULTS,
@@ -82,6 +87,7 @@ import {
82
87
  TestRequestScope,
83
88
  Testable,
84
89
  TrimStrings,
90
+ TrustHosts,
85
91
  UPDATE_URI,
86
92
  UPLOAD_URI,
87
93
  UploadAlreadyStoredError,
@@ -94,63 +100,27 @@ import {
94
100
  abort,
95
101
  abortIf,
96
102
  abortUnless,
97
- addApiRouting,
98
- applyExceptionCallbacks,
99
- applyMiddlewareCallbacks,
100
103
  back,
101
- bunRuntime,
102
- clientAddress,
103
104
  componentFiles,
104
105
  componentName,
105
106
  contentDisposition,
106
- currentRequest,
107
107
  currentVite,
108
- debugPage,
109
108
  describeComponent,
110
- detectRuntime,
111
109
  env,
112
- escapeHtml,
113
- exceedsJsonDepth,
114
110
  exportSite,
115
- extensionFromMime,
116
- filterRouteList,
117
- formatRouteList,
118
- fromEntries,
119
- ipMatches,
120
- isBlank,
121
111
  live,
122
- mergeRecursive,
123
- minimalPage,
124
112
  nodeRequestHandler,
125
- normalizeLists,
126
- optionalCookieJar,
127
- optionalSession,
128
- parseBracketKey,
129
113
  persistentMiddleware,
130
114
  redirect,
131
- registerHttpCommands,
132
115
  request,
133
- requestScope,
134
116
  response,
135
117
  route,
136
118
  routeListRows,
137
- sanitize,
138
119
  serve,
139
- serveBun,
140
- serveNode,
141
- servePublicFile,
142
- setClientAddress,
143
- stackFrames,
144
- statusFor,
145
- statusText,
146
- summarizeValidation,
147
- toWebRequest,
148
- transformLeaves,
149
120
  url,
150
121
  vite,
151
- viteReactRefresh,
152
- writeResponse
153
- } from "./chunk-7GPMFMS7.js";
122
+ viteReactRefresh
123
+ } from "./chunk-MG4YEWMV.js";
154
124
  import {
155
125
  Arr,
156
126
  BindingResolutionError,
@@ -166,6 +136,7 @@ import {
166
136
  ServiceProvider,
167
137
  Str,
168
138
  Stringable,
139
+ ValidatedInput,
169
140
  __,
170
141
  app,
171
142
  collect,
@@ -177,10 +148,13 @@ import {
177
148
  inject,
178
149
  isPublicAsset,
179
150
  now,
151
+ report,
152
+ rescue,
180
153
  retry,
154
+ serializeDate,
181
155
  tap,
182
156
  value
183
- } from "./chunk-FVI6X3VJ.js";
157
+ } from "./chunk-YNDMTTWL.js";
184
158
  import {
185
159
  Application,
186
160
  AuthFactory,
@@ -219,10 +193,11 @@ import {
219
193
  Schedule,
220
194
  Session,
221
195
  UrlGenerator,
196
+ VALIDATED_INPUT,
222
197
  ValidationFactory,
223
198
  ViewFactory,
224
199
  token
225
- } from "./chunk-BKA5F3TH.js";
200
+ } from "./chunk-6AXJB4CD.js";
226
201
 
227
202
  // ../Auth/dist/index.js
228
203
  import { createHash } from "crypto";
@@ -506,6 +481,7 @@ function AuthenticatableModel(Base) {
506
481
  getAuthIdentifierName() {
507
482
  return this.getKeyName();
508
483
  }
484
+ /** The model's key, typed as the model's getKey() is. */
509
485
  getAuthIdentifier() {
510
486
  return this.getKey();
511
487
  }
@@ -1845,6 +1821,26 @@ var EnsureEmailIsVerified = class {
1845
1821
  return "/email/verify";
1846
1822
  }
1847
1823
  };
1824
+ var RequirePassword = class {
1825
+ #container = inject(Container);
1826
+ async handle(request2, next, redirectToRoute, passwordTimeoutSeconds) {
1827
+ if (this.#confirmed(passwordTimeoutSeconds)) return next(request2);
1828
+ if (request2.expectsJson()) return Response.json({ message: "Password confirmation required." }, { status: 423 });
1829
+ return redirectTo(this.#container, request2, this.#confirmUrl(redirectToRoute || "password.confirm"), true);
1830
+ }
1831
+ #confirmed(passwordTimeoutSeconds) {
1832
+ const confirmedAt = Number(this.#container.make(Session).get("auth.password_confirmed_at", 0));
1833
+ const timeout = Number(passwordTimeoutSeconds || this.#container.make(ConfigRepository).get("auth.password_timeout", 10800));
1834
+ return Math.floor(Date.now() / 1e3) - confirmedAt <= timeout;
1835
+ }
1836
+ #confirmUrl(route2) {
1837
+ if (this.#container.bound(UrlGenerator)) {
1838
+ const url2 = this.#container.make(UrlGenerator);
1839
+ if (url2.hasRoute(route2)) return url2.route(route2);
1840
+ }
1841
+ return "/confirm-password";
1842
+ }
1843
+ };
1848
1844
  var POLICY_FILE = /^([A-Za-z0-9_]+)Policy\.(ts|mts|js|mjs)$/;
1849
1845
  async function discoverPolicies(directory, gate) {
1850
1846
  const files3 = await readdir(directory).catch(() => []);
@@ -2210,6 +2206,19 @@ var TwoFactorManager = class {
2210
2206
  if (this.#store().hasApp(user)) throw new TwoFactorAppAlreadyEnabledError();
2211
2207
  const secret = generateSecret();
2212
2208
  await this.#store().setSecret(user, secret);
2209
+ return this.#setup(user, secret);
2210
+ }
2211
+ /**
2212
+ * An app being set up (enableApp() called, not yet confirmed): its secret, URL and QR code again, so a page can show
2213
+ * them after a reload or a wrong code. Undefined before enableApp() and once the app is confirmed.
2214
+ */
2215
+ async appSetup(user) {
2216
+ const store = this.#store();
2217
+ const secret = store.secret(user);
2218
+ if (secret === void 0 || store.confirmedAt(user) !== void 0) return void 0;
2219
+ return this.#setup(user, secret);
2220
+ }
2221
+ #setup(user, secret) {
2213
2222
  const issuer = this.#config().issuer ?? inject(ConfigRepository).get("app.name", "Oriel");
2214
2223
  const url2 = otpauthUrl({ secret, issuer, account: String(user.getAttribute("email") ?? user.getAuthIdentifier()) });
2215
2224
  return { secret, url: url2, svg: qrSvg(url2) };
@@ -2365,7 +2374,7 @@ var AuthServiceProvider = class extends ServiceProvider {
2365
2374
  }
2366
2375
  async boot() {
2367
2376
  if (this.app.bound(Router)) {
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);
2377
+ this.app.make(Router).aliasMiddleware("auth", Authenticate).aliasMiddleware("auth.session", AuthenticateSession).aliasMiddleware("guest", RedirectIfAuthenticated).aliasMiddleware("can", Authorize).aliasMiddleware("verified", EnsureEmailIsVerified).aliasMiddleware("password.confirm", RequirePassword).aliasMiddleware("two-factor.challenge", TwoFactorChallenge);
2369
2378
  }
2370
2379
  if (this.app.bound(EventDispatcher)) {
2371
2380
  const events = this.app.make(EventDispatcher);
@@ -2711,6 +2720,17 @@ var PendingDispatch = class {
2711
2720
  chain(jobs) {
2712
2721
  return this.set(() => this.chained = [...this.chained, ...jobs]);
2713
2722
  }
2723
+ /**
2724
+ * Inside a database transaction, push it only once the transaction commits (dropped if it rolls back), whatever the
2725
+ * connection's `after_commit` says.
2726
+ */
2727
+ afterCommit() {
2728
+ return this.set(() => this.job && (this.job.afterCommit = true));
2729
+ }
2730
+ /** Push it at once, even inside a transaction on an `after_commit` connection. */
2731
+ beforeCommit() {
2732
+ return this.set(() => this.job && (this.job.afterCommit = false));
2733
+ }
2714
2734
  /** Run it after the response is sent instead (sync). */
2715
2735
  afterResponse() {
2716
2736
  return this.set(() => this.deferred = true);
@@ -2835,7 +2855,6 @@ import { link, mkdir, readFile, rename, rm, stat, writeFile } from "fs/promises"
2835
2855
  import { dirname, join as join3 } from "path";
2836
2856
  import { setTimeout as sleep2 } from "timers/promises";
2837
2857
  import { createHash as createHash22, randomUUID } from "crypto";
2838
- import Redis from "ioredis";
2839
2858
  import { setTimeout as sleep3 } from "timers/promises";
2840
2859
  var LockTimeoutError = class extends Error {
2841
2860
  constructor(lockName) {
@@ -3467,24 +3486,48 @@ export default class extends Migration {
3467
3486
  }
3468
3487
  }
3469
3488
  `;
3470
- function makeRedisClient(config2) {
3489
+ async function makeRedisClient(config2) {
3471
3490
  if (typeof config2.client === "object" && config2.client !== null) return config2.client;
3491
+ const { Redis } = await importOptional("ioredis", "The redis cache store", () => import("ioredis"));
3472
3492
  const { client: _client, url: url2, driver: _driver, prefix: _prefix, connection: _connection, ...options } = config2;
3473
3493
  if (typeof url2 === "string") return new Redis(url2, options);
3474
3494
  return new Redis(options);
3475
3495
  }
3496
+ var RedisConnection = class {
3497
+ constructor(source) {
3498
+ this.source = source;
3499
+ if (typeof source !== "function") this.#client = Promise.resolve(source);
3500
+ }
3501
+ source;
3502
+ #client;
3503
+ client() {
3504
+ return this.#client ??= this.source();
3505
+ }
3506
+ /** Whether there's a client: one given, or one made for a command. A store that has neither has nothing to close. */
3507
+ started() {
3508
+ return this.#client !== void 0;
3509
+ }
3510
+ };
3511
+ var connectionOf = (redis) => redis instanceof RedisConnection ? redis : new RedisConnection(redis);
3476
3512
  var RedisPrimitives = class {
3513
+ connection;
3477
3514
  constructor(redis) {
3478
- this.redis = redis;
3515
+ this.connection = connectionOf(redis);
3516
+ }
3517
+ /** The client, made at the first command. */
3518
+ redis() {
3519
+ return this.connection.client();
3520
+ }
3521
+ getConnection() {
3522
+ return this.connection;
3479
3523
  }
3480
- redis;
3481
3524
  async rawGet(key) {
3482
- const raw3 = await this.redis.get(key);
3525
+ const raw3 = await (await this.redis()).get(key);
3483
3526
  return raw3 === null ? void 0 : deserialize(raw3);
3484
3527
  }
3485
3528
  async rawMany(keys) {
3486
3529
  if (keys.length === 0) return {};
3487
- const values = await this.redis.mget(...keys);
3530
+ const values = await (await this.redis()).mget(...keys);
3488
3531
  const result = {};
3489
3532
  keys.forEach((key, i) => {
3490
3533
  const raw3 = values[i];
@@ -3493,19 +3536,21 @@ var RedisPrimitives = class {
3493
3536
  return result;
3494
3537
  }
3495
3538
  async rawPut(key, value2, ms) {
3496
- if (ms === void 0) await this.redis.set(key, serialize(roundTrip(value2)));
3497
- else await this.redis.set(key, serialize(roundTrip(value2)), "PX", Math.max(1, Math.round(ms)));
3539
+ const redis = await this.redis();
3540
+ if (ms === void 0) await redis.set(key, serialize(roundTrip(value2)));
3541
+ else await redis.set(key, serialize(roundTrip(value2)), "PX", Math.max(1, Math.round(ms)));
3498
3542
  return true;
3499
3543
  }
3500
3544
  async rawAdd(key, value2, ms) {
3501
- const result = ms === void 0 ? await this.redis.set(key, serialize(roundTrip(value2)), "NX") : await this.redis.set(key, serialize(roundTrip(value2)), "PX", Math.max(1, Math.round(ms)), "NX");
3545
+ const redis = await this.redis();
3546
+ const result = ms === void 0 ? await redis.set(key, serialize(roundTrip(value2)), "NX") : await redis.set(key, serialize(roundTrip(value2)), "PX", Math.max(1, Math.round(ms)), "NX");
3502
3547
  return result === "OK";
3503
3548
  }
3504
- rawIncrement(key, by) {
3505
- return this.redis.incrby(key, by);
3549
+ async rawIncrement(key, by) {
3550
+ return (await this.redis()).incrby(key, by);
3506
3551
  }
3507
3552
  async rawForget(key) {
3508
- return await this.redis.del(key) > 0;
3553
+ return await (await this.redis()).del(key) > 0;
3509
3554
  }
3510
3555
  };
3511
3556
  var RedisStore = class extends RedisPrimitives {
@@ -3552,16 +3597,17 @@ var RedisStore = class extends RedisPrimitives {
3552
3597
  return this.rawForget(this.k(key));
3553
3598
  }
3554
3599
  async flush() {
3600
+ const redis = await this.redis();
3555
3601
  let cursor = "0";
3556
3602
  do {
3557
- const [next, keys] = await this.redis.scan(cursor, "MATCH", `${this.keyPrefix}*`, "COUNT", 200);
3603
+ const [next, keys] = await redis.scan(cursor, "MATCH", `${this.keyPrefix}*`, "COUNT", 200);
3558
3604
  cursor = next;
3559
- if (keys.length > 0) await this.redis.unlink(...keys);
3605
+ if (keys.length > 0) await redis.unlink(...keys);
3560
3606
  } while (cursor !== "0");
3561
3607
  return true;
3562
3608
  }
3563
3609
  tags(names) {
3564
- return new RedisTaggedStore(this.redis, this.keyPrefix, names);
3610
+ return new RedisTaggedStore(this.connection, this.keyPrefix, names);
3565
3611
  }
3566
3612
  };
3567
3613
  var RedisTaggedStore = class extends RedisPrimitives {
@@ -3574,11 +3620,12 @@ var RedisTaggedStore = class extends RedisPrimitives {
3574
3620
  tagNames;
3575
3621
  async tagVersion(name) {
3576
3622
  const key = `${this.keyPrefix}tag:${name}:version`;
3577
- const existing = await this.redis.get(key);
3623
+ const redis = await this.redis();
3624
+ const existing = await redis.get(key);
3578
3625
  if (existing !== null) return existing;
3579
3626
  const version = randomUUID();
3580
- const set = await this.redis.set(key, version, "NX");
3581
- return set === "OK" ? version : await this.redis.get(key) ?? version;
3627
+ const set = await redis.set(key, version, "NX");
3628
+ return set === "OK" ? version : await redis.get(key) ?? version;
3582
3629
  }
3583
3630
  async namespace() {
3584
3631
  const versions = await Promise.all(this.tagNames.map((name) => this.tagVersion(name)));
@@ -3620,24 +3667,26 @@ var RedisTaggedStore = class extends RedisPrimitives {
3620
3667
  return this.rawForget(await this.k(key));
3621
3668
  }
3622
3669
  async flush() {
3623
- await Promise.all(this.tagNames.map((name) => this.redis.set(`${this.keyPrefix}tag:${name}:version`, randomUUID())));
3670
+ const redis = await this.redis();
3671
+ await Promise.all(this.tagNames.map((name) => redis.set(`${this.keyPrefix}tag:${name}:version`, randomUUID())));
3624
3672
  return true;
3625
3673
  }
3626
3674
  };
3627
3675
  var RELEASE_SCRIPT = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
3628
3676
  var RedisLock = class {
3677
+ /** `redis` is a client, or a store's connection (whose client is made at first use). */
3629
3678
  constructor(redis, name, seconds, owner, pollMs = 50) {
3630
- this.redis = redis;
3631
3679
  this.name = name;
3632
3680
  this.seconds = seconds;
3633
3681
  this.pollMs = pollMs;
3634
3682
  this.ownerValue = owner ?? Str.random(20);
3683
+ this.connection = redis instanceof RedisConnection ? redis : new RedisConnection(redis);
3635
3684
  }
3636
- redis;
3637
3685
  name;
3638
3686
  seconds;
3639
3687
  pollMs;
3640
3688
  ownerValue;
3689
+ connection;
3641
3690
  owner() {
3642
3691
  return this.ownerValue;
3643
3692
  }
@@ -3666,34 +3715,37 @@ var RedisLock = class {
3666
3715
  }
3667
3716
  }
3668
3717
  async release() {
3669
- const result = await this.redis.eval(RELEASE_SCRIPT, 1, this.name, this.ownerValue);
3718
+ const result = await (await this.connection.client()).eval(RELEASE_SCRIPT, 1, this.name, this.ownerValue);
3670
3719
  return result === 1;
3671
3720
  }
3672
3721
  async forceRelease() {
3673
- await this.redis.del(this.name);
3722
+ await (await this.connection.client()).del(this.name);
3674
3723
  }
3675
3724
  async acquire() {
3676
- const result = this.seconds === void 0 ? await this.redis.set(this.name, this.ownerValue, "NX") : await this.redis.set(this.name, this.ownerValue, "PX", Math.max(1, Math.round(this.seconds * 1e3)), "NX");
3725
+ const redis = await this.connection.client();
3726
+ const result = this.seconds === void 0 ? await redis.set(this.name, this.ownerValue, "NX") : await redis.set(this.name, this.ownerValue, "PX", Math.max(1, Math.round(this.seconds * 1e3)), "NX");
3677
3727
  return result === "OK";
3678
3728
  }
3679
3729
  };
3680
3730
  var quitting = /* @__PURE__ */ new WeakMap();
3681
3731
  var RedisRepository = class extends Repository2 {
3682
- constructor(redisStore, redis) {
3683
- super(redisStore, (_store, name, seconds, owner) => new RedisLock(redis, redisStore.getPrefix() + name, seconds, owner));
3732
+ constructor(redisStore) {
3733
+ super(redisStore, (_store, name, seconds, owner) => new RedisLock(redisStore.getConnection(), redisStore.getPrefix() + name, seconds, owner));
3684
3734
  this.redisStore = redisStore;
3685
- this.redis = redis;
3686
3735
  }
3687
3736
  redisStore;
3688
- redis;
3689
3737
  /**
3690
3738
  * Closes the redis client (CacheManager.disconnectAll() at shutdown): a connected one with QUIT, one that never
3691
3739
  * connected or is reconnecting without waiting; one already closed is left alone. A client two stores share is quit
3692
3740
  * once: QUIT resolves on the server's reply, but the client reads 'ready' until its socket closes, so the second
3693
3741
  * store waits on the first one's QUIT instead of sending another (which would fail with "Connection is closed.").
3742
+ * A store that never made its client has nothing to close.
3694
3743
  */
3695
3744
  async disconnect() {
3696
- const redis = this.redis;
3745
+ const connection = this.redisStore.getConnection();
3746
+ if (!connection.started()) return;
3747
+ const redis = await connection.client().catch(() => void 0);
3748
+ if (redis === void 0) return;
3697
3749
  const pending = quitting.get(redis);
3698
3750
  if (pending) return pending;
3699
3751
  if (redis.status === "end") return;
@@ -3707,7 +3759,7 @@ var RedisRepository = class extends Repository2 {
3707
3759
  const list5 = Array.isArray(names) ? names : [names];
3708
3760
  const taggedStore = this.redisStore.tags(list5);
3709
3761
  const prefix = this.redisStore.getPrefix();
3710
- return new Repository2(taggedStore, (_store, name, seconds, owner) => new RedisLock(this.redis, prefix + name, seconds, owner));
3762
+ return new Repository2(taggedStore, (_store, name, seconds, owner) => new RedisLock(this.redisStore.getConnection(), prefix + name, seconds, owner));
3711
3763
  }
3712
3764
  };
3713
3765
  function resolveRedisConfig(cfg, lookupDatabaseRedis) {
@@ -3747,22 +3799,22 @@ var CacheManager2 = class {
3747
3799
  cfg,
3748
3800
  (connectionName) => this.container.make(ConfigRepository).get(`database.redis.${connectionName}`, {})
3749
3801
  );
3750
- const redis = makeRedisClient(resolved);
3751
- const store = new RedisStore(redis, this.str(cfg.prefix));
3752
- return new RedisRepository(store, redis);
3802
+ const client = typeof resolved.client === "object" && resolved.client !== null ? resolved.client : void 0;
3803
+ const store = new RedisStore(client ?? (() => makeRedisClient(resolved)), this.str(cfg.prefix));
3804
+ return new RedisRepository(store);
3753
3805
  }
3754
3806
  store(name) {
3755
3807
  const cacheConfig = this.cacheConfig();
3756
- const storeName = name ?? cacheConfig.default;
3757
- let repository = this.stores.get(storeName);
3808
+ const storeName2 = name ?? cacheConfig.default;
3809
+ let repository = this.stores.get(storeName2);
3758
3810
  if (!repository) {
3759
- const storeConfig = cacheConfig.stores[storeName];
3760
- if (!storeConfig) throw new UnknownCacheStoreError(storeName);
3811
+ const storeConfig = cacheConfig.stores[storeName2];
3812
+ if (!storeConfig) throw new UnknownCacheStoreError(storeName2);
3761
3813
  const driverName = storeConfig.driver;
3762
3814
  const driver = driverName ? this.drivers.get(driverName) : void 0;
3763
3815
  if (!driver) throw new UnknownCacheDriverError(String(driverName));
3764
3816
  repository = driver({ ...storeConfig, prefix: storeConfig.prefix ?? cacheConfig.prefix ?? "" });
3765
- this.stores.set(storeName, repository);
3817
+ this.stores.set(storeName2, repository);
3766
3818
  }
3767
3819
  return repository;
3768
3820
  }
@@ -3839,6 +3891,21 @@ var CacheRateLimiter = class {
3839
3891
  this.store = store;
3840
3892
  }
3841
3893
  store;
3894
+ #limiters = /* @__PURE__ */ new Map();
3895
+ /** Laravel's RateLimiter::for(): names a limiter that `throttle:<name>` uses. */
3896
+ for(name, callback) {
3897
+ this.#limiters.set(name, callback);
3898
+ }
3899
+ limiter(name) {
3900
+ return this.#limiters.get(name);
3901
+ }
3902
+ /** Laravel's attempt(): false when `key` is out of attempts; else the callback's result (true for nothing), and a hit. */
3903
+ async attempt(key, maxAttempts, callback, decaySeconds = 60) {
3904
+ if (await this.tooManyAttempts(key, maxAttempts)) return false;
3905
+ const result = await callback();
3906
+ await this.hit(key, decaySeconds);
3907
+ return result === void 0 || result === null ? true : result;
3908
+ }
3842
3909
  async tooManyAttempts(key, maxAttempts) {
3843
3910
  const clean = this.cleanKey(key);
3844
3911
  if (await this.#attempts(clean) >= maxAttempts) {
@@ -3879,6 +3946,41 @@ var CacheRateLimiter = class {
3879
3946
  return Number(await this.store().get(clean) ?? 0);
3880
3947
  }
3881
3948
  };
3949
+ var Limit = class _Limit {
3950
+ constructor(maxAttempts, decaySeconds, unlimited = false) {
3951
+ this.maxAttempts = maxAttempts;
3952
+ this.decaySeconds = decaySeconds;
3953
+ this.unlimited = unlimited;
3954
+ }
3955
+ maxAttempts;
3956
+ decaySeconds;
3957
+ unlimited;
3958
+ key = "";
3959
+ static perSecond(maxAttempts, decaySeconds = 1) {
3960
+ return new _Limit(maxAttempts, decaySeconds);
3961
+ }
3962
+ static perMinute(maxAttempts, decayMinutes = 1) {
3963
+ return new _Limit(maxAttempts, 60 * decayMinutes);
3964
+ }
3965
+ static perMinutes(decayMinutes, maxAttempts) {
3966
+ return new _Limit(maxAttempts, 60 * decayMinutes);
3967
+ }
3968
+ static perHour(maxAttempts, decayHours = 1) {
3969
+ return new _Limit(maxAttempts, 3600 * decayHours);
3970
+ }
3971
+ static perDay(maxAttempts, decayDays = 1) {
3972
+ return new _Limit(maxAttempts, 86400 * decayDays);
3973
+ }
3974
+ /** Laravel's Limit::none(): no limit, and no rate limit headers. */
3975
+ static none() {
3976
+ return new _Limit(Number.MAX_SAFE_INTEGER, 60, true);
3977
+ }
3978
+ /** The key the hits are counted under, such as the user's id or the IP address. */
3979
+ by(key) {
3980
+ this.key = String(key);
3981
+ return this;
3982
+ }
3983
+ };
3882
3984
  var Cache = facade(CacheManager);
3883
3985
  var RateLimiter2 = facade(RateLimiter);
3884
3986
  function cache(arg, ttlSeconds) {
@@ -3889,6 +3991,41 @@ function cache(arg, ttlSeconds) {
3889
3991
  (results) => results.every(Boolean)
3890
3992
  );
3891
3993
  }
3994
+ var storeName = (command) => {
3995
+ const given = command.argument("store");
3996
+ return typeof given === "string" && given !== "" ? given : void 0;
3997
+ };
3998
+ function registerCacheCommands(kernel, app2) {
3999
+ kernel.command("cache:clear {store? : The name of the store you would like to clear}", async function() {
4000
+ let flushed;
4001
+ try {
4002
+ flushed = await app2.make(CacheManager).store(storeName(this)).flush();
4003
+ } catch (error) {
4004
+ this.error(error instanceof Error ? error.message : String(error));
4005
+ return 1;
4006
+ }
4007
+ if (!flushed) {
4008
+ this.error("Failed to clear cache. Make sure you have the appropriate permissions.");
4009
+ return 1;
4010
+ }
4011
+ this.info("Application cache cleared successfully.");
4012
+ return 0;
4013
+ }).purpose("Flush the application cache");
4014
+ kernel.command(
4015
+ "cache:forget {key : The key to remove} {store? : The store to remove the key from}",
4016
+ async function() {
4017
+ const key = String(this.argument("key"));
4018
+ try {
4019
+ await app2.make(CacheManager).store(storeName(this)).forget(key);
4020
+ } catch (error) {
4021
+ this.error(error instanceof Error ? error.message : String(error));
4022
+ return 1;
4023
+ }
4024
+ this.info(`The [${key}] key has been removed from the cache.`);
4025
+ return 0;
4026
+ }
4027
+ ).purpose("Remove an item from the cache");
4028
+ }
3892
4029
  var CacheServiceProvider = class extends ServiceProvider {
3893
4030
  register() {
3894
4031
  this.mergeConfigFrom(
@@ -3919,6 +4056,9 @@ var CacheServiceProvider = class extends ServiceProvider {
3919
4056
  });
3920
4057
  });
3921
4058
  }
4059
+ boot() {
4060
+ if (this.app.bound(ConsoleKernel)) registerCacheCommands(this.app.make(ConsoleKernel), this.app);
4061
+ }
3922
4062
  };
3923
4063
 
3924
4064
  // ../Console/dist/index.js
@@ -3931,10 +4071,13 @@ import { join as join22 } from "path";
3931
4071
  import { existsSync as existsSync3 } from "fs";
3932
4072
  import { mkdir as mkdir22, writeFile as writeFile22 } from "fs/promises";
3933
4073
  import { dirname as dirname22, join as join32 } from "path";
4074
+ import { existsSync as existsSync4 } from "fs";
4075
+ import { readFile as readFile2, writeFile as writeFile3 } from "fs/promises";
4076
+ import { dirname as dirname3, relative as relative22, sep as sep2 } from "path";
3934
4077
  import { join as join42 } from "path";
3935
4078
  import { spawn } from "child_process";
3936
4079
  import { start as start2 } from "repl";
3937
- import { existsSync as existsSync4, readdirSync as readdirSync2 } from "fs";
4080
+ import { existsSync as existsSync5, readdirSync as readdirSync2 } from "fs";
3938
4081
  import { join as join5 } from "path";
3939
4082
  import { pathToFileURL as pathToFileURL2 } from "url";
3940
4083
  import { createHash as createHash6 } from "crypto";
@@ -3942,6 +4085,14 @@ import { CronExpressionParser } from "cron-parser";
3942
4085
  var InvalidSignatureError = class extends Error {
3943
4086
  name = "InvalidSignatureError";
3944
4087
  };
4088
+ var InputRequiredError = class extends Error {
4089
+ constructor(question) {
4090
+ super(`The "${question}" question needs an answer, which --no-interaction can't give.`);
4091
+ this.question = question;
4092
+ }
4093
+ question;
4094
+ name = "InputRequiredError";
4095
+ };
3945
4096
  var CommandNotFoundError = class extends Error {
3946
4097
  constructor(message, suggestions = []) {
3947
4098
  super(message);
@@ -4086,12 +4237,26 @@ var Command = class {
4086
4237
  boundOptions = {};
4087
4238
  consoleOutput = new NodeConsoleOutput();
4088
4239
  consoleInput = new NodeConsoleInput();
4240
+ interactive = true;
4241
+ level = 0;
4242
+ /** @internal Read by the kernel: options this command doesn't declare become arguments (ignoreValidationErrors()). */
4243
+ ignoresValidationErrors = false;
4244
+ /** Laravel's ignoreValidationErrors(): options the signature doesn't declare reach the command as arguments. */
4245
+ ignoreValidationErrors() {
4246
+ this.ignoresValidationErrors = true;
4247
+ }
4089
4248
  /** @internal Set by the kernel before handle() runs. */
4090
4249
  bind(args, options, io) {
4091
4250
  this.boundArguments = args;
4092
4251
  this.boundOptions = options;
4093
4252
  this.consoleInput = io.input;
4094
4253
  this.consoleOutput = io.output;
4254
+ this.interactive = io.interactive ?? true;
4255
+ this.level = io.verbosity ?? 0;
4256
+ }
4257
+ /** -1 with -q/--quiet, 1, 2 or 3 with -v, -vv or -vvv, else 0 (Laravel's getOutput()->getVerbosity(), as a number). */
4258
+ verbosity() {
4259
+ return this.level;
4095
4260
  }
4096
4261
  argument(name) {
4097
4262
  return this.boundArguments[name];
@@ -4107,19 +4272,19 @@ var Command = class {
4107
4272
  return { ...this.boundOptions };
4108
4273
  }
4109
4274
  info(message) {
4110
- this.consoleOutput.write(`${message}
4275
+ if (this.level >= 0) this.consoleOutput.write(`${message}
4111
4276
  `);
4112
4277
  }
4113
4278
  line(message = "") {
4114
- this.consoleOutput.write(`${message}
4279
+ if (this.level >= 0) this.consoleOutput.write(`${message}
4115
4280
  `);
4116
4281
  }
4117
4282
  comment(message) {
4118
- this.consoleOutput.write(`${message}
4283
+ if (this.level >= 0) this.consoleOutput.write(`${message}
4119
4284
  `);
4120
4285
  }
4121
4286
  warn(message) {
4122
- this.consoleOutput.writeError(`${message}
4287
+ if (this.level >= 0) this.consoleOutput.writeError(`${message}
4123
4288
  `);
4124
4289
  }
4125
4290
  error(message) {
@@ -4127,7 +4292,7 @@ var Command = class {
4127
4292
  `);
4128
4293
  }
4129
4294
  newLine(count = 1) {
4130
- this.consoleOutput.write("\n".repeat(count));
4295
+ if (this.level >= 0) this.consoleOutput.write("\n".repeat(count));
4131
4296
  }
4132
4297
  table(headers, rows) {
4133
4298
  const widths = headers.map((header, i) => Math.max(header.length, ...rows.map((row) => (row[i] ?? "").length)));
@@ -4140,21 +4305,29 @@ var Command = class {
4140
4305
  this.line(border);
4141
4306
  }
4142
4307
  async ask(question, defaultValue) {
4308
+ if (!this.interactive) return defaultValue ?? "";
4143
4309
  const suffix2 = defaultValue !== void 0 ? ` (${defaultValue})` : "";
4144
4310
  const answer = (await this.consoleInput.question(`${question}${suffix2}: `)).trim();
4145
4311
  return answer === "" && defaultValue !== void 0 ? defaultValue : answer;
4146
4312
  }
4147
4313
  /** 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. */
4148
4314
  async secret(question) {
4315
+ if (!this.interactive) throw new InputRequiredError(question);
4149
4316
  return this.consoleInput.question(`${question}: `, { hidden: true });
4150
4317
  }
4151
4318
  async confirm(question, defaultValue = false) {
4319
+ if (!this.interactive) return defaultValue;
4152
4320
  const hint = defaultValue ? "Y/n" : "y/N";
4153
4321
  const answer = (await this.consoleInput.question(`${question} (${hint}): `)).trim().toLowerCase();
4154
4322
  if (answer === "") return defaultValue;
4155
4323
  return answer === "y" || answer === "yes";
4156
4324
  }
4157
4325
  async choice(question, choices, defaultIndex) {
4326
+ if (!this.interactive) {
4327
+ const fallback = defaultIndex !== void 0 ? choices[defaultIndex] : void 0;
4328
+ if (fallback === void 0) throw new InputRequiredError(question);
4329
+ return fallback;
4330
+ }
4158
4331
  this.line(question);
4159
4332
  choices.forEach((choice, i) => this.line(` [${i}] ${choice}`));
4160
4333
  const defaultValue = defaultIndex !== void 0 ? choices[defaultIndex] : void 0;
@@ -4172,7 +4345,12 @@ var Command = class {
4172
4345
  const kernel = inject(ConsoleKernel);
4173
4346
  if (!(command in kernel.all())) return void 0;
4174
4347
  if (kernel.callWithIo)
4175
- return kernel.callWithIo(command, parameters, { input: this.consoleInput, output: this.consoleOutput });
4348
+ return kernel.callWithIo(command, parameters, {
4349
+ input: this.consoleInput,
4350
+ output: this.consoleOutput,
4351
+ interactive: this.interactive,
4352
+ verbosity: this.level
4353
+ });
4176
4354
  return kernel.call(command, parameters);
4177
4355
  }
4178
4356
  };
@@ -4241,13 +4419,13 @@ function parseSignature(signature) {
4241
4419
  }
4242
4420
  return { name, arguments: args, options };
4243
4421
  }
4244
- function applyOption(options, def, inline, next) {
4422
+ function applyOption(options, def, inline2, next) {
4245
4423
  if (def.mode === "flag") {
4246
4424
  options[def.name] = true;
4247
4425
  return 0;
4248
4426
  }
4249
- const takesNext = inline === void 0 && next !== void 0 && !next.startsWith("-");
4250
- const value2 = takesNext ? next : inline;
4427
+ const takesNext = inline2 === void 0 && next !== void 0 && !next.startsWith("-");
4428
+ const value2 = takesNext ? next : inline2;
4251
4429
  if (value2 === void 0) return 0;
4252
4430
  if (def.mode === "array") {
4253
4431
  const existing = options[def.name];
@@ -4270,12 +4448,12 @@ function applyShortcutToken(options, token2, next, shortcuts, byName2) {
4270
4448
  continue;
4271
4449
  }
4272
4450
  const rest = token2.slice(pos + 1);
4273
- const inline = rest === "" ? void 0 : rest.replace(/^=/, "");
4274
- return applyOption(options, def, inline, next);
4451
+ const inline2 = rest === "" ? void 0 : rest.replace(/^=/, "");
4452
+ return applyOption(options, def, inline2, next);
4275
4453
  }
4276
4454
  return 0;
4277
4455
  }
4278
- function parseArgv(argv, signature) {
4456
+ function parseArgv(argv, signature, parse3 = {}) {
4279
4457
  const shortcuts = new Map(signature.options.filter((o) => o.shortcut).map((o) => [o.shortcut, o.name]));
4280
4458
  const byName2 = new Map(signature.options.map((o) => [o.name, o]));
4281
4459
  const options = {};
@@ -4289,10 +4467,16 @@ function parseArgv(argv, signature) {
4289
4467
  if (token2.startsWith("--")) {
4290
4468
  const eq = token2.indexOf("=");
4291
4469
  const name = eq === -1 ? token2.slice(2) : token2.slice(2, eq);
4292
- const inline = eq === -1 ? void 0 : token2.slice(eq + 1);
4470
+ const inline2 = eq === -1 ? void 0 : token2.slice(eq + 1);
4293
4471
  const def = byName2.get(name);
4472
+ if (!def && parse3.unknownAsArguments) {
4473
+ positionals.push(token2);
4474
+ continue;
4475
+ }
4294
4476
  if (!def) throw new InvalidSignatureError(`The "--${name}" option does not exist.`);
4295
- i += applyOption(options, def, inline, argv[i + 1]);
4477
+ i += applyOption(options, def, inline2, argv[i + 1]);
4478
+ } else if (token2.length > 1 && token2.startsWith("-") && parse3.unknownAsArguments && !shortcuts.has(token2[1])) {
4479
+ positionals.push(token2);
4296
4480
  } else if (token2.length > 1 && token2.startsWith("-")) {
4297
4481
  i += applyShortcutToken(options, token2, argv[i + 1], shortcuts, byName2);
4298
4482
  } else {
@@ -4385,6 +4569,81 @@ var HelpCommand = class extends Command {
4385
4569
  return 0;
4386
4570
  }
4387
4571
  };
4572
+ var GLOBAL_OPTION_HELP = [
4573
+ ["-h, --help", "Display help for the given command. When no command is given display help for the list command"],
4574
+ ["-q, --quiet", "Do not output any message"],
4575
+ ["-V, --version", "Display this application version"],
4576
+ [" --ansi|--no-ansi", "Accepted for Laravel's scripts; Oriel's output has no colours"],
4577
+ ["-n, --no-interaction", "Do not ask any interactive question"],
4578
+ [" --env[=ENV]", "The environment the command should run under"],
4579
+ ["-v|vv|vvv, --verbose", "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug"]
4580
+ ];
4581
+ var VERBOSE = { "-v": 1, "-vv": 2, "-vvv": 3, "--verbose": 1 };
4582
+ function declared(token2, signature) {
4583
+ if (signature === void 0) return false;
4584
+ if (token2.startsWith("--")) {
4585
+ const name = token2.slice(2).split("=")[0];
4586
+ return signature.options.some((option) => option.name === name);
4587
+ }
4588
+ return signature.options.some((option) => option.shortcut !== void 0 && `-${option.shortcut}` === token2);
4589
+ }
4590
+ function splitGlobalOptions(argv, signature) {
4591
+ const options = { interactive: true, verbosity: 0, version: false };
4592
+ const rest = [];
4593
+ let quiet = false;
4594
+ for (let i = 0; i < argv.length; i++) {
4595
+ const token2 = argv[i];
4596
+ if (token2 === "--") {
4597
+ rest.push(...argv.slice(i));
4598
+ break;
4599
+ }
4600
+ if (declared(token2, signature)) {
4601
+ rest.push(token2);
4602
+ continue;
4603
+ }
4604
+ if (token2 === "-n" || token2 === "--no-interaction") options.interactive = false;
4605
+ else if (token2 === "-q" || token2 === "--quiet") quiet = true;
4606
+ else if (token2 === "-V" || token2 === "--version") options.version = true;
4607
+ else if (token2 === "--ansi" || token2 === "--no-ansi") continue;
4608
+ else if (VERBOSE[token2] !== void 0) options.verbosity = Math.max(options.verbosity, VERBOSE[token2]);
4609
+ else if (/^--verbose=[123]$/.test(token2)) options.verbosity = Number(token2.slice(-1));
4610
+ else if (token2.startsWith("--env=")) options.env = token2.slice("--env=".length);
4611
+ else if (token2 === "--env" && argv[i + 1] !== void 0 && !argv[i + 1].startsWith("-")) options.env = argv[++i];
4612
+ else rest.push(token2);
4613
+ }
4614
+ if (quiet) options.verbosity = -1;
4615
+ return { argv: rest, options };
4616
+ }
4617
+ function commandIndex(argv) {
4618
+ for (let i = 0; i < argv.length; i++) {
4619
+ const token2 = argv[i];
4620
+ if (token2 === "--") return -1;
4621
+ if (token2 === "--env" && argv[i + 1] !== void 0 && !argv[i + 1].startsWith("-")) {
4622
+ i++;
4623
+ continue;
4624
+ }
4625
+ if (splitGlobalOptions([token2]).argv.length === 0) continue;
4626
+ return i;
4627
+ }
4628
+ return -1;
4629
+ }
4630
+ function splitGlobalParameters(parameters, signature) {
4631
+ const rest = {};
4632
+ let interactive;
4633
+ let verbosity;
4634
+ for (const [key, value2] of Object.entries(parameters)) {
4635
+ const name = key.replace(/^-+/, "");
4636
+ if (key.startsWith("-") && signature.options.some((option) => option.name === name || option.shortcut === name)) {
4637
+ rest[key] = value2;
4638
+ } else if ((key === "--no-interaction" || key === "-n") && value2) interactive = false;
4639
+ else if ((key === "--quiet" || key === "-q") && value2) verbosity = -1;
4640
+ else if (key === "--verbose" || key === "-v") {
4641
+ if (value2) verbosity ??= typeof value2 === "number" && value2 >= 1 && value2 <= 3 ? value2 : 1;
4642
+ } else if (key === "--ansi" || key === "--no-ansi" || key === "--env") continue;
4643
+ else rest[key] = value2;
4644
+ }
4645
+ return { parameters: rest, ...interactive !== void 0 && { interactive }, ...verbosity !== void 0 && { verbosity } };
4646
+ }
4388
4647
  var ListCommand = class extends Command {
4389
4648
  signature = "list {namespace? : Only list commands in this namespace}";
4390
4649
  description = "List commands";
@@ -4394,6 +4653,10 @@ var ListCommand = class extends Command {
4394
4653
  const names = Object.keys(all).filter((name) => namespace === void 0 || name === namespace || name.startsWith(`${namespace}:`)).sort();
4395
4654
  const width = Math.max(0, ...names.map((name) => name.length));
4396
4655
  const describe2 = (name) => ` ${name.padEnd(width)} ${all[name].description}`;
4656
+ const optionWidth = Math.max(...GLOBAL_OPTION_HELP.map(([option]) => option.length));
4657
+ this.line("Options:");
4658
+ for (const [option, help] of GLOBAL_OPTION_HELP) this.line(` ${option.padEnd(optionWidth)} ${help}`);
4659
+ this.newLine();
4397
4660
  this.line("Available commands:");
4398
4661
  const unnamespaced = names.filter((name) => !name.includes(":"));
4399
4662
  const namespaced = names.filter((name) => name.includes(":"));
@@ -4827,21 +5090,7 @@ export class {{ class }} {
4827
5090
  }
4828
5091
  `;
4829
5092
  var POLICY_STUB = `export class {{ class }} {
4830
- view(_user: unknown, _model: unknown): boolean {
4831
- return true
4832
- }
4833
-
4834
- create(_user: unknown): boolean {
4835
- return true
4836
- }
4837
-
4838
- update(_user: unknown, _model: unknown): boolean {
4839
- return true
4840
- }
4841
-
4842
- delete(_user: unknown, _model: unknown): boolean {
4843
- return true
4844
- }
5093
+ //
4845
5094
  }
4846
5095
  `;
4847
5096
  var PROVIDER_STUB = `import { ServiceProvider } from '@orieljs/framework'
@@ -4897,19 +5146,23 @@ export class {{ class }} implements CastsAttributes {
4897
5146
  }
4898
5147
  }
4899
5148
  `;
4900
- var RESOURCE_STUB = `export class {{ class }} {
4901
- constructor(private readonly resource: unknown) {}
5149
+ var RESOURCE_STUB = `import { JsonResource } from '@orieljs/framework'
5150
+ import type { HttpRequest } from '@orieljs/framework/contracts'
4902
5151
 
4903
- toArray(): Record<string, unknown> {
4904
- return { ...(this.resource as Record<string, unknown>) }
5152
+ export class {{ class }} extends JsonResource {
5153
+ /** Transform the resource into an array. */
5154
+ override toArray(request: HttpRequest) {
5155
+ return super.toArray(request)
4905
5156
  }
4906
5157
  }
4907
5158
  `;
4908
- var RESOURCE_COLLECTION_STUB = `export class {{ class }} {
4909
- constructor(private readonly resource: unknown[]) {}
5159
+ var RESOURCE_COLLECTION_STUB = `import { ResourceCollection } from '@orieljs/framework'
5160
+ import type { HttpRequest } from '@orieljs/framework/contracts'
4910
5161
 
4911
- toArray(): unknown[] {
4912
- return this.resource
5162
+ export class {{ class }} extends ResourceCollection {
5163
+ /** Transform the resource collection into an array. */
5164
+ override toArray(request: HttpRequest) {
5165
+ return super.toArray(request)
4913
5166
  }
4914
5167
  }
4915
5168
  `;
@@ -5266,6 +5519,40 @@ var MakePolicyCommand = class extends GeneratorCommand {
5266
5519
  };
5267
5520
  }
5268
5521
  };
5522
+ function addProviderToBootstrap(source, className, specifier) {
5523
+ const list23 = /export default \[([\s\S]*?)\]/.exec(source);
5524
+ if (list23 === null) return void 0;
5525
+ const listed4 = list23[1].split(",").map((entry) => entry.trim()).filter(Boolean);
5526
+ if (listed4.includes(className)) return source;
5527
+ const inner = list23[1];
5528
+ let items;
5529
+ if (!inner.includes("\n")) {
5530
+ items = listed4.length === 0 ? className : `${inner.replace(/\s*$/, "")}, ${className}`;
5531
+ } else {
5532
+ const lines = inner.split("\n");
5533
+ const closing = lines.pop();
5534
+ const indent = /^(\s*)\S/.exec(lines.find((line) => line.trim() !== "") ?? "")?.[1] ?? " ";
5535
+ while (lines.length > 0 && lines.at(-1).trim() === "") lines.pop();
5536
+ if (lines.length > 0 && !lines.at(-1).trimEnd().endsWith(",") && lines.at(-1).trim() !== "") lines[lines.length - 1] = `${lines.at(-1).trimEnd()},`;
5537
+ items = [...lines, `${indent}${className},`, closing].join("\n");
5538
+ }
5539
+ const start3 = list23.index + "export default [".length;
5540
+ let updated = source.slice(0, start3) + items + source.slice(start3 + inner.length);
5541
+ if (!new RegExp(`import\\s*\\{[^}]*\\b${className}\\b[^}]*\\}`).test(updated)) {
5542
+ const imports = [...updated.matchAll(/^import[\s\S]*?from\s+['"][^'"]+['"];?[^\S\n]*$/gm)];
5543
+ const line = `import { ${className} } from '${specifier}'`;
5544
+ if (imports.length === 0) updated = `${line}
5545
+
5546
+ ${updated}`;
5547
+ else {
5548
+ const last = imports.at(-1);
5549
+ const end = last.index + last[0].length;
5550
+ updated = `${updated.slice(0, end)}
5551
+ ${line}${updated.slice(end)}`;
5552
+ }
5553
+ }
5554
+ return updated;
5555
+ }
5269
5556
  var MakeProviderCommand = class extends GeneratorCommand {
5270
5557
  signature = "make:provider {name} {--force}";
5271
5558
  description = "Create a new service provider class";
@@ -5278,6 +5565,25 @@ var MakeProviderCommand = class extends GeneratorCommand {
5278
5565
  stub() {
5279
5566
  return PROVIDER_STUB;
5280
5567
  }
5568
+ /** Writes the class, then lists it in bootstrap/providers.ts, as Laravel's make:provider does. */
5569
+ async handle() {
5570
+ const code = await super.handle();
5571
+ if (code !== 0) return code;
5572
+ const rawName = this.argument("name");
5573
+ const { className } = this.qualifyClass(rawName);
5574
+ const file = inject(Application).bootstrapPath("providers.ts");
5575
+ const specifier = relative22(dirname3(file), this.targetPath(rawName).replace(/\.ts$/, "")).split(sep2).join("/");
5576
+ const source = existsSync4(file) ? await readFile2(file, "utf8") : void 0;
5577
+ const updated = source === void 0 ? void 0 : addProviderToBootstrap(source, className, specifier.startsWith(".") ? specifier : `./${specifier}`);
5578
+ if (updated === void 0) {
5579
+ this.warn(
5580
+ `Unable to automatically add the provider to bootstrap/providers.ts. Import ${className} from '${specifier}' there and add it to the list.`
5581
+ );
5582
+ } else if (updated !== source) {
5583
+ await writeFile3(file, updated);
5584
+ }
5585
+ return 0;
5586
+ }
5281
5587
  };
5282
5588
  var MakeRequestCommand = class extends GeneratorCommand {
5283
5589
  signature = "make:request {name} {--force}";
@@ -5294,12 +5600,13 @@ var MakeRequestCommand = class extends GeneratorCommand {
5294
5600
  };
5295
5601
  var MakeResourceCommand = class extends GeneratorCommand {
5296
5602
  signature = "make:resource {name} {--collection} {--force}";
5297
- description = "Create a new resource transformer class";
5603
+ description = "Create a new resource";
5298
5604
  type() {
5299
5605
  return "Http/Resources";
5300
5606
  }
5607
+ /** A JsonResource, or a ResourceCollection with --collection or a name ending in Collection, as Laravel's. */
5301
5608
  stub() {
5302
- return this.option("collection") ? RESOURCE_COLLECTION_STUB : RESOURCE_STUB;
5609
+ return this.option("collection") || String(this.argument("name")).endsWith("Collection") ? RESOURCE_COLLECTION_STUB : RESOURCE_STUB;
5303
5610
  }
5304
5611
  };
5305
5612
  var MakeRuleCommand = class extends GeneratorCommand {
@@ -5549,10 +5856,11 @@ var TestCommand = class extends Command {
5549
5856
  super();
5550
5857
  this.spawner = spawner;
5551
5858
  this.onBun = onBun;
5859
+ this.ignoreValidationErrors();
5552
5860
  }
5553
5861
  spawner;
5554
5862
  onBun;
5555
- /** Paths are passed on to vitest; so is everything after `--` (`oriel test -- --coverage`). */
5863
+ /** Paths and options Oriel doesn't know are passed on to vitest (`oriel test --coverage`), as is everything after `--`. */
5556
5864
  signature = "test {args?*} {--filter=}";
5557
5865
  description = "Run the test suite";
5558
5866
  handle() {
@@ -5599,7 +5907,7 @@ function sourceFiles(directory) {
5599
5907
  return files3.sort();
5600
5908
  }
5601
5909
  async function discoverCommands(kernel, directory) {
5602
- if (!existsSync4(directory)) return;
5910
+ if (!existsSync5(directory)) return;
5603
5911
  for (const file of sourceFiles(directory)) {
5604
5912
  const module = await import(pathToFileURL2(file).href);
5605
5913
  for (const exported of Object.values(module)) {
@@ -5615,7 +5923,7 @@ var generation = 0;
5615
5923
  async function loadConsoleRoutes(app2, kernel) {
5616
5924
  if (!app2.bound(RoutingPaths)) return;
5617
5925
  const file = app2.make(RoutingPaths).console;
5618
- if (!file || !existsSync4(file)) return;
5926
+ if (!file || !existsSync5(file)) return;
5619
5927
  const url2 = `${pathToFileURL2(file).href}?oriel-console=${++generation}`;
5620
5928
  await app2.run(async () => {
5621
5929
  const module = await import(url2);
@@ -5730,23 +6038,44 @@ var Kernel2 = class {
5730
6038
  async callWithIo(command, parameters, io) {
5731
6039
  const instance = this.findOrThrow(command);
5732
6040
  const signature = parseSignature(instance.signature);
5733
- return this.execute(instance, signature, parametersToInput(parameters, signature), io);
6041
+ const global = splitGlobalParameters(parameters, signature);
6042
+ const runIo = {
6043
+ ...io,
6044
+ ...global.interactive !== void 0 && { interactive: global.interactive },
6045
+ ...global.verbosity !== void 0 && { verbosity: global.verbosity }
6046
+ };
6047
+ return this.execute(instance, signature, parametersToInput(global.parameters, signature), runIo);
5734
6048
  }
5735
6049
  async handle(argv) {
5736
6050
  const io = { input: this.defaultInput, output: this.defaultOutput };
5737
6051
  this.running++;
5738
6052
  try {
5739
- const [name, ...rest] = this.normalizeTopLevel(argv);
6053
+ const at = commandIndex(argv);
6054
+ const leading = splitGlobalOptions(at === -1 ? argv.filter((token2) => token2 !== "--") : argv.slice(0, at)).options;
6055
+ if (leading.version) return this.printVersion(io.output);
6056
+ const [name, ...rest] = this.normalizeTopLevel(at === -1 ? [] : argv.slice(at));
5740
6057
  const instance = this.findOrThrow(name);
5741
6058
  const signature = parseSignature(instance.signature);
5742
- const input = parseArgv(rest, signature);
5743
- return await this.execute(instance, signature, input, io);
6059
+ const split = splitGlobalOptions(rest, signature);
6060
+ if (split.options.version) return this.printVersion(io.output);
6061
+ const lenient = instance.ignoresValidationErrors === true;
6062
+ const input = parseArgv(split.argv, signature, { unknownAsArguments: lenient });
6063
+ return await this.execute(instance, signature, input, {
6064
+ ...io,
6065
+ interactive: leading.interactive && split.options.interactive,
6066
+ verbosity: leading.verbosity === -1 || split.options.verbosity === -1 ? -1 : Math.max(leading.verbosity, split.options.verbosity)
6067
+ });
5744
6068
  } catch (error) {
5745
6069
  return this.reportTopLevelError(error, io.output);
5746
6070
  } finally {
5747
6071
  if (--this.running === 0) this.defaultInput.close?.();
5748
6072
  }
5749
6073
  }
6074
+ printVersion(output) {
6075
+ output.write(`Oriel Framework${this.app.version === void 0 ? "" : ` ${this.app.version}`}
6076
+ `);
6077
+ return 0;
6078
+ }
5750
6079
  reportTopLevelError(error, output) {
5751
6080
  if (error instanceof ConsoleAbortedError) {
5752
6081
  output.writeError(`${error.message}
@@ -5763,7 +6092,7 @@ var Kernel2 = class {
5763
6092
  }
5764
6093
  return 1;
5765
6094
  }
5766
- if (error instanceof InvalidSignatureError) {
6095
+ if (error instanceof InvalidSignatureError || error instanceof InputRequiredError) {
5767
6096
  output.writeError(`${error.message}
5768
6097
  `);
5769
6098
  return 1;
@@ -5808,6 +6137,40 @@ var Kernel2 = class {
5808
6137
  });
5809
6138
  }
5810
6139
  };
6140
+ var ScheduledTaskStarting = class {
6141
+ constructor(task) {
6142
+ this.task = task;
6143
+ }
6144
+ task;
6145
+ };
6146
+ var ScheduledTaskFinished = class {
6147
+ constructor(task, runtime) {
6148
+ this.task = task;
6149
+ this.runtime = runtime;
6150
+ }
6151
+ task;
6152
+ runtime;
6153
+ };
6154
+ var ScheduledTaskFailed = class {
6155
+ constructor(task, exception) {
6156
+ this.task = task;
6157
+ this.exception = exception;
6158
+ }
6159
+ task;
6160
+ exception;
6161
+ };
6162
+ var ScheduledTaskSkipped = class {
6163
+ constructor(task) {
6164
+ this.task = task;
6165
+ }
6166
+ task;
6167
+ };
6168
+ var ScheduledExitError = class extends Error {
6169
+ };
6170
+ async function dispatchScheduleEvent(event2) {
6171
+ const container = currentContainer();
6172
+ if (container?.bound(EventDispatcher)) await container.make(EventDispatcher).dispatch(event2);
6173
+ }
5811
6174
  var SHOULD_QUEUE2 = /* @__PURE__ */ Symbol.for("oriel:bus.shouldQueue");
5812
6175
  var QUEUE_OPTIONS2 = ["connection", "queue", "delay", "tries", "backoff", "timeout"];
5813
6176
  function isQueueable2(job) {
@@ -6176,11 +6539,18 @@ var ScheduledEventImpl = class {
6176
6539
  * servers that start the event a little late still compete for the same slot, and the server that wins keeps the
6177
6540
  * slot for the event's every-N-seconds repetitions in that minute. `checkedAt` is when this run starts (a
6178
6541
  * repetition's own moment), from which the next repetition counts.
6542
+ *
6543
+ * Dispatches Laravel's scheduler events, so schedule:run, schedule:work and the Vercel cron all do: Skipped when a
6544
+ * filter holds it back; Starting, then Finished (with the runtime) and, if it failed, Failed. A task that throws
6545
+ * dispatches only Failed; one that exits non-zero, or returns false, Finished then Failed, as Laravel's runEvent().
6546
+ * A lock that holds it back dispatches nothing.
6179
6547
  */
6180
6548
  async run(startedAt = /* @__PURE__ */ new Date(), checkedAt = startedAt) {
6181
6549
  this.lastChecked = checkedAt.getTime();
6182
- for (const filter of this.filters) if (!await filter()) return;
6183
- for (const reject of this.rejects) if (await reject()) return;
6550
+ if (!await this.filtersPass()) {
6551
+ await dispatchScheduleEvent(new ScheduledTaskSkipped(this));
6552
+ return;
6553
+ }
6184
6554
  if (this.oneServer) {
6185
6555
  const minuteSlot = Math.floor(startedAt.getTime() / 6e4);
6186
6556
  if (this.wonServerSlot !== minuteSlot) {
@@ -6196,10 +6566,23 @@ var ScheduledEventImpl = class {
6196
6566
  this.heldOverlapLock = overlapLock;
6197
6567
  }
6198
6568
  try {
6199
- for (const callback of this.beforeCallbacks) await callback();
6200
- const failure = await this.execute();
6201
- for (const callback of this.afterCallbacks) await callback(failure === void 0);
6202
- if (failure !== void 0) throw failure.error;
6569
+ await dispatchScheduleEvent(new ScheduledTaskStarting(this));
6570
+ const start3 = performance.now();
6571
+ let failure;
6572
+ try {
6573
+ for (const callback of this.beforeCallbacks) await callback();
6574
+ failure = await this.execute();
6575
+ for (const callback of this.afterCallbacks) await callback(failure === void 0);
6576
+ } catch (error) {
6577
+ failure = { error, exited: false };
6578
+ }
6579
+ if (failure === void 0 || failure.exited) {
6580
+ await dispatchScheduleEvent(new ScheduledTaskFinished(this, Math.round((performance.now() - start3) / 10) / 100));
6581
+ }
6582
+ if (failure !== void 0) {
6583
+ await dispatchScheduleEvent(new ScheduledTaskFailed(this, failure.error));
6584
+ throw failure.error;
6585
+ }
6203
6586
  } finally {
6204
6587
  if (overlapLock && this.heldOverlapLock === overlapLock) {
6205
6588
  this.heldOverlapLock = void 0;
@@ -6223,12 +6606,18 @@ var ScheduledEventImpl = class {
6223
6606
  */
6224
6607
  async execute() {
6225
6608
  try {
6226
- if (await this.executor() === false) return { error: new Error(`${this.getSummaryForDisplay()} returned false.`) };
6609
+ if (await this.executor() === false) return { error: new Error(`${this.getSummaryForDisplay()} returned false.`), exited: true };
6227
6610
  return void 0;
6228
6611
  } catch (error) {
6229
- return { error };
6612
+ return { error, exited: error instanceof ScheduledExitError };
6230
6613
  }
6231
6614
  }
6615
+ /** Laravel's filtersPass(): every when() is true and no skip() is. */
6616
+ async filtersPass() {
6617
+ for (const filter of this.filters) if (!await filter()) return false;
6618
+ for (const reject of this.rejects) if (await reject()) return false;
6619
+ return true;
6620
+ }
6232
6621
  /**
6233
6622
  * Follows Laravel: a command event's mutex is `sha1(expression + full command
6234
6623
  * string incl. parameters)` (Laravel's `Event::mutexName()`) — no `name()` required. A closure event (`call()`/
@@ -6264,7 +6653,7 @@ var ScheduleImpl = class {
6264
6653
  const commandString = argv.join(" ");
6265
6654
  const execute = async () => {
6266
6655
  const code = await inject(ConsoleKernel).handle(argv);
6267
- if (code !== 0) throw new Error(`"${commandString}" exited with code ${code}.`);
6656
+ if (code !== 0) throw new ScheduledExitError(`"${commandString}" exited with code ${code}.`);
6268
6657
  };
6269
6658
  return this.push(new ScheduledEventImpl(execute, commandString).description(command));
6270
6659
  }
@@ -6355,7 +6744,8 @@ var ConsoleServiceProvider = class extends ServiceProvider {
6355
6744
  var Artisan = facade(ConsoleKernel);
6356
6745
  var Schedule5 = facade(Schedule);
6357
6746
  async function runConsole(app2, argv = process.argv.slice(2)) {
6358
- app2.setRunningInConsole(true);
6747
+ const at = commandIndex(argv);
6748
+ app2.setRunningInConsole(at === -1 || argv[at] !== "serve");
6359
6749
  try {
6360
6750
  await app2.boot();
6361
6751
  return await app2.make(ConsoleKernel).handle(argv);
@@ -6615,7 +7005,7 @@ import { sql as sql5 } from "kysely";
6615
7005
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
6616
7006
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
6617
7007
  import { isDeepStrictEqual } from "util";
6618
- import { existsSync as existsSync5, readdirSync as readdirSync3 } from "fs";
7008
+ import { existsSync as existsSync6, readdirSync as readdirSync3 } from "fs";
6619
7009
  import { join as join43 } from "path";
6620
7010
  import { pathToFileURL as pathToFileURL3 } from "url";
6621
7011
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
@@ -6625,10 +7015,10 @@ import { existsSync as existsSync32, readdirSync as readdirSync22 } from "fs";
6625
7015
  import { basename, extname, join as join6 } from "path";
6626
7016
  import { pathToFileURL as pathToFileURL22 } from "url";
6627
7017
  import { existsSync as existsSync42 } from "fs";
6628
- import { isAbsolute, join as join7, relative as relative22 } from "path";
7018
+ import { isAbsolute, join as join7, relative as relative23 } from "path";
6629
7019
  import { pathToFileURL as pathToFileURL32 } from "url";
6630
- import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
6631
- import { dirname as dirname3, relative as relative3, sep as sep2 } from "path";
7020
+ import { mkdir as mkdir3, writeFile as writeFile4 } from "fs/promises";
7021
+ import { dirname as dirname4, relative as relative3, sep as sep3 } from "path";
6632
7022
  import { existsSync as existsSync52, readdirSync as readdirSync32, statSync } from "fs";
6633
7023
  import { join as join8 } from "path";
6634
7024
  import { pathToFileURL as pathToFileURL4 } from "url";
@@ -6872,11 +7262,12 @@ function buildQuery(values, prefix) {
6872
7262
  }
6873
7263
  return parts.join("&");
6874
7264
  }
7265
+ var isModelLike = (value2) => typeof value2 === "object" && value2 !== null && typeof value2.getKey === "function" && typeof value2.getAttributes === "function";
6875
7266
  var isArrayable = (value2) => typeof value2 === "object" && value2 !== null && typeof value2.toArray === "function";
6876
7267
  var AbstractPaginator = class _AbstractPaginator {
6877
7268
  constructor(items, perPageValue, options, currentPage) {
6878
7269
  this.perPageValue = perPageValue;
6879
- this.collection = new Collection(items);
7270
+ this.collection = items instanceof Collection ? items : new Collection(items);
6880
7271
  const path = options.path ?? _AbstractPaginator.resolveCurrentPath();
6881
7272
  this.pathValue = path !== "/" ? path.replace(/\/+$/, "") : path;
6882
7273
  this.queryValues = { ...options.query ?? {} };
@@ -6975,6 +7366,7 @@ var AbstractPaginator = class _AbstractPaginator {
6975
7366
  items() {
6976
7367
  return this.collection.all();
6977
7368
  }
7369
+ /** The items on this page: an Eloquent query's in its models' Eloquent collection, as Laravel's. */
6978
7370
  getCollection() {
6979
7371
  return this.collection;
6980
7372
  }
@@ -6987,7 +7379,9 @@ var AbstractPaginator = class _AbstractPaginator {
6987
7379
  * `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.
6988
7380
  */
6989
7381
  through(callback) {
6990
- this.collection = this.collection.map(callback);
7382
+ const mapped = this.collection.all().map(callback);
7383
+ const eloquent = typeof this.collection.modelKeys === "function" && mapped.every(isModelLike);
7384
+ this.collection = eloquent ? new this.collection.constructor(mapped) : new Collection(mapped);
6991
7385
  return this;
6992
7386
  }
6993
7387
  perPage() {
@@ -7069,7 +7463,7 @@ var CursorPaginator = class extends AbstractPaginator {
7069
7463
  this.parameters = options.parameters;
7070
7464
  this.hasMore = this.collection.count() > perPage;
7071
7465
  this.collection = this.collection.slice(0, perPage);
7072
- if (cursorValue?.pointsToPreviousItems()) this.collection = new Collection(this.collection.all().reverse());
7466
+ if (cursorValue?.pointsToPreviousItems()) this.collection = this.collection.reverse();
7073
7467
  }
7074
7468
  cursorValue;
7075
7469
  hasMore;
@@ -8052,14 +8446,14 @@ var Builder = class _Builder {
8052
8446
  const current = page ?? AbstractPaginator.resolveCurrentPage(pageName);
8053
8447
  const total = await this.clone().count();
8054
8448
  const items = total > 0 ? await this.clone().withColumns(columns).forPage(current, size).runSelect() : [];
8055
- return new LengthAwarePaginator(items, total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
8449
+ return new LengthAwarePaginator(this.newCollection(items), total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
8056
8450
  }
8057
8451
  /** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */
8058
8452
  async simplePaginate(perPage, columns = ["*"], pageName = "page", page) {
8059
8453
  const size = perPage ?? this.defaultPerPage();
8060
8454
  const current = page ?? AbstractPaginator.resolveCurrentPage(pageName);
8061
8455
  const items = await this.clone().withColumns(columns).offset((current - 1) * size).limit(size + 1).runSelect();
8062
- return new Paginator(items, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
8456
+ return new Paginator(this.newCollection(items), size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
8063
8457
  }
8064
8458
  /**
8065
8459
  * Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);
@@ -8072,7 +8466,7 @@ var Builder = class _Builder {
8072
8466
  const orders = query.ordersForCursor(current?.pointsToPreviousItems() ?? false);
8073
8467
  if (current) query.whereCursor(current, orders, 0);
8074
8468
  const items = await query.limit(size + 1).runSelect();
8075
- return new CursorPaginator(items, size, current, {
8469
+ return new CursorPaginator(this.newCollection(items), size, current, {
8076
8470
  path: AbstractPaginator.resolveCurrentPath(),
8077
8471
  cursorName,
8078
8472
  parameters: orders.map((order) => String(order.column))
@@ -9433,13 +9827,13 @@ async function rebuild(db, grammar, step) {
9433
9827
  throw new LogicError(`SQLite can't rebuild [${table}]: it has generated or hidden columns.`);
9434
9828
  }
9435
9829
  const { definitions, options } = splitCreateTable(master.sql);
9436
- const declared = /* @__PURE__ */ new Map();
9830
+ const declared2 = /* @__PURE__ */ new Map();
9437
9831
  for (const definition of definitions) {
9438
9832
  const name = definedColumn(definition);
9439
- if (name !== void 0) declared.set(lower(name), definition);
9833
+ if (name !== void 0) declared2.set(lower(name), definition);
9440
9834
  }
9441
9835
  const keyColumns = columns.filter((column) => Number(column.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk));
9442
- let autoincrement = keyColumns.length === 1 && columnClauses(declared.get(lower(keyColumns[0].name)) ?? "").autoincrement ? keyColumns[0].name : void 0;
9836
+ let autoincrement = keyColumns.length === 1 && columnClauses(declared2.get(lower(keyColumns[0].name)) ?? "").autoincrement ? keyColumns[0].name : void 0;
9443
9837
  let primary = keyColumns.map((column) => column.name);
9444
9838
  const foreign = grammar.normalizeForeignKeys((await db.execute(grammar.compileForeignKeys(table))).rows).map(foreignKeyDefinition);
9445
9839
  for (const change of step.changes) {
@@ -9472,7 +9866,7 @@ async function rebuild(db, grammar, step) {
9472
9866
  }
9473
9867
  const parts = columns.map((column) => {
9474
9868
  const change = changes.get(lower(column.name));
9475
- return change ? grammar.columnDefinition(change) : renderColumn(column, declared.get(lower(column.name)), column.name === autoincrement);
9869
+ return change ? grammar.columnDefinition(change) : renderColumn(column, declared2.get(lower(column.name)), column.name === autoincrement);
9476
9870
  });
9477
9871
  if (autoincrement === void 0 && primary.length) parts.push(sql5`primary key (${columnList2(primary)})`);
9478
9872
  for (const key of foreign) parts.push(grammar.compileForeignKeyConstraint(key));
@@ -9641,6 +10035,9 @@ var SchemaBuilder = class _SchemaBuilder {
9641
10035
  for (const statement of statements) await this.db.execute(statement);
9642
10036
  }
9643
10037
  };
10038
+ function holdsCallbacks(frame) {
10039
+ return frame !== void 0 && frame.ignoresCallbacks !== true;
10040
+ }
9644
10041
  var Connection = class {
9645
10042
  constructor(name, config2) {
9646
10043
  this.name = name;
@@ -9726,24 +10123,108 @@ var Connection = class {
9726
10123
  try {
9727
10124
  result = await this.context.run(frame, () => fn(this));
9728
10125
  } catch (error) {
9729
- await this.close(frame, "rollback");
10126
+ try {
10127
+ await this.close(frame, "rollback");
10128
+ } finally {
10129
+ await this.rolledBack(frame);
10130
+ }
10131
+ throw error;
10132
+ }
10133
+ try {
10134
+ await this.close(frame, "commit");
10135
+ } catch (error) {
10136
+ await this.rolledBack(frame);
9730
10137
  throw error;
9731
10138
  }
9732
- await this.close(frame, "commit");
10139
+ await this.committed(frame);
9733
10140
  return result;
9734
10141
  }
10142
+ /** A committed level hands its callbacks to the transaction(fn) it's nested in, or runs them, outside its context. */
10143
+ async committed(frame) {
10144
+ frame.ended = "commit";
10145
+ if (holdsCallbacks(frame.parent)) {
10146
+ frame.parent.callbacks.push(...frame.callbacks.splice(0));
10147
+ frame.parent.rollbacks.push(...frame.rollbacks.splice(0));
10148
+ return;
10149
+ }
10150
+ frame.rollbacks.length = 0;
10151
+ for (const callback of frame.callbacks.splice(0)) await this.context.exit(() => callback());
10152
+ }
10153
+ /** A level that rolled back drops its callbacks and runs its onRollBack ones, outside its context. */
10154
+ async rolledBack(frame) {
10155
+ frame.ended = "rollback";
10156
+ frame.callbacks.length = 0;
10157
+ for (const callback of frame.rollbacks.splice(0)) await this.runQuietly(callback);
10158
+ }
10159
+ /** An onRollBack callback's failure must not hide the error that rolled the transaction back. */
10160
+ async runQuietly(callback) {
10161
+ try {
10162
+ await this.context.exit(() => callback());
10163
+ } catch {
10164
+ }
10165
+ }
9735
10166
  /** Starts a transaction that stays open, for every async context, until commit()/rollBack(). */
9736
10167
  async beginTransaction() {
9737
- this.pinned.push(await this.open());
10168
+ const frame = await this.open();
10169
+ frame.pinned = true;
10170
+ this.pinned.push(frame);
10171
+ }
10172
+ /**
10173
+ * @internal RefreshDatabase's and DatabaseTransactions': the level beginTransaction() just opened holds no
10174
+ * afterCommit() callbacks, so they run as they would without the test's transaction (Laravel's
10175
+ * callbacksShouldIgnore()), and a test's own transaction(fn) or beginTransaction() runs them at its commit.
10176
+ */
10177
+ ignoreAfterCommitAtCurrentLevel() {
10178
+ const frame = this.pinned.at(-1);
10179
+ if (frame) frame.ignoresCallbacks = true;
10180
+ }
10181
+ /**
10182
+ * Laravel's DB::afterCommit(): runs the callback once the transaction open here commits, the outermost one when
10183
+ * they're nested, and drops it if that level rolls back: a transaction(fn) open in this async context, or a level
10184
+ * beginTransaction() opened. Outside one, or in only the testing traits' transaction, it runs at once.
10185
+ * `onRollBack` runs instead when the level that holds the callback rolls back. A callback added once its level has
10186
+ * ended (by work nobody awaited) follows it: held by the level it was committed into, run if the commit is done,
10187
+ * dropped if it rolled back.
10188
+ */
10189
+ async afterCommit(callback, onRollBack) {
10190
+ let frame = this.context.getStore() ?? this.pinned.at(-1);
10191
+ while (frame?.ended === "commit") frame = holdsCallbacks(frame.parent) ? frame.parent : void 0;
10192
+ if (!holdsCallbacks(frame)) {
10193
+ await callback();
10194
+ return;
10195
+ }
10196
+ if (frame.ended === "rollback") {
10197
+ if (onRollBack !== void 0) await this.runQuietly(onRollBack);
10198
+ return;
10199
+ }
10200
+ frame.callbacks.push(callback);
10201
+ if (onRollBack !== void 0) frame.rollbacks.push(onRollBack);
10202
+ }
10203
+ /** @internal Whether a transaction is open here that afterCommit() would wait for. */
10204
+ inTransactionContext() {
10205
+ return holdsCallbacks(this.context.getStore() ?? this.pinned.at(-1));
9738
10206
  }
10207
+ /** Commits the innermost level opened by beginTransaction(), then runs (or hands up) its afterCommit() callbacks. */
9739
10208
  async commit() {
9740
10209
  const frame = this.pinned.pop();
9741
- if (frame) await this.close(frame, "commit");
10210
+ if (!frame) return;
10211
+ try {
10212
+ await this.close(frame, "commit");
10213
+ } catch (error) {
10214
+ await this.rolledBack(frame);
10215
+ throw error;
10216
+ }
10217
+ await this.committed(frame);
9742
10218
  }
9743
- /** Rolls back the innermost level opened by beginTransaction(). Does nothing when none is open. */
10219
+ /** Rolls back the innermost level opened by beginTransaction(), dropping its afterCommit() callbacks. */
9744
10220
  async rollBack() {
9745
10221
  const frame = this.pinned.pop();
9746
- if (frame) await this.close(frame, "rollback");
10222
+ if (!frame) return;
10223
+ try {
10224
+ await this.close(frame, "rollback");
10225
+ } finally {
10226
+ await this.rolledBack(frame);
10227
+ }
9747
10228
  }
9748
10229
  transactionLevel() {
9749
10230
  return this.current()?.level ?? 0;
@@ -9773,7 +10254,7 @@ var Connection = class {
9773
10254
  }
9774
10255
  async open() {
9775
10256
  const parent = this.current();
9776
- if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve() };
10257
+ if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve(), callbacks: [], rollbacks: [] };
9777
10258
  const previous = parent.turn;
9778
10259
  let endTurn;
9779
10260
  parent.turn = new Promise((resolve5) => endTurn = resolve5);
@@ -9786,7 +10267,7 @@ var Connection = class {
9786
10267
  endTurn();
9787
10268
  throw error;
9788
10269
  }
9789
- return { trx: parent.trx, level: level2, savepoint, turn: Promise.resolve(), endTurn };
10270
+ return { trx: parent.trx, level: level2, savepoint, turn: Promise.resolve(), endTurn, parent, callbacks: [], rollbacks: [] };
9790
10271
  }
9791
10272
  async close(frame, action) {
9792
10273
  try {
@@ -9924,6 +10405,18 @@ var DatabaseManagerImpl = class {
9924
10405
  beginTransaction() {
9925
10406
  return this.connection().beginTransaction();
9926
10407
  }
10408
+ /**
10409
+ * Laravel's DB::afterCommit(): waits for the transaction(fn) open in this async context, on the default connection
10410
+ * first, then on any other opened one; runs at once outside one. It opens no connection: one with a transaction is
10411
+ * open already.
10412
+ */
10413
+ async afterCommit(callback, onRollBack) {
10414
+ const preferred = this.connections.get(this.getDefaultConnection());
10415
+ const opened = [...preferred === void 0 ? [] : [preferred], ...this.connections.values()];
10416
+ const open = opened.find((connection) => connection.inTransactionContext());
10417
+ if (open === void 0) await callback();
10418
+ else await open.afterCommit(callback, onRollBack);
10419
+ }
9927
10420
  commit() {
9928
10421
  return this.connection().commit();
9929
10422
  }
@@ -10167,11 +10660,6 @@ var Builder2 = class extends Builder {
10167
10660
  if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models);
10168
10661
  return models;
10169
10662
  }
10170
- // ---------------------------------------------------------------- eager loading
10171
- /**
10172
- * Relations to load with the results, one query per relation (and per nesting level):
10173
- * with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').
10174
- */
10175
10663
  with(...relations) {
10176
10664
  for (const spec of relations) {
10177
10665
  if (typeof spec === "string") this.addEagerLoad(spec, void 0);
@@ -10180,7 +10668,6 @@ var Builder2 = class extends Builder {
10180
10668
  }
10181
10669
  return this;
10182
10670
  }
10183
- /** Removes eager loads (including the model's default `with`). */
10184
10671
  without(...relations) {
10185
10672
  for (const name of relations) {
10186
10673
  for (const key of [...this.eagerLoad.keys()]) if (key === name || key.startsWith(`${name}.`)) this.eagerLoad.delete(key);
@@ -10236,40 +10723,24 @@ var Builder2 = class extends Builder {
10236
10723
  }
10237
10724
  return nested;
10238
10725
  }
10239
- // ---------------------------------------------------------------- relation counts and existence
10240
- /**
10241
- * Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),
10242
- * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
10243
- */
10244
10726
  withCount(...relations) {
10245
10727
  return this.withAggregate(relations, "*", "count");
10246
10728
  }
10247
- /** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */
10248
10729
  withSum(relations, column) {
10249
10730
  return this.withAggregate(relations, column, "sum");
10250
10731
  }
10251
- /** Adds `<relation>_avg_<column>`. */
10252
10732
  withAvg(relations, column) {
10253
10733
  return this.withAggregate(relations, column, "avg");
10254
10734
  }
10255
- /** Adds `<relation>_min_<column>`. */
10256
10735
  withMin(relations, column) {
10257
10736
  return this.withAggregate(relations, column, "min");
10258
10737
  }
10259
- /** Adds `<relation>_max_<column>`. */
10260
10738
  withMax(relations, column) {
10261
10739
  return this.withAggregate(relations, column, "max");
10262
10740
  }
10263
- /** Adds a boolean `<relation>_exists`: withExists('comments'). */
10264
10741
  withExists(...relations) {
10265
10742
  return this.withAggregate(relations, "*", "exists");
10266
10743
  }
10267
- /**
10268
- * Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the
10269
- * alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's
10270
- * constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects
10271
- * `exists (…)`, cast to a boolean. Without a function the column's first value is selected.
10272
- */
10273
10744
  withAggregate(relations, column, fn) {
10274
10745
  const specs = this.normalizeRelationSpecs([relations].flat());
10275
10746
  if (!specs.length) return this;
@@ -10303,13 +10774,10 @@ var Builder2 = class extends Builder {
10303
10774
  this.selectCasts = { ...this.selectCasts, ...casts };
10304
10775
  return this;
10305
10776
  }
10306
- /**
10307
- * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
10308
- * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
10309
- */
10310
10777
  has(relation, operator = ">=", count = 1, boolean = "and", callback) {
10311
- if (relation.includes(".")) return this.hasNested(relation, operator, count, boolean, callback);
10312
- const instance = this.getRelation(relation);
10778
+ const name = relation;
10779
+ if (name.includes(".")) return this.hasNested(name, operator, count, boolean, callback);
10780
+ const instance = this.getRelation(name);
10313
10781
  const useExists = (operator === ">=" || operator === "<") && count === 1;
10314
10782
  const query = useExists ? instance.getRelationExistenceQuery(instance.getRelated().newQueryWithoutRelationships(), this) : instance.getRelationExistenceCountQuery(instance.getRelated().newQueryWithoutRelationships(), this);
10315
10783
  query.wheres.push(...instance.wheres);
@@ -10327,7 +10795,6 @@ var Builder2 = class extends Builder {
10327
10795
  orDoesntHave(relation) {
10328
10796
  return this.doesntHave(relation, "or");
10329
10797
  }
10330
- /** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */
10331
10798
  whereHas(relation, callback, operator = ">=", count = 1) {
10332
10799
  return this.has(relation, operator, count, "and", callback);
10333
10800
  }
@@ -10421,48 +10888,46 @@ var Builder2 = class extends Builder {
10421
10888
  newModelInstance(attributes = {}) {
10422
10889
  return this.model.newInstance(attributes);
10423
10890
  }
10424
- make(attributes = {}) {
10425
- return this.newModelInstance(attributes);
10891
+ make(attributes) {
10892
+ return this.newModelInstance(attributes ?? {});
10426
10893
  }
10427
- async create(attributes = {}) {
10428
- const model = this.newModelInstance(attributes);
10894
+ async create(attributes) {
10895
+ const model = this.newModelInstance(attributes ?? {});
10429
10896
  await model.save();
10430
10897
  return model;
10431
10898
  }
10432
- /** Creates without mass assignment protection. Never pass it request input. */
10433
10899
  async forceCreate(attributes) {
10434
10900
  const model = this.newModelInstance().forceFill(attributes);
10435
10901
  await model.save();
10436
10902
  return model;
10437
10903
  }
10438
- /** The first match, or a new unsaved model with attributes + values. */
10439
- async firstOrNew(attributes, values = {}) {
10440
- return await this.clone().where(attributes).first() ?? this.newModelInstance({ ...attributes, ...values });
10904
+ async firstOrNew(attributes, values) {
10905
+ const where = attributes;
10906
+ return await this.clone().where(where).first() ?? this.newModelInstance({ ...where, ...values ?? {} });
10441
10907
  }
10442
- /** The first match, or a new saved model. A concurrent insert of the same unique key returns that row instead. */
10443
- async firstOrCreate(attributes, values = {}) {
10444
- return await this.clone().where(attributes).first() ?? this.createOrFirst(attributes, values);
10908
+ async firstOrCreate(attributes, values) {
10909
+ return await this.clone().where(attributes).first() ?? this.createOrFirst(attributes, values ?? {});
10445
10910
  }
10446
- /** Tries to create; on a unique constraint violation, returns the existing row (Laravel's createOrFirst()). */
10447
- async createOrFirst(attributes, values = {}) {
10911
+ async createOrFirst(attributes, values) {
10912
+ const where = attributes;
10913
+ const extra = values ?? {};
10448
10914
  try {
10449
10915
  const connection = this.connection;
10450
- const create = () => this.create({ ...attributes, ...values });
10916
+ const create = () => this.create({ ...where, ...extra });
10451
10917
  return connection.transactionLevel() > 0 ? await connection.transaction(create) : await create();
10452
10918
  } catch (error) {
10453
10919
  if (!isUniqueViolation(error)) throw error;
10454
- const existing = await this.clone().where(attributes).first();
10920
+ const existing = await this.clone().where(where).first();
10455
10921
  if (!existing) throw error;
10456
10922
  return existing;
10457
10923
  }
10458
10924
  }
10459
- /** Updates the first match with values, or creates it. */
10460
- async updateOrCreate(attributes, values = {}) {
10461
- const model = await this.firstOrCreate(attributes, values);
10462
- if (!model.wasRecentlyCreated) await model.fill(values).save();
10925
+ async updateOrCreate(attributes, values) {
10926
+ const extra = values ?? {};
10927
+ const model = await this.firstOrCreate(attributes, extra);
10928
+ if (!model.wasRecentlyCreated) await model.fill(extra).save();
10463
10929
  return model;
10464
10930
  }
10465
- /** Mass update (no model events); sets updated_at when the model uses timestamps. */
10466
10931
  async update(values) {
10467
10932
  return Builder.prototype.update.call(this.applyScopes(), this.addUpdatedAtColumn(values));
10468
10933
  }
@@ -10695,26 +11160,19 @@ var EloquentCollection = class extends Collection {
10695
11160
  doesntContainStrict(...args) {
10696
11161
  return !Reflect.apply(Collection.prototype.contains, this, args);
10697
11162
  }
10698
- /** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */
10699
11163
  async load(...relations) {
10700
11164
  const first = this.first();
10701
11165
  if (!first || !relations.length) return this;
10702
11166
  await first.newQueryWithoutRelationships().with(...relations).eagerLoadRelations(this.items);
10703
11167
  return this;
10704
11168
  }
10705
- /** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */
10706
11169
  async loadMissing(...relations) {
10707
- await loadMissingOn(this.items, relations);
11170
+ await loadMissingOn(this.items, [...relations]);
10708
11171
  return this;
10709
11172
  }
10710
- /** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */
10711
11173
  loadCount(...relations) {
10712
11174
  return this.loadAggregate(relations, "*", "count");
10713
11175
  }
10714
- /**
10715
- * Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.
10716
- * The values become clean attributes (with their casts: loadExists() gives booleans).
10717
- */
10718
11176
  async loadAggregate(relations, column, fn) {
10719
11177
  const first = this.first();
10720
11178
  if (!first || ![relations].flat().length) return this;
@@ -10730,7 +11188,6 @@ var EloquentCollection = class extends Collection {
10730
11188
  }
10731
11189
  return this;
10732
11190
  }
10733
- /** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */
10734
11191
  loadSum(relations, column) {
10735
11192
  return this.loadAggregate(relations, column, "sum");
10736
11193
  }
@@ -10743,7 +11200,6 @@ var EloquentCollection = class extends Collection {
10743
11200
  loadMax(relations, column) {
10744
11201
  return this.loadAggregate(relations, column, "max");
10745
11202
  }
10746
- /** Adds a boolean <relation>_exists to every model. */
10747
11203
  loadExists(...relations) {
10748
11204
  return this.loadAggregate(relations, "*", "exists");
10749
11205
  }
@@ -10870,7 +11326,7 @@ function resolveMorphClass(type) {
10870
11326
  throw new LogicError(`Class [${type}] not found for a morphTo relation. Add it to Relation.morphMap().`);
10871
11327
  }
10872
11328
  var selfAliases = 0;
10873
- var Relation = class extends Builder2 {
11329
+ var Relation = class _Relation extends Builder2 {
10874
11330
  constructor(related, parent) {
10875
11331
  super(related);
10876
11332
  this.parent = parent;
@@ -10902,11 +11358,15 @@ var Relation = class extends Builder2 {
10902
11358
  aliasSelfTable(query) {
10903
11359
  const table = query.getModel().getTable();
10904
11360
  if (table !== this.parent.getTable()) return void 0;
10905
- const alias = `oriel_reserved_${selfAliases++}`;
11361
+ const alias = _Relation.reserveAlias();
10906
11362
  query.from(`${table} as ${alias}`);
10907
11363
  query.getModel().setTable(alias);
10908
11364
  return alias;
10909
11365
  }
11366
+ /** A new `oriel_reserved_<n>` alias, for a table a query reads twice. */
11367
+ static reserveAlias() {
11368
+ return `oriel_reserved_${selfAliases++}`;
11369
+ }
10910
11370
  /**
10911
11371
  * @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,
10912
11372
  * on the relations that know the column holding the parent's key.
@@ -11165,9 +11625,8 @@ var BelongsToMany = class extends Relation {
11165
11625
  if (this.pivotTimestamps) values[this.pivotTimestamps[1]] = formatDateTime(this.parent.freshTimestamp());
11166
11626
  return this.newPivotQuery().where(this.foreignPivotKey, "=", this.getParentKey()).where(this.relatedPivotKey, "=", this.idOf(id)).update(values);
11167
11627
  }
11168
- /** Saves a new related model and attaches it. */
11169
- async create(attributes = {}, pivotAttributes = {}) {
11170
- const model = this.model.newInstance(attributes);
11628
+ async create(attributes, pivotAttributes = {}) {
11629
+ const model = this.model.newInstance(attributes ?? {});
11171
11630
  await model.save();
11172
11631
  await this.attach(model, pivotAttributes);
11173
11632
  return model;
@@ -11371,10 +11830,11 @@ var HasOneOrMany = class extends Relation {
11371
11830
  for (const model of models) saved.push(await this.save(model));
11372
11831
  return saved;
11373
11832
  }
11833
+ /** One related model per record, in the related model's Eloquent collection. */
11374
11834
  async createMany(records) {
11375
11835
  const created = [];
11376
11836
  for (const record of records) created.push(await this.create(record));
11377
- return created;
11837
+ return this.getRelated().newCollection(created);
11378
11838
  }
11379
11839
  eagerPartitionColumn() {
11380
11840
  return this.foreignKey;
@@ -11568,12 +12028,16 @@ var Factory2 = class _Factory {
11568
12028
  async createOne(attributes = {}) {
11569
12029
  return await this.newInstance({ countValue: void 0 }).create(attributes);
11570
12030
  }
11571
- /** One model per record (or `count` models). */
12031
+ /** One model per record (or `count` models), in the model's Eloquent collection. */
11572
12032
  async createMany(records) {
11573
12033
  const list32 = typeof records === "number" ? Array.from({ length: records }, () => ({})) : records;
11574
12034
  const created = [];
11575
12035
  for (const record of list32) created.push(await this.createOne(record));
11576
- return new Collection(created);
12036
+ return this.collect(created);
12037
+ }
12038
+ /** The models in their own Eloquent collection (the model's newCollection()). */
12039
+ collect(models) {
12040
+ return new this.model().newCollection(models);
11577
12041
  }
11578
12042
  newInstance(changes) {
11579
12043
  const copy = Object.create(Object.getPrototypeOf(this));
@@ -11638,11 +12102,11 @@ var Factory2 = class _Factory {
11638
12102
  return model.getRelationInstance(relationship);
11639
12103
  }
11640
12104
  result(models) {
11641
- return this.countValue === void 0 ? models[0] : new Collection(models);
12105
+ return this.countValue === void 0 ? models[0] : this.collect(models);
11642
12106
  }
11643
12107
  };
11644
12108
  async function discoverFactories(path) {
11645
- if (!existsSync5(path)) return;
12109
+ if (!existsSync6(path)) return;
11646
12110
  for (const file of readdirSync3(path).sort()) {
11647
12111
  if (!/\.(ts|js|mts|mjs)$/.test(file) || /\.d\.[mc]?ts$/.test(file)) continue;
11648
12112
  const module = await import(pathToFileURL3(join43(path, file)).href);
@@ -11708,7 +12172,7 @@ var HasMany = class extends HasOneOrMany {
11708
12172
  }
11709
12173
  };
11710
12174
  var THROUGH_KEY = "laravel_through_key";
11711
- var HasManyThrough = class extends Relation {
12175
+ var HasManyThrough = class _HasManyThrough extends Relation {
11712
12176
  /**
11713
12177
  * @param firstKey on the through table, pointing at the far parent ('users.country_id')
11714
12178
  * @param secondKey on the related table, pointing at the through model ('posts.user_id')
@@ -11722,9 +12186,10 @@ var HasManyThrough = class extends Relation {
11722
12186
  this.secondKey = secondKey;
11723
12187
  this.localKey = localKey;
11724
12188
  this.secondLocalKey = secondLocalKey;
11725
- this.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", this.getQualifiedForeignKeyName());
12189
+ this.throughAlias = throughParent.getTable() === related.getTable() ? _HasManyThrough.reserveAlias() : void 0;
12190
+ this.join(this.throughTable(this.throughAlias), this.getQualifiedParentKeyName(), "=", this.getQualifiedForeignKeyName());
11726
12191
  if (this.throughParent.usesSoftDeletes()) {
11727
- this.withGlobalScope("SoftDeletableHasManyThrough", (query) => query.whereNull(this.throughParent.getQualifiedDeletedAtColumn()));
12192
+ this.withGlobalScope("SoftDeletableHasManyThrough", (query) => query.whereNull(this.throughColumn(this.throughParent.getDeletedAtColumn())));
11728
12193
  }
11729
12194
  this.init();
11730
12195
  }
@@ -11735,9 +12200,22 @@ var HasManyThrough = class extends Relation {
11735
12200
  secondLocalKey;
11736
12201
  /** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */
11737
12202
  throughKeys = /* @__PURE__ */ new WeakMap();
12203
+ /**
12204
+ * The through table's alias when it is the related table too (a person's grandchildren, through their children):
12205
+ * every query of the relation reads it under this name, its keys and soft deletes included.
12206
+ */
12207
+ throughAlias;
12208
+ /** The through table to join: `users`, or `users as <alias>`. */
12209
+ throughTable(alias) {
12210
+ return alias === void 0 ? this.throughParent.getTable() : `${this.throughParent.getTable()} as ${alias}`;
12211
+ }
12212
+ /** A through column, qualified by the through table or by its alias. */
12213
+ throughColumn(column, alias = this.throughAlias) {
12214
+ return alias === void 0 ? this.throughParent.qualifyColumn(column) : `${alias}.${column}`;
12215
+ }
11738
12216
  /** users.country_id */
11739
12217
  getQualifiedFirstKeyName() {
11740
- return this.throughParent.qualifyColumn(this.firstKey);
12218
+ return this.throughColumn(this.firstKey);
11741
12219
  }
11742
12220
  /** posts.user_id */
11743
12221
  getQualifiedForeignKeyName() {
@@ -11745,7 +12223,7 @@ var HasManyThrough = class extends Relation {
11745
12223
  }
11746
12224
  /** users.id */
11747
12225
  getQualifiedParentKeyName() {
11748
- return this.throughParent.qualifyColumn(this.secondLocalKey);
12226
+ return this.throughColumn(this.secondLocalKey);
11749
12227
  }
11750
12228
  /** countries.id */
11751
12229
  getQualifiedLocalKeyName() {
@@ -11770,6 +12248,10 @@ var HasManyThrough = class extends Relation {
11770
12248
  }
11771
12249
  return models;
11772
12250
  }
12251
+ /** An eager limit() or offset() applies to each far parent, by the through table's key to it (Laravel 11). */
12252
+ eagerPartitionColumn() {
12253
+ return this.getQualifiedFirstKeyName();
12254
+ }
11773
12255
  async getResults() {
11774
12256
  const key = this.parent.getAttribute(this.localKey);
11775
12257
  return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
@@ -11792,9 +12274,15 @@ var HasManyThrough = class extends Relation {
11792
12274
  for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
11793
12275
  return models;
11794
12276
  }
12277
+ /**
12278
+ * The query of has()/withCount(), as Laravel's ...ForSelfRelation and ...ForThroughSelfRelation: a related table that
12279
+ * is the parent's is read under an alias, and so is a through table that is the parent's (or the related one).
12280
+ */
11795
12281
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
11796
- query.select(...columns).join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", this.getQualifiedForeignKeyName()).whereColumn(this.getQualifiedLocalKeyName(), "=", this.getQualifiedFirstKeyName());
11797
- if (this.throughParent.usesSoftDeletes()) query.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
12282
+ const related = this.aliasSelfTable(query) ?? query.getModel().getTable();
12283
+ const alias = this.throughAlias ?? (this.throughParent.getTable() === this.parent.getTable() ? _HasManyThrough.reserveAlias() : void 0);
12284
+ query.select(...columns).join(this.throughTable(alias), this.throughColumn(this.secondLocalKey, alias), "=", `${related}.${this.secondKey}`).whereColumn(this.getQualifiedLocalKeyName(), "=", this.throughColumn(this.firstKey, alias));
12285
+ if (this.throughParent.usesSoftDeletes()) query.whereNull(this.throughColumn(this.throughParent.getDeletedAtColumn(), alias));
11798
12286
  return query;
11799
12287
  }
11800
12288
  };
@@ -11912,9 +12400,6 @@ function hasher() {
11912
12400
  return container.make(Hasher);
11913
12401
  }
11914
12402
  var serializing = /* @__PURE__ */ new WeakSet();
11915
- function serializeDate(date) {
11916
- return date.toISOString().replace(/\.(\d{3})Z$/, ".$1000Z");
11917
- }
11918
12403
  var Model = class _Model {
11919
12404
  static CREATED_AT = "created_at";
11920
12405
  static UPDATED_AT = "updated_at";
@@ -12008,8 +12493,8 @@ var Model = class _Model {
12008
12493
  return instance;
12009
12494
  }
12010
12495
  /** A new, unsaved model filled with attributes (mass assignment rules apply). */
12011
- static make(attributes = {}) {
12012
- return new this().fill(attributes);
12496
+ static make(attributes) {
12497
+ return new this().fill(attributes ?? {});
12013
12498
  }
12014
12499
  static addGlobalScope(nameOrScope, implementation) {
12015
12500
  let name;
@@ -12302,20 +12787,20 @@ var Model = class _Model {
12302
12787
  return this.query().lazyById(chunkSize);
12303
12788
  }
12304
12789
  /** Creates and saves a model (mass assignment rules apply). */
12305
- static create(attributes = {}) {
12306
- return this.query().create(attributes);
12790
+ static create(attributes) {
12791
+ return this.query().create(attributes ?? {});
12307
12792
  }
12308
12793
  static forceCreate(attributes) {
12309
12794
  return this.query().forceCreate(attributes);
12310
12795
  }
12311
- static firstOrNew(attributes, values = {}) {
12312
- return this.query().firstOrNew(attributes, values);
12796
+ static firstOrNew(attributes, values) {
12797
+ return this.query().firstOrNew(attributes, values ?? {});
12313
12798
  }
12314
- static firstOrCreate(attributes, values = {}) {
12315
- return this.query().firstOrCreate(attributes, values);
12799
+ static firstOrCreate(attributes, values) {
12800
+ return this.query().firstOrCreate(attributes, values ?? {});
12316
12801
  }
12317
- static updateOrCreate(attributes, values = {}) {
12318
- return this.query().updateOrCreate(attributes, values);
12802
+ static updateOrCreate(attributes, values) {
12803
+ return this.query().updateOrCreate(attributes, values ?? {});
12319
12804
  }
12320
12805
  static factory(count, state) {
12321
12806
  let factory = Factory2.forModel(this);
@@ -12572,6 +13057,7 @@ var Model = class _Model {
12572
13057
  if (value2 === void 0 || value2 === null || value2 === "") this.setAttribute(column, this.newUniqueId());
12573
13058
  }
12574
13059
  }
13060
+ /** The primary key's value: a string, a number or a bigint, or nothing on a model not yet saved. */
12575
13061
  getKey() {
12576
13062
  return this.getAttribute(this.getKeyName());
12577
13063
  }
@@ -12738,9 +13224,9 @@ var Model = class _Model {
12738
13224
  this.pendingHashes.clear();
12739
13225
  }
12740
13226
  /** Fills and saves an existing model. */
12741
- async update(attributes = {}) {
13227
+ async update(attributes) {
12742
13228
  if (!this.exists) return false;
12743
- return this.fill(attributes).save();
13229
+ return this.fill(attributes ?? {}).save();
12744
13230
  }
12745
13231
  /**
12746
13232
  * Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or
@@ -13736,8 +14222,8 @@ var TypeGenerator = class {
13736
14222
  }
13737
14223
  /** Generates and writes the file; returns its path. */
13738
14224
  async write(models) {
13739
- await mkdir3(dirname3(this.options.outputFile), { recursive: true });
13740
- await writeFile3(this.options.outputFile, await this.generate(models));
14225
+ await mkdir3(dirname4(this.options.outputFile), { recursive: true });
14226
+ await writeFile4(this.options.outputFile, await this.generate(models));
13741
14227
  return this.options.outputFile;
13742
14228
  }
13743
14229
  async modelBlock({ name, model, file }) {
@@ -13752,14 +14238,22 @@ var TypeGenerator = class {
13752
14238
  const members = attributes.filter(([column]) => !(column in instance));
13753
14239
  const extra = accessors(model).filter(([attribute2]) => !columns.some((column) => column.name === attribute2) && !(attribute2 in instance));
13754
14240
  const statics = scopes(model).filter(([method]) => !(method in Model));
13755
- const hidden = instance.getHidden().filter((column) => columns.some(({ name: columnName }) => columnName === column));
14241
+ const names = (list32) => list32.map((item) => `'${item}'`).join(" | ");
14242
+ const hidden = instance.getHidden();
14243
+ const visible = instance.getVisible();
14244
+ const appends = instance.getAppends();
13756
14245
  const lines = [
13757
14246
  `declare module '${this.modulePath(file)}' {`,
13758
14247
  ` interface ${name} {`,
13759
14248
  " $attributes?: {",
13760
14249
  ...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),
13761
14250
  " }",
13762
- ...hidden.length ? [` $hidden?: ${hidden.map((column) => `'${column}'`).join(" | ")}`] : [],
14251
+ // The model itself, for its own methods: inside them `this` is a type parameter, and their writes and loads read
14252
+ // the attributes and relations they check from here.
14253
+ ` $self?: ${name}`,
14254
+ ...hidden.length ? [` $hidden?: ${names(hidden)}`] : [],
14255
+ ...visible.length ? [` $visible?: ${names(visible)}`] : [],
14256
+ ...appends.length ? [` $appends?: ${names(appends)}`] : [],
13763
14257
  ...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),
13764
14258
  ...extra.map(([attribute2, method]) => ` ${this.key(attribute2)}: ReturnType<${name}['${method}']>`),
13765
14259
  " }"
@@ -13772,7 +14266,7 @@ var TypeGenerator = class {
13772
14266
  }
13773
14267
  /** '../app/Models/Post' for app/Models/Post.ts, relative to the output file. */
13774
14268
  modulePath(file) {
13775
- const path = relative3(dirname3(this.options.outputFile), file).split(sep2).join("/").replace(/\.(ts|js|mts|mjs)$/, "");
14269
+ const path = relative3(dirname4(this.options.outputFile), file).split(sep3).join("/").replace(/\.(ts|js|mts|mjs)$/, "");
13776
14270
  return path.startsWith(".") ? path : `./${path}`;
13777
14271
  }
13778
14272
  key(name) {
@@ -13817,7 +14311,7 @@ async function generateModelTypes(context) {
13817
14311
  if (!context.models) return void 0;
13818
14312
  const outputFile = context.app.basePath(join7("types", "models.d.ts"));
13819
14313
  await new TypeGenerator({ outputFile, importSource: context.typesImportSource }).write((await context.models()).all());
13820
- return relative22(context.app.basePath(), outputFile);
14314
+ return relative23(context.app.basePath(), outputFile);
13821
14315
  }
13822
14316
  async function writeModelTypes(context, command) {
13823
14317
  if (context.app.isProduction() || !existsSync42(context.app.basePath("types"))) return;
@@ -13908,7 +14402,7 @@ function registerMigrationCommands(kernel, context) {
13908
14402
  table: text(command.option("table")),
13909
14403
  importSource: context.stubsImportSource
13910
14404
  });
13911
- command.info(`Migration [${relative22(context.app.basePath(), file)}] created successfully.`);
14405
+ command.info(`Migration [${relative23(context.app.basePath(), file)}] created successfully.`);
13912
14406
  return 0;
13913
14407
  });
13914
14408
  }
@@ -14379,7 +14873,7 @@ function databaseConfigDefaults(app2) {
14379
14873
  }
14380
14874
  };
14381
14875
  }
14382
- function currentRequest2() {
14876
+ function currentRequest() {
14383
14877
  const container = currentContainer();
14384
14878
  if (!container?.bound(HttpRequest)) return void 0;
14385
14879
  try {
@@ -14399,15 +14893,15 @@ function paginationState() {
14399
14893
  }
14400
14894
  }
14401
14895
  function usePaginationResolvers() {
14402
- AbstractPaginator.currentPathResolver = () => paginationState()?.currentPath() ?? currentRequest2()?.url() ?? "/";
14896
+ AbstractPaginator.currentPathResolver = () => paginationState()?.currentPath() ?? currentRequest()?.url() ?? "/";
14403
14897
  AbstractPaginator.currentPageResolver = (pageName) => {
14404
14898
  const state = paginationState()?.currentPage(pageName);
14405
14899
  if (state !== void 0) return state;
14406
- const page = Number(currentRequest2()?.input(pageName));
14900
+ const page = Number(currentRequest()?.input(pageName));
14407
14901
  return Number.isInteger(page) && page >= 1 ? page : 1;
14408
14902
  };
14409
- AbstractPaginator.queryStringResolver = () => currentRequest2()?.query() ?? {};
14410
- AbstractPaginator.currentCursorResolver = (cursorName) => currentRequest2()?.input(cursorName);
14903
+ AbstractPaginator.queryStringResolver = () => currentRequest()?.query() ?? {};
14904
+ AbstractPaginator.currentCursorResolver = (cursorName) => currentRequest()?.input(cursorName);
14411
14905
  }
14412
14906
  var DatabaseServiceProvider = class extends ServiceProvider {
14413
14907
  register() {
@@ -14444,7 +14938,7 @@ var DatabaseServiceProvider = class extends ServiceProvider {
14444
14938
 
14445
14939
  // ../Encryption/dist/index.js
14446
14940
  import { createCipheriv, createDecipheriv, createHmac as createHmac6, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual5 } from "crypto";
14447
- import { readFile as readFile2, writeFile as writeFile4 } from "fs/promises";
14941
+ import { readFile as readFile3, writeFile as writeFile5 } from "fs/promises";
14448
14942
  var EncryptionFailure = class extends Error {
14449
14943
  kind = "Server";
14450
14944
  status = 500;
@@ -14631,13 +15125,13 @@ function keyGenerateHandler(app2) {
14631
15125
  return 1;
14632
15126
  }
14633
15127
  const path = app2.basePath(".env");
14634
- const contents = await readFile2(path, "utf8").catch(() => void 0);
15128
+ const contents = await readFile3(path, "utf8").catch(() => void 0);
14635
15129
  const pattern = /^APP_KEY=.*$/m;
14636
15130
  if (contents === void 0 || !pattern.test(contents)) {
14637
15131
  this.error("Unable to set application key. No APP_KEY variable was found in the .env file.");
14638
15132
  return 1;
14639
15133
  }
14640
- await writeFile4(path, contents.replace(pattern, () => `APP_KEY=${key}`));
15134
+ await writeFile5(path, contents.replace(pattern, () => `APP_KEY=${key}`));
14641
15135
  config2.set("app.key", key);
14642
15136
  app2.forgetInstance(Encrypter);
14643
15137
  this.info("Application key set successfully.");
@@ -14673,7 +15167,7 @@ var EncryptionServiceProvider = class extends ServiceProvider {
14673
15167
  };
14674
15168
 
14675
15169
  // ../Events/dist/index.js
14676
- import { existsSync as existsSync6, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
15170
+ import { existsSync as existsSync7, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
14677
15171
  import { join as join10 } from "path";
14678
15172
  import { pathToFileURL as pathToFileURL5 } from "url";
14679
15173
  var InvalidListenerError = class extends Error {
@@ -14715,6 +15209,7 @@ var CallQueuedListener = class {
14715
15209
  tries;
14716
15210
  backoff;
14717
15211
  timeout;
15212
+ afterCommit;
14718
15213
  /** A fresh listener instance, resolved through the container (never called with constructor arguments — DI only). */
14719
15214
  resolve() {
14720
15215
  const registry2 = inject(ClassRegistry);
@@ -14754,7 +15249,7 @@ function files(directory) {
14754
15249
  var isDiscoverableListener = (value2) => typeof value2 === "function" && typeof value2.prototype?.handle === "function" && "listensTo" in value2;
14755
15250
  var discoveredByDispatcher = /* @__PURE__ */ new WeakMap();
14756
15251
  async function discoverListeners(directory, dispatcher, registry2) {
14757
- if (!existsSync6(directory)) return [];
15252
+ if (!existsSync7(directory)) return [];
14758
15253
  let discovered = discoveredByDispatcher.get(dispatcher);
14759
15254
  if (!discovered) {
14760
15255
  discovered = /* @__PURE__ */ new WeakSet();
@@ -14786,6 +15281,7 @@ function isListenerClass(value2) {
14786
15281
  }
14787
15282
  var SHOULD_QUEUE22 = /* @__PURE__ */ Symbol.for("oriel:bus.shouldQueue");
14788
15283
  var QUEUE_OPTION_KEYS = ["connection", "queue", "delay", "tries", "backoff", "timeout"];
15284
+ var COPIED_OPTION_KEYS = [...QUEUE_OPTION_KEYS, "afterCommit"];
14789
15285
  function isQueueableListener(cls, instance) {
14790
15286
  const members = instance;
14791
15287
  const statics = cls;
@@ -14802,13 +15298,14 @@ var VALIDATORS = {
14802
15298
  delay: isNumber,
14803
15299
  tries: isNumber,
14804
15300
  timeout: isNumber,
14805
- backoff: isNumberOrNumberArray
15301
+ backoff: isNumberOrNumberArray,
15302
+ afterCommit: (value2) => typeof value2 === "boolean"
14806
15303
  };
14807
15304
  function queueOptionsOf(cls, instance) {
14808
15305
  const statics = cls;
14809
15306
  const members = instance;
14810
15307
  const options = {};
14811
- for (const key of QUEUE_OPTION_KEYS) {
15308
+ for (const key of COPIED_OPTION_KEYS) {
14812
15309
  let value2;
14813
15310
  let onInstance = true;
14814
15311
  if (members[key] !== void 0) value2 = members[key];
@@ -14835,8 +15332,8 @@ function uniqueSpecOf(cls, instance, name, data) {
14835
15332
  if (found === void 0) return void 0;
14836
15333
  return typeof found.value === "function" ? found.value.apply(found.on, data) : found.value;
14837
15334
  };
14838
- const declared = typeof read2("uniqueId")?.value === "function" || read2("uniqueFor") !== void 0 || read2("uniqueUntilProcessing")?.value === true || typeof read2("uniqueVia")?.value === "function";
14839
- if (!declared) return void 0;
15335
+ const declared2 = typeof read2("uniqueId")?.value === "function" || read2("uniqueFor") !== void 0 || read2("uniqueUntilProcessing")?.value === true || typeof read2("uniqueVia")?.value === "function";
15336
+ if (!declared2) return void 0;
14840
15337
  const id = typeof read2("uniqueId")?.value === "function" ? resolve5("uniqueId") : void 0;
14841
15338
  const spec = { name, id: id === void 0 || id === null ? "" : String(id) };
14842
15339
  const uniqueFor = resolve5("uniqueFor");
@@ -15006,13 +15503,14 @@ var EventServiceProvider = class extends ServiceProvider {
15006
15503
 
15007
15504
  // ../Filesystem/dist/index.js
15008
15505
  import { createReadStream, createWriteStream } from "fs";
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";
15010
- import { dirname as dirname4, extname as extname2, resolve as resolve2 } from "path";
15506
+ import { chmod, copyFile, mkdir as mkdir4, readFile as readFile4, readdir as readdir2, rename as rename2, rm as rm2, stat as stat2, writeFile as writeFile6 } from "fs/promises";
15507
+ import { dirname as dirname5, extname as extname2, resolve as resolve2 } from "path";
15011
15508
  import { Readable } from "stream";
15012
15509
  import { pipeline } from "stream/promises";
15013
- import { resolve, sep as sep3 } from "path";
15510
+ import { resolve, sep as sep4 } from "path";
15014
15511
  import { posix } from "path";
15015
15512
  import { posix as posix2 } from "path";
15513
+ import { basename as basename2 } from "path";
15016
15514
  import { lstat, mkdir as mkdir23, symlink, unlink } from "fs/promises";
15017
15515
  import { dirname as dirname23, relative as relative4 } from "path";
15018
15516
  var PathTraversalError = class extends Error {
@@ -15126,7 +15624,7 @@ function mimeFromExtension(extension) {
15126
15624
  function resolveDiskPath(root, path) {
15127
15625
  const resolvedRoot = resolve(root);
15128
15626
  const resolved = resolve(resolvedRoot, path);
15129
- if (resolved !== resolvedRoot && !resolved.startsWith(resolvedRoot + sep3)) {
15627
+ if (resolved !== resolvedRoot && !resolved.startsWith(resolvedRoot + sep4)) {
15130
15628
  throw new PathTraversalError(path);
15131
15629
  }
15132
15630
  return resolved;
@@ -15144,11 +15642,14 @@ function encodeKey(key) {
15144
15642
  var FILE_MODE = { public: 420, private: 384 };
15145
15643
  var DIR_MODE = { public: 493, private: 448 };
15146
15644
  var LocalFilesystem = class {
15147
- constructor(config2) {
15645
+ /** `disk` is the disk's name in config('filesystems.disks'), which names its `storage.<disk>` route. */
15646
+ constructor(config2, disk) {
15148
15647
  this.config = config2;
15648
+ this.disk = disk;
15149
15649
  this.root = resolve2(config2.root);
15150
15650
  }
15151
15651
  config;
15652
+ disk;
15152
15653
  root;
15153
15654
  resolve(path) {
15154
15655
  return resolveDiskPath(this.root, path);
@@ -15172,15 +15673,24 @@ var LocalFilesystem = class {
15172
15673
  async missing(path) {
15173
15674
  return !await this.exists(path);
15174
15675
  }
15676
+ /** Whether a file (not a directory) is at the path. */
15677
+ async fileExists(path) {
15678
+ const full = this.resolve(path);
15679
+ try {
15680
+ return (await stat2(full)).isFile();
15681
+ } catch {
15682
+ return false;
15683
+ }
15684
+ }
15175
15685
  async get(path) {
15176
15686
  const full = this.resolve(path);
15177
15687
  await this.statOrThrow(path, full);
15178
- return readFile3(full, "utf8");
15688
+ return readFile4(full, "utf8");
15179
15689
  }
15180
15690
  async getBytes(path) {
15181
15691
  const full = this.resolve(path);
15182
15692
  await this.statOrThrow(path, full);
15183
- return new Uint8Array(await readFile3(full));
15693
+ return new Uint8Array(await readFile4(full));
15184
15694
  }
15185
15695
  async readStream(path) {
15186
15696
  const full = this.resolve(path);
@@ -15189,11 +15699,11 @@ var LocalFilesystem = class {
15189
15699
  }
15190
15700
  async put(path, contents, options) {
15191
15701
  const full = this.resolve(path);
15192
- await mkdir4(dirname4(full), { recursive: true });
15702
+ await mkdir4(dirname5(full), { recursive: true });
15193
15703
  if (contents instanceof ReadableStream) {
15194
15704
  await pipeline(Readable.fromWeb(contents), createWriteStream(full));
15195
15705
  } else {
15196
- await writeFile5(full, contents);
15706
+ await writeFile6(full, contents);
15197
15707
  }
15198
15708
  await this.applyVisibility(full, options?.visibility, "file");
15199
15709
  return true;
@@ -15217,7 +15727,7 @@ var LocalFilesystem = class {
15217
15727
  const fromFull = this.resolve(from);
15218
15728
  const toFull = this.resolve(to);
15219
15729
  await this.statOrThrow(from, fromFull);
15220
- await mkdir4(dirname4(toFull), { recursive: true });
15730
+ await mkdir4(dirname5(toFull), { recursive: true });
15221
15731
  await copyFile(fromFull, toFull);
15222
15732
  return true;
15223
15733
  }
@@ -15225,7 +15735,7 @@ var LocalFilesystem = class {
15225
15735
  const fromFull = this.resolve(from);
15226
15736
  const toFull = this.resolve(to);
15227
15737
  await this.statOrThrow(from, fromFull);
15228
- await mkdir4(dirname4(toFull), { recursive: true });
15738
+ await mkdir4(dirname5(toFull), { recursive: true });
15229
15739
  try {
15230
15740
  await rename2(fromFull, toFull);
15231
15741
  } catch (error) {
@@ -15252,8 +15762,13 @@ var LocalFilesystem = class {
15252
15762
  if (!this.config.url) throw new UnsupportedOperationError("url", 'this disk has no "url" configured');
15253
15763
  return `${this.config.url.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
15254
15764
  }
15255
- async temporaryUrl(_path, _expiresAt) {
15256
- throw new UnsupportedOperationError("temporaryUrl", "local disks cannot generate signed URLs; configure the s3 disk");
15765
+ /** A link to the disk's `storage.<disk>` route, signed over its path and query, that works until `expiresAt`. */
15766
+ async temporaryUrl(path, expiresAt) {
15767
+ if (this.config.serve !== true || this.disk === void 0) {
15768
+ throw new UnsupportedOperationError("temporaryUrl", "this local disk is not served: set serve: true on it in config/filesystems.ts");
15769
+ }
15770
+ const urls = app(UrlGenerator);
15771
+ return urls.to(urls.temporarySignedRoute(`storage.${this.disk}`, expiresAt, { path }, false));
15257
15772
  }
15258
15773
  async files(directory = "", recursive = false) {
15259
15774
  return this.walk(directory, recursive, "file");
@@ -15715,11 +16230,15 @@ var FilesystemManager2 = class {
15715
16230
  this.container = container;
15716
16231
  this.drivers.set(
15717
16232
  "local",
15718
- (config2) => new LocalFilesystem({
15719
- root: String(config2.root ?? ""),
15720
- url: config2.url,
15721
- visibility: config2.visibility
15722
- })
16233
+ (config2, name) => new LocalFilesystem(
16234
+ {
16235
+ root: String(config2.root ?? ""),
16236
+ url: config2.url,
16237
+ visibility: config2.visibility,
16238
+ serve: config2.serve === true
16239
+ },
16240
+ name
16241
+ )
15723
16242
  );
15724
16243
  this.drivers.set("s3", (config2) => new S3Filesystem(() => this.buildS3Client(config2), this.s3Config(config2)));
15725
16244
  this.drivers.set("vercel-blob", (config2) => {
@@ -15768,7 +16287,7 @@ var FilesystemManager2 = class {
15768
16287
  const driverName = diskConfig.driver;
15769
16288
  const driver = driverName ? this.drivers.get(driverName) : void 0;
15770
16289
  if (!driver) throw new UnknownFilesystemDriverError(String(driverName));
15771
- disk = driver(diskConfig);
16290
+ disk = driver(diskConfig, diskName);
15772
16291
  this.disks.set(diskName, disk);
15773
16292
  }
15774
16293
  return disk;
@@ -15840,12 +16359,71 @@ var FilesystemManager2 = class {
15840
16359
  return this.disk().path(path);
15841
16360
  }
15842
16361
  };
16362
+ var ServeFileError = class extends Error {
16363
+ constructor(status) {
16364
+ super("");
16365
+ this.status = status;
16366
+ this.name = "ServeFileError";
16367
+ }
16368
+ status;
16369
+ kind = "Http";
16370
+ };
16371
+ var HEADERS = {
16372
+ "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
16373
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
16374
+ "X-Content-Type-Options": "nosniff"
16375
+ };
16376
+ function inline(name) {
16377
+ const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
16378
+ return ascii === name ? `inline; filename="${name}"` : `inline; filename="${ascii}"; filename*=utf-8''${encodeURIComponent(name)}`;
16379
+ }
16380
+ var ServeFile = class {
16381
+ constructor(disk, config2, isProduction) {
16382
+ this.disk = disk;
16383
+ this.config = config2;
16384
+ this.isProduction = isProduction;
16385
+ }
16386
+ disk;
16387
+ config;
16388
+ isProduction;
16389
+ async handle(request2, path) {
16390
+ if (!this.hasValidSignature(request2)) throw new ServeFileError(this.isProduction ? 404 : 403);
16391
+ const disk = app(FilesystemManager).disk(this.disk);
16392
+ try {
16393
+ const found = disk instanceof LocalFilesystem ? await disk.fileExists(path) : await disk.exists(path);
16394
+ if (!found) throw new ServeFileError(404);
16395
+ const [stream, type, size] = await Promise.all([disk.readStream(path), disk.mimeType(path), disk.size(path)]);
16396
+ return new Response(stream, {
16397
+ headers: { ...HEADERS, "Content-Type": type ?? "application/octet-stream", "Content-Length": String(size), "Content-Disposition": inline(basename2(path)) }
16398
+ });
16399
+ } catch (error) {
16400
+ if (error instanceof PathTraversalError) throw new ServeFileError(404);
16401
+ throw error;
16402
+ }
16403
+ }
16404
+ hasValidSignature(request2) {
16405
+ return (this.config.visibility ?? "private") === "public" || app(UrlGenerator).hasValidSignature(request2, false);
16406
+ }
16407
+ };
16408
+ function servedPath(config2) {
16409
+ if (typeof config2.url !== "string" || config2.url === "") return "/storage";
16410
+ return new URL(config2.url, "http://localhost").pathname.replace(/\/+$/, "");
16411
+ }
16412
+ function serveFiles(application, router) {
16413
+ const disks = application.make(ConfigRepository).get("filesystems.disks", {}) ?? {};
16414
+ const production = application.isProduction();
16415
+ for (const [name, config2] of Object.entries(disks)) {
16416
+ if (config2.driver !== "local" || config2.serve !== true) continue;
16417
+ const file = new ServeFile(name, config2, production);
16418
+ router.get(`${servedPath(config2)}/{path}`, (path) => file.handle(app(HttpRequest), path)).where("path", ".*").name(`storage.${name}`);
16419
+ }
16420
+ }
15843
16421
  var STORAGE_LINK_SIGNATURE = "storage:link {--relative : Create the symbolic link using relative paths} {--force : Recreate an existing symbolic link}";
15844
- function storageLinkHandler(app2) {
16422
+ function storageLinkHandler(app3) {
15845
16423
  return async function() {
15846
16424
  const option = (name) => this.option(name) === true;
15847
- const link2 = app2.publicPath("storage");
15848
- const target = app2.storagePath("app/public");
16425
+ const link2 = app3.publicPath("storage");
16426
+ const target = app3.storagePath("app/public");
15849
16427
  try {
15850
16428
  const stats = await lstat(link2);
15851
16429
  if (!option("force")) {
@@ -15866,8 +16444,8 @@ function storageLinkHandler(app2) {
15866
16444
  return 0;
15867
16445
  };
15868
16446
  }
15869
- function registerStorageLinkCommand(kernel, app2) {
15870
- kernel.command(STORAGE_LINK_SIGNATURE, storageLinkHandler(app2)).purpose("Create the symbolic links configured for the application");
16447
+ function registerStorageLinkCommand(kernel, app3) {
16448
+ kernel.command(STORAGE_LINK_SIGNATURE, storageLinkHandler(app3)).purpose("Create the symbolic links configured for the application");
15871
16449
  }
15872
16450
  var FilesystemServiceProvider = class extends ServiceProvider {
15873
16451
  register() {
@@ -15903,6 +16481,7 @@ var FilesystemServiceProvider = class extends ServiceProvider {
15903
16481
  }
15904
16482
  boot() {
15905
16483
  if (this.app.bound(ConsoleKernel)) registerStorageLinkCommand(this.app.make(ConsoleKernel), this.app);
16484
+ if (this.app.bound(Router)) serveFiles(this.app, this.app.make(Router));
15906
16485
  }
15907
16486
  };
15908
16487
 
@@ -16092,14 +16671,14 @@ var HashingServiceProvider = class extends ServiceProvider {
16092
16671
  };
16093
16672
 
16094
16673
  // ../Inertia/dist/index.js
16095
- import { existsSync as existsSync7, readdirSync as readdirSync5 } from "fs";
16096
- import { join as join11, relative as relative5, sep as sep4 } from "path";
16674
+ import { existsSync as existsSync8, readdirSync as readdirSync5 } from "fs";
16675
+ import { join as join11, relative as relative5, sep as sep5 } from "path";
16097
16676
  import { createHash as createHash7 } from "crypto";
16098
16677
  import { existsSync as existsSync24, readFileSync } from "fs";
16099
16678
  import { spawn as spawn2 } from "child_process";
16100
16679
  import { existsSync as existsSync33 } from "fs";
16101
- import { mkdir as mkdir5, writeFile as writeFile6 } from "fs/promises";
16102
- import { dirname as dirname5, isAbsolute as isAbsolute2, join as join24, relative as relative23 } from "path";
16680
+ import { mkdir as mkdir5, writeFile as writeFile7 } from "fs/promises";
16681
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join24, relative as relative24 } from "path";
16103
16682
  import { existsSync as existsSync43, readFileSync as readFileSync2 } from "fs";
16104
16683
  var Header = {
16105
16684
  INERTIA: "X-Inertia",
@@ -16395,6 +16974,7 @@ var isContainer = (value2) => {
16395
16974
  var entriesOf = (value2) => Array.isArray(value2) ? value2.map((item, index) => [String(index), item]) : Object.entries(value2);
16396
16975
  var PropsResolver = class {
16397
16976
  constructor(request2, component, options = {}) {
16977
+ this.request = request2;
16398
16978
  this.options = options;
16399
16979
  this.#isPartial = request2.header(Header.PARTIAL_COMPONENT) === component;
16400
16980
  const inertia2 = request2.header(Header.INERTIA);
@@ -16405,6 +16985,7 @@ var PropsResolver = class {
16405
16985
  this.#loadedOnce = parseList(request2.header(Header.EXCEPT_ONCE_PROPS)) ?? [];
16406
16986
  this.#mergeIntent = request2.header(Header.INFINITE_SCROLL_MERGE_INTENT);
16407
16987
  }
16988
+ request;
16408
16989
  options;
16409
16990
  #isPartial;
16410
16991
  #isInertia;
@@ -16511,22 +17092,28 @@ var PropsResolver = class {
16511
17092
  #wasAlreadyLoadedByClient(prop, path) {
16512
17093
  return prop.shouldResolveOnce() && !prop.shouldBeRefreshed() && this.#loadedOnce.includes(prop.getKey() ?? path);
16513
17094
  }
17095
+ /** A resource's response body, else what toJSON() gives, else the object itself. */
17096
+ #serialize(value2) {
17097
+ const candidate = value2;
17098
+ if (typeof candidate.toResponseBody === "function") return candidate.toResponseBody(this.request);
17099
+ if (typeof candidate.toJSON === "function") return candidate.toJSON();
17100
+ return value2;
17101
+ }
16514
17102
  /** Callbacks and prop types run; objects with toJSON() (models, collections, paginators, dates) serialize. */
16515
17103
  async #resolveValue(value2, path) {
16516
17104
  if (value2 instanceof ScrollProp) value2.configureMergeIntent(this.#mergeIntent);
16517
- const rescue = isProp(value2) && value2.shouldRescue();
17105
+ const rescue2 = isProp(value2) && value2.shouldRescue();
16518
17106
  try {
16519
17107
  let resolved = value2;
16520
17108
  if (isProp(resolved)) resolved = await resolved.resolve();
16521
17109
  else if (typeof resolved === "function") resolved = await resolved();
16522
17110
  else if (resolved instanceof Promise) resolved = await resolved;
16523
17111
  if (!isProp(resolved) && typeof resolved === "object" && resolved !== null && !Array.isArray(resolved)) {
16524
- const serializable = resolved;
16525
- if (typeof serializable.toJSON === "function") resolved = serializable.toJSON();
17112
+ resolved = this.#serialize(resolved);
16526
17113
  }
16527
17114
  return resolved;
16528
17115
  } catch (error) {
16529
- if (!rescue) throw error;
17116
+ if (!rescue2) throw error;
16530
17117
  await this.options.report?.(error);
16531
17118
  this.#rescued.push(path);
16532
17119
  return null;
@@ -16592,9 +17179,7 @@ var PropsResolver = class {
16592
17179
  if (current[segment] === void 0 || current[segment] === null) return;
16593
17180
  if (typeof current[segment] === "function") current[segment] = await current[segment]();
16594
17181
  const value2 = current[segment];
16595
- if (typeof value2 === "object" && value2 !== null && !isContainer(value2) && typeof value2.toJSON === "function") {
16596
- current[segment] = value2.toJSON();
16597
- }
17182
+ if (typeof value2 === "object" && value2 !== null && !isContainer(value2)) current[segment] = this.#serialize(value2);
16598
17183
  const walked = current[segment];
16599
17184
  if (typeof walked !== "object" || walked === null) return;
16600
17185
  current[segment] = Array.isArray(walked) ? [...walked] : Object.assign(Object.create(Object.getPrototypeOf(walked)), walked);
@@ -16602,15 +17187,15 @@ var PropsResolver = class {
16602
17187
  }
16603
17188
  }
16604
17189
  };
16605
- function requestScope2() {
17190
+ function requestScope() {
16606
17191
  const container = currentContainer();
16607
17192
  return container !== void 0 && container.bound(HttpRequest) ? container : void 0;
16608
17193
  }
16609
- function currentRequest3() {
16610
- return requestScope2()?.make(HttpRequest);
17194
+ function currentRequest2() {
17195
+ return requestScope()?.make(HttpRequest);
16611
17196
  }
16612
- function optionalSession2() {
16613
- const scope = requestScope2();
17197
+ function optionalSession() {
17198
+ const scope = requestScope();
16614
17199
  return scope?.bound(Session) ? scope.make(Session) : void 0;
16615
17200
  }
16616
17201
  function isInertiaRequest(request2) {
@@ -16700,7 +17285,7 @@ var Response2 = class {
16700
17285
  }
16701
17286
  /** The page object for this request. */
16702
17287
  async toPage(request2) {
16703
- const scope = requestScope2();
17288
+ const scope = requestScope();
16704
17289
  this.#ensurePageExists(scope);
16705
17290
  const resolver2 = new PropsResolver(request2, this.component, {
16706
17291
  exposeSharedPropKeys: this.#config(scope, "inertia.expose_shared_prop_keys", true),
@@ -16709,7 +17294,7 @@ var Response2 = class {
16709
17294
  }
16710
17295
  });
16711
17296
  const { props, metadata } = await resolver2.resolve(this.settings.shared, this.#props);
16712
- const session2 = optionalSession2();
17297
+ const session2 = optionalSession();
16713
17298
  const clearHistory = session2?.pull(SessionKey.CLEAR_HISTORY, false) === true;
16714
17299
  const preserveFragment = session2?.pull(SessionKey.PRESERVE_FRAGMENT, false) === true;
16715
17300
  const flash = session2?.pull(SessionKey.FLASH_DATA, void 0);
@@ -16736,7 +17321,7 @@ var Response2 = class {
16736
17321
  headers: { "content-type": "application/json", "X-Inertia": "true" }
16737
17322
  });
16738
17323
  }
16739
- const scope = requestScope2();
17324
+ const scope = requestScope();
16740
17325
  if (scope === void 0 || !scope.bound(ViewFactory)) {
16741
17326
  throw new InertiaError(`Cannot render the Inertia root view [${this.#rootView}]: no ViewFactory is bound.`);
16742
17327
  }
@@ -16758,20 +17343,20 @@ function pageNames(paths, extensions) {
16758
17343
  const byLength = [...extensions].sort((a, b) => b.length - a.length);
16759
17344
  const pages = /* @__PURE__ */ new Map();
16760
17345
  for (const path of paths) {
16761
- if (!existsSync7(path)) continue;
17346
+ if (!existsSync8(path)) continue;
16762
17347
  for (const entry of readdirSync5(path, { recursive: true, withFileTypes: true })) {
16763
17348
  if (!entry.isFile()) continue;
16764
17349
  const file = join11(entry.parentPath, entry.name);
16765
17350
  const extension = byLength.find((candidate) => entry.name.endsWith(`.${candidate}`));
16766
17351
  if (extension === void 0) continue;
16767
- const name = relative5(path, file).slice(0, -(extension.length + 1)).split(sep4).join("/");
17352
+ const name = relative5(path, file).slice(0, -(extension.length + 1)).split(sep5).join("/");
16768
17353
  if (!pages.has(name)) pages.set(name, file);
16769
17354
  }
16770
17355
  }
16771
17356
  return [...pages].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, file]) => ({ name, file }));
16772
17357
  }
16773
17358
  function pageExists(component, paths, extensions) {
16774
- return paths.some((path) => extensions.some((extension) => existsSync7(join11(path, `${component}.${extension}`))));
17359
+ return paths.some((path) => extensions.some((extension) => existsSync8(join11(path, `${component}.${extension}`))));
16775
17360
  }
16776
17361
  var ResponseFactory = class _ResponseFactory {
16777
17362
  constructor(app2, parent) {
@@ -16836,10 +17421,10 @@ var ResponseFactory = class _ResponseFactory {
16836
17421
  this.#encryptHistory = encrypt2;
16837
17422
  }
16838
17423
  clearHistory() {
16839
- optionalSession2()?.put(SessionKey.CLEAR_HISTORY, true);
17424
+ optionalSession()?.put(SessionKey.CLEAR_HISTORY, true);
16840
17425
  }
16841
17426
  preserveFragment() {
16842
- optionalSession2()?.put(SessionKey.PRESERVE_FRAGMENT, true);
17427
+ optionalSession()?.put(SessionKey.PRESERVE_FRAGMENT, true);
16843
17428
  }
16844
17429
  optional(callback) {
16845
17430
  return new OptionalProp(callback);
@@ -16864,19 +17449,19 @@ var ResponseFactory = class _ResponseFactory {
16864
17449
  }
16865
17450
  /** Flashes page.flash data for the next Inertia response (stored in the session immediately). */
16866
17451
  flash(key, value2) {
16867
- const session2 = optionalSession2();
17452
+ const session2 = optionalSession();
16868
17453
  if (session2 === void 0) return this;
16869
17454
  const flash = typeof key === "string" ? { [key]: value2 } : key;
16870
17455
  session2.flash(SessionKey.FLASH_DATA, { ...session2.get(SessionKey.FLASH_DATA, {}), ...flash });
16871
17456
  return this;
16872
17457
  }
16873
17458
  back(fallback, status = 302) {
16874
- const scope = requestScope2() ?? this.app;
17459
+ const scope = requestScope() ?? this.app;
16875
17460
  return scope.make(Redirector).back(fallback, status);
16876
17461
  }
16877
17462
  /** 409 + X-Inertia-Location for Inertia requests (the client does a full visit), a plain 302 otherwise. */
16878
17463
  location(url2) {
16879
- const request2 = currentRequest3();
17464
+ const request2 = currentRequest2();
16880
17465
  if (request2 !== void 0 && isInertiaRequest(request2)) {
16881
17466
  return new globalThis.Response(null, { status: 409, headers: { [Header.LOCATION]: url2 } });
16882
17467
  }
@@ -17010,7 +17595,7 @@ var InertiaMiddleware = class {
17010
17595
  const vary2 = (response2.headers.get("Vary") ?? "").split(",").map((value2) => value2.trim()).filter((value2) => value2 !== "" && value2 !== "X-Inertia");
17011
17596
  response2 = rebuild2(response2, { headers: { Vary: [...vary2, "X-Inertia"].join(", ") } });
17012
17597
  const redirect2 = isRedirect(response2);
17013
- const session2 = optionalSession2();
17598
+ const session2 = optionalSession();
17014
17599
  if (redirect2 && session2 !== void 0) this.reflash(session2);
17015
17600
  if (!isInertiaRequest(request2)) return response2;
17016
17601
  if (session2 !== void 0 && this.shouldStoreCurrentUrl(request2, response2)) session2.setPreviousUrl(request2.fullUrl());
@@ -17026,7 +17611,7 @@ var InertiaMiddleware = class {
17026
17611
  }
17027
17612
  /** The session's flashed errors ({ [bag]: { field: string[] } }), shaped for the client. */
17028
17613
  resolveValidationErrors(request2) {
17029
- const flashed = optionalSession2()?.get("errors", void 0);
17614
+ const flashed = optionalSession()?.get("errors", void 0);
17030
17615
  if (flashed === void 0 || flashed === null || typeof flashed !== "object") return {};
17031
17616
  const bags = Object.fromEntries(
17032
17617
  Object.entries(flashed).map(([bag, fields]) => [
@@ -17059,7 +17644,7 @@ var InertiaMiddleware = class {
17059
17644
  return new Response(null, { status: 409, headers: { [Header.REDIRECT]: response2.headers.get("Location") ?? "" } });
17060
17645
  }
17061
17646
  async onVersionChange(request2, _response) {
17062
- optionalSession2()?.reflash();
17647
+ optionalSession()?.reflash();
17063
17648
  const inertia2 = this.container.make(InertiaFactory);
17064
17649
  const response2 = inertia2.location(request2.fullUrl());
17065
17650
  return rebuild2(response2, { headers: { [Header.VERSION]: await inertia2.getVersion() } });
@@ -17119,6 +17704,15 @@ var PrecognitiveValidator = class {
17119
17704
  await this.validator.validated();
17120
17705
  throw new PrecognitionPassed();
17121
17706
  }
17707
+ async safe() {
17708
+ this.reached();
17709
+ await this.validator.validated();
17710
+ throw new PrecognitionPassed();
17711
+ }
17712
+ stopOnFirstFailure(stop = true) {
17713
+ this.validator.stopOnFirstFailure(stop);
17714
+ return this;
17715
+ }
17122
17716
  errors() {
17123
17717
  return this.validator.errors();
17124
17718
  }
@@ -17130,6 +17724,12 @@ var PrecognitiveValidator = class {
17130
17724
  return this;
17131
17725
  }
17132
17726
  };
17727
+ function shouldValidate(attribute2, fields) {
17728
+ return fields.some((field) => {
17729
+ const pattern = field.split("*").map((part2) => part2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^.]+");
17730
+ return new RegExp(`^${pattern}$`).test(attribute2);
17731
+ });
17732
+ }
17133
17733
  var PrecognitiveValidationFactory = class {
17134
17734
  constructor(factory, only) {
17135
17735
  this.factory = factory;
@@ -17140,7 +17740,7 @@ var PrecognitiveValidationFactory = class {
17140
17740
  reached = false;
17141
17741
  make(data, rules, messages, attributes) {
17142
17742
  const only = this.only;
17143
- const filtered = only === void 0 ? rules : Object.fromEntries(Object.entries(rules).filter(([attribute2]) => only.includes(attribute2)));
17743
+ const filtered = only === void 0 ? rules : Object.fromEntries(Object.entries(rules).filter(([attribute2]) => shouldValidate(attribute2, only)));
17144
17744
  return new PrecognitiveValidator(this.factory.make(data, filtered, messages, attributes), () => {
17145
17745
  this.reached = true;
17146
17746
  });
@@ -17283,11 +17883,11 @@ function registerInertiaCommands(kernel, app2, gateway, options = {}) {
17283
17883
  const output = absolute(optionText(this.option("output")) ?? config2("inertia.types.routes", "resources/js/oriel/routes.ts"));
17284
17884
  const server = absolute(optionText(this.option("server")) ?? config2("inertia.types.server_routes", "types/routes.d.ts"));
17285
17885
  const table = routeTable(app2.make(Router).getRoutes(), config2("inertia.types.except_routes", DEFAULT_EXCEPT_ROUTES));
17286
- await mkdir5(dirname5(output), { recursive: true });
17287
- await writeFile6(output, renderRoutesModule(table));
17288
- await mkdir5(dirname5(server), { recursive: true });
17289
- await writeFile6(server, renderServerRouteTypes(routeTable(app2.make(Router).getRoutes())));
17290
- this.info(`Route types for ${Object.keys(table).length} named routes written to ${relative23(app2.basePath(), output)}.`);
17886
+ await mkdir5(dirname6(output), { recursive: true });
17887
+ await writeFile7(output, renderRoutesModule(table));
17888
+ await mkdir5(dirname6(server), { recursive: true });
17889
+ await writeFile7(server, renderServerRouteTypes(routeTable(app2.make(Router).getRoutes())));
17890
+ this.info(`Route types for ${Object.keys(table).length} named routes written to ${relative24(app2.basePath(), output)}.`);
17291
17891
  return 0;
17292
17892
  }
17293
17893
  ).purpose("Generate the route table and route name types for the frontend");
@@ -17300,7 +17900,7 @@ function registerInertiaCommands(kernel, app2, gateway, options = {}) {
17300
17900
  const output = absolute(optionText(this.option("output")) ?? config2("inertia.types.pages", "resources/js/oriel/pages.d.ts"));
17301
17901
  const result = await module.generatePageTypes({ root: app2.basePath(), output });
17302
17902
  for (const warning of result.warnings) this.warn(warning);
17303
- this.info(`Page types for ${result.pages} pages written to ${relative23(app2.basePath(), result.output)}.`);
17903
+ this.info(`Page types for ${result.pages} pages written to ${relative24(app2.basePath(), result.output)}.`);
17304
17904
  return 0;
17305
17905
  }).purpose("Generate TypeScript types for the Inertia page props");
17306
17906
  kernel.command("inertia:middleware {name=HandleInertiaRequests : The middleware class name} {--force : Overwrite an existing file}", async function() {
@@ -17311,12 +17911,12 @@ function registerInertiaCommands(kernel, app2, gateway, options = {}) {
17311
17911
  }
17312
17912
  const file = app2.appPath(join24("Http", "Middleware", `${name}.ts`));
17313
17913
  if (existsSync33(file) && this.option("force") !== true) {
17314
- this.error(`Middleware [${relative23(app2.basePath(), file)}] already exists.`);
17914
+ this.error(`Middleware [${relative24(app2.basePath(), file)}] already exists.`);
17315
17915
  return 1;
17316
17916
  }
17317
- await mkdir5(dirname5(file), { recursive: true });
17318
- await writeFile6(file, MIDDLEWARE_STUB2.replace("{{ class }}", () => name));
17319
- this.info(`Middleware [${relative23(app2.basePath(), file)}] created successfully.`);
17917
+ await mkdir5(dirname6(file), { recursive: true });
17918
+ await writeFile7(file, MIDDLEWARE_STUB2.replace("{{ class }}", () => name));
17919
+ this.info(`Middleware [${relative24(app2.basePath(), file)}] created successfully.`);
17320
17920
  return 0;
17321
17921
  }).purpose("Create a new Inertia middleware");
17322
17922
  kernel.command("inertia:start-ssr {--runtime= : The runtime that runs the SSR bundle (node or bun)}", async function() {
@@ -17393,7 +17993,7 @@ var HttpGateway = class {
17393
17993
  this.#except.push(...[paths].flat());
17394
17994
  }
17395
17995
  async dispatch(page) {
17396
- if (!this.enabled(currentRequest3())) return void 0;
17996
+ if (!this.enabled(currentRequest2())) return void 0;
17397
17997
  const hot = this.hotUrl();
17398
17998
  if (hot === void 0 && this.#config("inertia.ssr.ensure_bundle_exists", true) && this.bundle() === void 0) return void 0;
17399
17999
  const url2 = hot === void 0 ? `${this.productionUrl()}/render` : `${hot}/__inertia_ssr`;
@@ -17462,7 +18062,7 @@ var HttpGateway = class {
17462
18062
  });
17463
18063
  }
17464
18064
  async #failed(failure) {
17465
- const scope = requestScope2() ?? this.app;
18065
+ const scope = requestScope() ?? this.app;
17466
18066
  if (scope.bound(EventDispatcher)) await scope.make(EventDispatcher).dispatch(SSR_RENDER_FAILED, [failure]);
17467
18067
  if (this.#config("inertia.ssr.throw_on_error", false)) throw new SsrError(`SSR render failed: ${failure.error}`);
17468
18068
  }
@@ -17520,7 +18120,7 @@ var InertiaServiceProvider = class extends ServiceProvider {
17520
18120
  // ../Log/dist/index.js
17521
18121
  import pino2 from "pino";
17522
18122
  import { createWriteStream as createWriteStream2, mkdirSync as mkdirSync3, readdirSync as readdirSync6, rmSync } from "fs";
17523
- import { basename as basename2, dirname as dirname6, extname as extname3, join as join12 } from "path";
18123
+ import { basename as basename3, dirname as dirname7, extname as extname3, join as join12 } from "path";
17524
18124
  import { Writable as Writable2 } from "stream";
17525
18125
  import "pino";
17526
18126
  var rootKey = {};
@@ -17646,8 +18246,8 @@ var DailyRotatingStream = class extends Writable2 {
17646
18246
  super();
17647
18247
  this.days = days;
17648
18248
  this.now = now5;
17649
- this.dir = dirname6(basePath);
17650
- this.stem = basename2(basePath, extname3(basePath) || void 0);
18249
+ this.dir = dirname7(basePath);
18250
+ this.stem = basename3(basePath, extname3(basePath) || void 0);
17651
18251
  mkdirSync3(this.dir, { recursive: true });
17652
18252
  }
17653
18253
  days;
@@ -17996,7 +18596,6 @@ var LogServiceProvider = class extends ServiceProvider {
17996
18596
  // ../Mail/dist/index.js
17997
18597
  import { randomUUID as randomUUID3 } from "crypto";
17998
18598
  import { randomUUID as randomUUID22 } from "crypto";
17999
- import nodemailer from "nodemailer";
18000
18599
  import { createHash as createHash8 } from "crypto";
18001
18600
  var UnknownMailerError = class extends Error {
18002
18601
  kind = "Server";
@@ -18138,14 +18737,23 @@ function smtpOptions(config2) {
18138
18737
  auth: config2.username ? { user: config2.username, pass: config2.password } : void 0
18139
18738
  };
18140
18739
  }
18141
- var defaultFactory = (config2) => nodemailer.createTransport(smtpOptions(config2));
18740
+ var defaultFactory = async (config2) => {
18741
+ const { default: nodemailer } = await importOptional("nodemailer", "The smtp mailer", () => import("nodemailer"));
18742
+ return nodemailer.createTransport(smtpOptions(config2));
18743
+ };
18142
18744
  var SmtpTransport = class {
18143
- transporter;
18144
18745
  constructor(config2, factory = defaultFactory) {
18145
- this.transporter = factory(config2);
18746
+ this.config = config2;
18747
+ this.factory = factory;
18748
+ }
18749
+ config;
18750
+ factory;
18751
+ #transporter;
18752
+ transporter() {
18753
+ return this.#transporter ??= Promise.resolve().then(() => this.factory(this.config));
18146
18754
  }
18147
18755
  async send(message) {
18148
- const info = await this.transporter.sendMail({
18756
+ const info = await (await this.transporter()).sendMail({
18149
18757
  from: formatAddress(message.from),
18150
18758
  to: message.to.map(formatAddress),
18151
18759
  cc: message.cc.length > 0 ? message.cc.map(formatAddress) : void 0,
@@ -18231,12 +18839,30 @@ var Mailable = class {
18231
18839
  return this.mailAttachments;
18232
18840
  }
18233
18841
  };
18842
+ var MessageSending = class {
18843
+ constructor(message, data) {
18844
+ this.message = message;
18845
+ this.data = data;
18846
+ }
18847
+ message;
18848
+ data;
18849
+ };
18850
+ var MessageSent = class {
18851
+ constructor(message, sent, data) {
18852
+ this.message = message;
18853
+ this.sent = sent;
18854
+ this.data = data;
18855
+ }
18856
+ message;
18857
+ sent;
18858
+ data;
18859
+ };
18234
18860
  var SHOULD_QUEUE4 = /* @__PURE__ */ Symbol.for("oriel:bus.shouldQueue");
18235
18861
  var UNIQUE3 = /* @__PURE__ */ Symbol.for("oriel:bus.unique");
18236
18862
  function uniqueSpecOf2(target, name) {
18237
18863
  const members = target;
18238
- const declared = typeof members.uniqueId === "function" || members.uniqueFor !== void 0 || members.uniqueUntilProcessing === true || typeof members.uniqueVia === "function";
18239
- if (!declared) return void 0;
18864
+ const declared2 = typeof members.uniqueId === "function" || members.uniqueFor !== void 0 || members.uniqueUntilProcessing === true || typeof members.uniqueVia === "function";
18865
+ if (!declared2) return void 0;
18240
18866
  const id = typeof members.uniqueId === "function" ? members.uniqueId.call(target) : void 0;
18241
18867
  const spec = { name, id: id === void 0 || id === null ? "" : String(id) };
18242
18868
  const uniqueFor = typeof members.uniqueFor === "function" ? members.uniqueFor.call(target) : members.uniqueFor;
@@ -18286,7 +18912,8 @@ var MailerImpl = class {
18286
18912
  await container.make(BusDispatcher).dispatch(job);
18287
18913
  }
18288
18914
  /** Renders and delivers immediately, bypassing the queueable check. Used by send() and by the queued job's
18289
- * handle(), once it's already running on the worker. */
18915
+ * handle(), once it's already running on the worker. Dispatches MessageSending, whose listener may stop the message
18916
+ * by returning false (then this resolves undefined), and MessageSent. */
18290
18917
  async sendNow(mailable, overrides) {
18291
18918
  const envelope = await mailable.envelope();
18292
18919
  const to = overrides?.to && overrides.to.length > 0 ? overrides.to : normalizeAddresses(envelope.to);
@@ -18311,7 +18938,13 @@ var MailerImpl = class {
18311
18938
  attachments,
18312
18939
  headers: {}
18313
18940
  };
18314
- return this.transport.send(message);
18941
+ const container = currentContainer();
18942
+ const events = container?.bound(EventDispatcher) ? container.make(EventDispatcher) : void 0;
18943
+ const data = { mailable };
18944
+ if (events !== void 0 && await events.until(new MessageSending(message, data)) === false) return void 0;
18945
+ const sent = await this.transport.send(message);
18946
+ await events?.dispatch(new MessageSent(message, sent, data));
18947
+ return sent;
18315
18948
  }
18316
18949
  };
18317
18950
  var PendingMail = class {
@@ -18356,7 +18989,8 @@ var QUEUE_OPTIONS3 = [
18356
18989
  "backoff",
18357
18990
  "timeout",
18358
18991
  "failOnTimeout",
18359
- "deleteWhenMissingModels"
18992
+ "deleteWhenMissingModels",
18993
+ "afterCommit"
18360
18994
  ];
18361
18995
  function copyShouldQueueFields(target, source) {
18362
18996
  const fields = source;
@@ -18407,8 +19041,8 @@ var SendQueuedMailable = class {
18407
19041
  return typeof hooks.retryUntil === "function" ? hooks.retryUntil.call(this.mailable) : void 0;
18408
19042
  }
18409
19043
  middleware() {
18410
- const declared = this.mailable.middleware;
18411
- return (typeof declared === "function" ? declared.call(this.mailable) : declared) ?? [];
19044
+ const declared2 = this.mailable.middleware;
19045
+ return (typeof declared2 === "function" ? declared2.call(this.mailable) : declared2) ?? [];
18412
19046
  }
18413
19047
  };
18414
19048
  SendQueuedMailable.prototype[SHOULD_QUEUE4] = true;
@@ -18966,8 +19600,8 @@ var SHOULD_QUEUE5 = /* @__PURE__ */ Symbol.for("oriel:bus.shouldQueue");
18966
19600
  var UNIQUE4 = /* @__PURE__ */ Symbol.for("oriel:bus.unique");
18967
19601
  function uniqueSpecOf3(target, name) {
18968
19602
  const members = target;
18969
- const declared = typeof members.uniqueId === "function" || members.uniqueFor !== void 0 || members.uniqueUntilProcessing === true || typeof members.uniqueVia === "function";
18970
- if (!declared) return void 0;
19603
+ const declared2 = typeof members.uniqueId === "function" || members.uniqueFor !== void 0 || members.uniqueUntilProcessing === true || typeof members.uniqueVia === "function";
19604
+ if (!declared2) return void 0;
18971
19605
  const id = typeof members.uniqueId === "function" ? members.uniqueId.call(target) : void 0;
18972
19606
  const spec = { name, id: id === void 0 || id === null ? "" : String(id) };
18973
19607
  const uniqueFor = typeof members.uniqueFor === "function" ? members.uniqueFor.call(target) : members.uniqueFor;
@@ -19019,6 +19653,40 @@ var AnonymousNotifiable = class {
19019
19653
  await resolveDispatcher().sendNow(this, notification, channels);
19020
19654
  }
19021
19655
  };
19656
+ var NotificationSending = class {
19657
+ constructor(notifiable, notification, channel) {
19658
+ this.notifiable = notifiable;
19659
+ this.notification = notification;
19660
+ this.channel = channel;
19661
+ }
19662
+ notifiable;
19663
+ notification;
19664
+ channel;
19665
+ };
19666
+ var NotificationSent = class {
19667
+ constructor(notifiable, notification, channel, response2) {
19668
+ this.notifiable = notifiable;
19669
+ this.notification = notification;
19670
+ this.channel = channel;
19671
+ this.response = response2;
19672
+ }
19673
+ notifiable;
19674
+ notification;
19675
+ channel;
19676
+ response;
19677
+ };
19678
+ var NotificationFailed = class {
19679
+ constructor(notifiable, notification, channel, data) {
19680
+ this.notifiable = notifiable;
19681
+ this.notification = notification;
19682
+ this.channel = channel;
19683
+ this.data = data;
19684
+ }
19685
+ notifiable;
19686
+ notification;
19687
+ channel;
19688
+ data;
19689
+ };
19022
19690
  var QUEUE_OPTIONS4 = [
19023
19691
  "connection",
19024
19692
  "queue",
@@ -19027,7 +19695,8 @@ var QUEUE_OPTIONS4 = [
19027
19695
  "backoff",
19028
19696
  "timeout",
19029
19697
  "failOnTimeout",
19030
- "deleteWhenMissingModels"
19698
+ "deleteWhenMissingModels",
19699
+ "afterCommit"
19031
19700
  ];
19032
19701
  function copyShouldQueueFields2(target, source) {
19033
19702
  const fields = source;
@@ -19075,8 +19744,8 @@ var SendQueuedNotifications = class {
19075
19744
  return typeof hooks.retryUntil === "function" ? hooks.retryUntil.call(this.notification) : void 0;
19076
19745
  }
19077
19746
  middleware() {
19078
- const declared = this.notification.middleware;
19079
- return (typeof declared === "function" ? declared.call(this.notification) : declared) ?? [];
19747
+ const declared2 = this.notification.middleware;
19748
+ return (typeof declared2 === "function" ? declared2.call(this.notification) : declared2) ?? [];
19080
19749
  }
19081
19750
  };
19082
19751
  SendQueuedNotifications.prototype[SHOULD_QUEUE5] = true;
@@ -19142,10 +19811,26 @@ var Dispatcher3 = class {
19142
19811
  const names = channels ?? notification.via(notifiable);
19143
19812
  for (const name of names) {
19144
19813
  if (name === "database" && notifiable instanceof AnonymousNotifiable) continue;
19145
- await this.resolve(name).send(notifiable, own);
19814
+ await this.sendToNotifiable(notifiable, own, name);
19146
19815
  }
19147
19816
  }
19148
19817
  }
19818
+ /**
19819
+ * Laravel's sendToNotifiable(): NotificationSending first (a listener's false skips this channel), then the channel,
19820
+ * then NotificationSent with what it returned; NotificationFailed if it throws, and the error goes on.
19821
+ */
19822
+ async sendToNotifiable(notifiable, notification, channel) {
19823
+ const events = this.container.bound(EventDispatcher) ? this.container.make(EventDispatcher) : void 0;
19824
+ if (events !== void 0 && await events.until(new NotificationSending(notifiable, notification, channel)) === false) return;
19825
+ let response2;
19826
+ try {
19827
+ response2 = await this.resolve(channel).send(notifiable, notification);
19828
+ } catch (exception) {
19829
+ await events?.dispatch(new NotificationFailed(notifiable, notification, channel, { exception }));
19830
+ throw exception;
19831
+ }
19832
+ await events?.dispatch(new NotificationSent(notifiable, notification, channel, response2));
19833
+ }
19149
19834
  /** On-demand: an AnonymousNotifiable, whose notify() goes through the bound NotificationDispatcher. */
19150
19835
  route(channel, route2) {
19151
19836
  return new AnonymousNotifiable().route(channel, route2);
@@ -19291,10 +19976,9 @@ var PipelineServiceProvider = class {
19291
19976
  import { Buffer as Buffer2 } from "buffer";
19292
19977
  import { randomUUID as randomUUID5 } from "crypto";
19293
19978
  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";
19979
+ import { existsSync as existsSync9, readdirSync as readdirSync7, statSync as statSync3 } from "fs";
19980
+ import { dirname as dirname8, join as join13, relative as relative6, sep as sep6 } from "path";
19296
19981
  import { pathToFileURL as pathToFileURL6 } from "url";
19297
- import { Redis as Redis2 } from "ioredis";
19298
19982
  import { randomUUID as randomUUID32 } from "crypto";
19299
19983
  import { setTimeout as sleep4 } from "timers/promises";
19300
19984
  import { spawn as spawnProcess } from "child_process";
@@ -19637,6 +20321,51 @@ function decodePayload(raw3) {
19637
20321
  }
19638
20322
  return { ...payload, attempts: Number(payload.attempts ?? 0), data: payload.data ?? {} };
19639
20323
  }
20324
+ var JobQueued = class {
20325
+ constructor(connectionName, queue, id, job, payload, delay) {
20326
+ this.connectionName = connectionName;
20327
+ this.queue = queue;
20328
+ this.id = id;
20329
+ this.job = job;
20330
+ this.payload = payload;
20331
+ this.delay = delay;
20332
+ }
20333
+ connectionName;
20334
+ queue;
20335
+ id;
20336
+ job;
20337
+ payload;
20338
+ delay;
20339
+ };
20340
+ var JobProcessing = class {
20341
+ constructor(connectionName, job) {
20342
+ this.connectionName = connectionName;
20343
+ this.job = job;
20344
+ }
20345
+ connectionName;
20346
+ job;
20347
+ };
20348
+ var JobProcessed = class {
20349
+ constructor(connectionName, job) {
20350
+ this.connectionName = connectionName;
20351
+ this.job = job;
20352
+ }
20353
+ connectionName;
20354
+ job;
20355
+ };
20356
+ var JobFailed = class {
20357
+ constructor(connectionName, job, exception) {
20358
+ this.connectionName = connectionName;
20359
+ this.job = job;
20360
+ this.exception = exception;
20361
+ }
20362
+ connectionName;
20363
+ job;
20364
+ exception;
20365
+ };
20366
+ async function dispatchQueueEvent(container, event2) {
20367
+ if (container.bound(EventDispatcher)) await container.make(EventDispatcher).dispatch(event2);
20368
+ }
19640
20369
  var BaseJob = class {
19641
20370
  constructor(context, queue) {
19642
20371
  this.context = context;
@@ -19705,7 +20434,8 @@ var BaseJob = class {
19705
20434
  }
19706
20435
  /**
19707
20436
  * Marks the job as failed, deletes it, runs the handler's failure bookkeeping (unique lock, batch, chain catch,
19708
- * the job's failed() hook) and stores it with the FailedJobProvider. A job that was already deleted is ignored.
20437
+ * the job's failed() hook), stores it with the FailedJobProvider and dispatches JobFailed. A job that was already
20438
+ * deleted is ignored.
19709
20439
  */
19710
20440
  async fail(error) {
19711
20441
  this.markAsFailed();
@@ -19716,8 +20446,12 @@ var BaseJob = class {
19716
20446
  await this.context.handler.failed(this, reason);
19717
20447
  } finally {
19718
20448
  const { container } = this.context;
19719
- if (container.bound(FailedJobProvider)) {
19720
- await container.make(FailedJobProvider).log(this.getConnectionName(), this.getQueue(), this.payload(), reason);
20449
+ try {
20450
+ if (container.bound(FailedJobProvider)) {
20451
+ await container.make(FailedJobProvider).log(this.getConnectionName(), this.getQueue(), this.payload(), reason);
20452
+ }
20453
+ } finally {
20454
+ await dispatchQueueEvent(container, new JobFailed(this.getConnectionName(), this, reason));
19721
20455
  }
19722
20456
  }
19723
20457
  }
@@ -19803,8 +20537,8 @@ var CallQueuedHandler = class {
19803
20537
  return job.fail(error);
19804
20538
  }
19805
20539
  async dispatchThroughMiddleware(instance) {
19806
- const declared = instance.middleware;
19807
- const middleware = (typeof declared === "function" ? declared.call(instance) : declared) ?? [];
20540
+ const declared2 = instance.middleware;
20541
+ const middleware = (typeof declared2 === "function" ? declared2.call(instance) : declared2) ?? [];
19808
20542
  const run = async (index, current) => {
19809
20543
  const layer = middleware[index];
19810
20544
  if (layer === void 0) return current.handle();
@@ -19832,13 +20566,15 @@ var CallQueuedHandler = class {
19832
20566
  await this.container.make(BatchRepository).recordSuccessfulJob(payload.batchId, payload.uuid);
19833
20567
  }
19834
20568
  async releaseUniqueLock(payload) {
19835
- const lock = payload.uniqueLock;
19836
- if (!lock || !this.container.bound(CacheManager)) return;
19837
- const cache2 = this.container.make(CacheManager);
19838
- const store = lock.store !== void 0 ? cache2.store(lock.store) : cache2;
19839
- await store.lock(lock.key).forceRelease();
20569
+ await releaseUniqueLock(this.container, payload.uniqueLock);
19840
20570
  }
19841
20571
  };
20572
+ async function releaseUniqueLock(container, lock) {
20573
+ if (!lock || !container.bound(CacheManager)) return;
20574
+ const cache2 = container.make(CacheManager);
20575
+ const store = lock.store !== void 0 ? cache2.store(lock.store) : cache2;
20576
+ await store.lock(lock.key).forceRelease();
20577
+ }
19842
20578
  var WithoutOverlapping = class {
19843
20579
  constructor(key = "", releaseAfter = 0, expiresAfter = 0) {
19844
20580
  this.key = key;
@@ -19902,7 +20638,7 @@ var WORKER_DISCOVERY_DIRECTORIES = ["Events", "Listeners", "Mail", "Notification
19902
20638
  var isClass2 = (value2) => typeof value2 === "function" && /^class[\s{]/.test(Function.prototype.toString.call(value2));
19903
20639
  var isJobClass = (value2) => typeof value2.prototype.handle === "function";
19904
20640
  async function discoverClasses(directory, registry2, filter = () => true) {
19905
- if (!existsSync8(directory)) return [];
20641
+ if (!existsSync9(directory)) return [];
19906
20642
  const names = [];
19907
20643
  for (const file of files2(directory)) {
19908
20644
  const module = await import(pathToFileURL6(file).href);
@@ -19926,7 +20662,7 @@ async function discover(appPath, registry2) {
19926
20662
  const seen = /* @__PURE__ */ new Set();
19927
20663
  for (const directory of ["Jobs", ...WORKER_DISCOVERY_DIRECTORIES]) {
19928
20664
  const root = join13(appPath, directory);
19929
- if (!existsSync8(root)) continue;
20665
+ if (!existsSync9(root)) continue;
19930
20666
  for (const file of files2(root)) {
19931
20667
  let module;
19932
20668
  try {
@@ -19935,7 +20671,7 @@ async function discover(appPath, registry2) {
19935
20671
  console.warn(`Oriel couldn't load ${relative6(appPath, file)} to name its classes for the queue: ${error instanceof Error ? error.message : String(error)}`);
19936
20672
  continue;
19937
20673
  }
19938
- const folder = relative6(appPath, dirname7(file)).split(sep5).join(".");
20674
+ const folder = relative6(appPath, dirname8(file)).split(sep6).join(".");
19939
20675
  for (const exported of Object.values(module)) {
19940
20676
  if (!isClass2(exported) || seen.has(exported) || directory === "Jobs" && !isJobClass(exported)) continue;
19941
20677
  seen.add(exported);
@@ -19981,6 +20717,8 @@ var QueueBase = class {
19981
20717
  container;
19982
20718
  defaultQueue;
19983
20719
  connectionName = "default";
20720
+ /** `queue.connections.<name>.after_commit`: work dispatched inside a transaction waits for its commit. */
20721
+ dispatchAfterCommit = false;
19984
20722
  handler;
19985
20723
  setConnectionName(name) {
19986
20724
  this.connectionName = name;
@@ -19989,6 +20727,10 @@ var QueueBase = class {
19989
20727
  getConnectionName() {
19990
20728
  return this.connectionName;
19991
20729
  }
20730
+ setDispatchAfterCommit(value2) {
20731
+ this.dispatchAfterCommit = value2;
20732
+ return this;
20733
+ }
19992
20734
  /** The queue name to use: the given one, else the connection's default. */
19993
20735
  getQueue(queue) {
19994
20736
  return optionalString2(queue) || this.defaultQueue;
@@ -19998,11 +20740,49 @@ var QueueBase = class {
19998
20740
  }
19999
20741
  async push(job, queue) {
20000
20742
  await ensureAppClasses(this.container);
20001
- return this.pushRaw(this.createPayload(job), queue ?? (optionalString2(job.queue) || void 0));
20743
+ const payload = this.createPayload(job);
20744
+ const name = queue ?? (optionalString2(job.queue) || void 0);
20745
+ return this.enqueue(job, () => this.pushed(job, payload, name, void 0, this.pushRaw(payload, name)));
20002
20746
  }
20003
20747
  async later(delaySeconds2, job, queue) {
20004
20748
  await ensureAppClasses(this.container);
20005
- return this.pushRaw(this.createPayload(job), queue ?? (optionalString2(job.queue) || void 0), delaySeconds2);
20749
+ const payload = this.createPayload(job);
20750
+ const name = queue ?? (optionalString2(job.queue) || void 0);
20751
+ return this.enqueue(job, () => this.pushed(job, payload, name, delaySeconds2, this.pushRaw(payload, name, delaySeconds2)));
20752
+ }
20753
+ /** Waits for the push, then dispatches JobQueued with its id. */
20754
+ async pushed(job, payload, queue, delay, push) {
20755
+ const id = await push;
20756
+ await this.raiseJobQueued(this.getQueue(queue), id, job, payload, delay);
20757
+ return id;
20758
+ }
20759
+ /** Laravel's raiseJobQueuedEvent(). */
20760
+ async raiseJobQueued(queue, id, job, payload, delay) {
20761
+ await dispatchQueueEvent(this.container, new JobQueued(this.connectionName, queue, id, job, payload, delay));
20762
+ }
20763
+ /** The job's own `afterCommit`, else the connection's `after_commit`. */
20764
+ shouldDispatchAfterCommit(job) {
20765
+ return typeof job.afterCommit === "boolean" ? job.afterCommit : this.dispatchAfterCommit;
20766
+ }
20767
+ /**
20768
+ * Laravel's enqueueUsing(): pushes now, or, for a job that waits for the commit, once the database transaction open
20769
+ * here commits (resolving '' meanwhile). The payload is made first, so a job that can't be queued fails at dispatch.
20770
+ * A rollback drops the push and frees a unique job's lock, as does a push that fails after the commit.
20771
+ */
20772
+ async enqueue(job, push) {
20773
+ if (!this.shouldDispatchAfterCommit(job) || !this.container.bound(DatabaseManager)) return push();
20774
+ const lock = symbolValue(job, UNIQUE_LOCK2);
20775
+ const release = lock === void 0 ? void 0 : () => releaseUniqueLock(this.container, lock);
20776
+ let id = "";
20777
+ await this.container.make(DatabaseManager).afterCommit(async () => {
20778
+ try {
20779
+ id = await push();
20780
+ } catch (error) {
20781
+ await release?.();
20782
+ throw error;
20783
+ }
20784
+ }, release);
20785
+ return id;
20006
20786
  }
20007
20787
  /** Closes network connections (redis). No-op by default. */
20008
20788
  async disconnect() {
@@ -20037,13 +20817,18 @@ var SyncQueue = class extends QueueBase {
20037
20817
  async pushRaw(payload, queue) {
20038
20818
  const job = new SyncJob(this.jobContext(), payload, this.getQueue(queue));
20039
20819
  try {
20820
+ await dispatchQueueEvent(this.container, new JobProcessing(this.connectionName, job));
20040
20821
  await job.fire();
20822
+ await dispatchQueueEvent(this.container, new JobProcessed(this.connectionName, job));
20041
20823
  } catch (error) {
20042
20824
  if (!job.hasFailed()) await job.fail(error);
20043
20825
  throw error;
20044
20826
  }
20045
20827
  return payload.uuid;
20046
20828
  }
20829
+ /** The job has run already: nothing was queued. */
20830
+ async raiseJobQueued(_queue, _id, _job, _payload, _delay) {
20831
+ }
20047
20832
  async pop() {
20048
20833
  return void 0;
20049
20834
  }
@@ -20276,13 +21061,14 @@ redis.call('del', KEYS[1], KEYS[2], KEYS[3], KEYS[4])
20276
21061
  return size
20277
21062
  `;
20278
21063
  var QUEUE_KEYS = ["driver", "connection", "queue", "retry_after", "block_for", "after_commit", "client", "url"];
20279
- function makeRedisClient2(config2) {
21064
+ async function makeRedisClient2(config2) {
20280
21065
  if (config2.client) return config2.client;
21066
+ const { Redis } = await importOptional("ioredis", "The redis queue connection", () => import("ioredis"));
20281
21067
  const options = Object.fromEntries(
20282
21068
  Object.entries(config2).filter(([key, value2]) => value2 !== void 0 && !QUEUE_KEYS.includes(key))
20283
21069
  );
20284
- if (typeof config2.url === "string" && config2.url !== "") return new Redis2(config2.url, options);
20285
- return new Redis2(options);
21070
+ if (typeof config2.url === "string" && config2.url !== "") return new Redis(config2.url, options);
21071
+ return new Redis(options);
20286
21072
  }
20287
21073
  function resolveRedisConfig2(config2, appConfig2) {
20288
21074
  if (config2.client !== void 0 || typeof config2.url === "string" && config2.url !== "") return config2;
@@ -20290,6 +21076,7 @@ function resolveRedisConfig2(config2, appConfig2) {
20290
21076
  return appConfig2.get(`database.redis.${name}`) ?? config2;
20291
21077
  }
20292
21078
  var RedisQueue = class extends QueueBase {
21079
+ /** `connect` gives the client (or a promise of it), at the queue's first command. */
20293
21080
  constructor(container, connect, options = {}) {
20294
21081
  super(container, options.queue ?? "default");
20295
21082
  this.connect = connect;
@@ -20299,7 +21086,7 @@ var RedisQueue = class extends QueueBase {
20299
21086
  client;
20300
21087
  retryAfter;
20301
21088
  redis() {
20302
- return this.client ??= this.connect();
21089
+ return this.client ??= Promise.resolve().then(() => this.connect());
20303
21090
  }
20304
21091
  /** The list key for a queue name: `queues:<name>`. */
20305
21092
  key(queue) {
@@ -20308,44 +21095,47 @@ var RedisQueue = class extends QueueBase {
20308
21095
  async pushRaw(payload, queue, delaySeconds2 = 0) {
20309
21096
  const key = this.key(queue);
20310
21097
  const body = encodePayload({ ...payload, attempts: payload.attempts ?? 0 });
20311
- if (delaySeconds2 > 0) await this.redis().zadd(`${key}:delayed`, this.now() + delaySeconds2, body);
20312
- else await this.redis().eval(PUSH, 2, key, `${key}:notify`, body);
21098
+ const redis = await this.redis();
21099
+ if (delaySeconds2 > 0) await redis.zadd(`${key}:delayed`, this.now() + delaySeconds2, body);
21100
+ else await redis.eval(PUSH, 2, key, `${key}:notify`, body);
20313
21101
  return payload.uuid;
20314
21102
  }
20315
21103
  async pop(queue) {
20316
21104
  const key = this.key(queue);
20317
21105
  const now5 = this.now();
20318
- await this.redis().eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:delayed`, key, `${key}:notify`, now5);
20319
- await this.redis().eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:reserved`, key, `${key}:notify`, now5);
21106
+ const redis = await this.redis();
21107
+ await redis.eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:delayed`, key, `${key}:notify`, now5);
21108
+ await redis.eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:reserved`, key, `${key}:notify`, now5);
20320
21109
  for (; ; ) {
20321
- const [job, reserved] = await this.redis().eval(POP, 3, key, `${key}:reserved`, `${key}:notify`, now5 + this.retryAfter);
21110
+ const [job, reserved] = await redis.eval(POP, 3, key, `${key}:reserved`, `${key}:notify`, now5 + this.retryAfter);
20322
21111
  if (!job || !reserved) return void 0;
20323
21112
  try {
20324
21113
  return new RedisJob(this.jobContext(), this, job, reserved, this.getQueue(queue));
20325
21114
  } catch (error) {
20326
21115
  await this.failCorrupt(this.getQueue(queue), job, error);
20327
- await this.redis().zrem(`${key}:reserved`, reserved);
21116
+ await redis.zrem(`${key}:reserved`, reserved);
20328
21117
  }
20329
21118
  }
20330
21119
  }
20331
21120
  async size(queue) {
20332
21121
  const key = this.key(queue);
20333
- return Number(await this.redis().eval(SIZE, 3, key, `${key}:delayed`, `${key}:reserved`));
21122
+ return Number(await (await this.redis()).eval(SIZE, 3, key, `${key}:delayed`, `${key}:reserved`));
20334
21123
  }
20335
21124
  async clear(queue) {
20336
21125
  const key = this.key(queue);
20337
- return Number(await this.redis().eval(CLEAR, 4, key, `${key}:delayed`, `${key}:reserved`, `${key}:notify`));
21126
+ return Number(await (await this.redis()).eval(CLEAR, 4, key, `${key}:delayed`, `${key}:reserved`, `${key}:notify`));
20338
21127
  }
20339
21128
  async deleteReserved(queue, job) {
20340
- await this.redis().zrem(`${this.key(queue)}:reserved`, job.getReservedJob());
21129
+ await (await this.redis()).zrem(`${this.key(queue)}:reserved`, job.getReservedJob());
20341
21130
  }
20342
21131
  async deleteAndRelease(queue, job, delaySeconds2) {
20343
21132
  const key = this.key(queue);
20344
- await this.redis().eval(RELEASE, 2, `${key}:delayed`, `${key}:reserved`, job.getReservedJob(), this.now() + Math.max(0, delaySeconds2));
21133
+ await (await this.redis()).eval(RELEASE, 2, `${key}:delayed`, `${key}:reserved`, job.getReservedJob(), this.now() + Math.max(0, delaySeconds2));
20345
21134
  }
20346
21135
  async disconnect() {
20347
- const client = this.client;
21136
+ const pending = this.client;
20348
21137
  this.client = void 0;
21138
+ const client = await pending?.catch(() => void 0);
20349
21139
  if (client && client.status !== "end") await client.quit();
20350
21140
  }
20351
21141
  /** Unix seconds, with milliseconds as the fraction (sorted-set scores). */
@@ -20394,6 +21184,15 @@ var QueueManager2 = class {
20394
21184
  extend(driver, factory) {
20395
21185
  this.drivers.set(driver, factory);
20396
21186
  }
21187
+ before(callback) {
21188
+ this.container.make(EventDispatcher).listen(JobProcessing, callback);
21189
+ }
21190
+ after(callback) {
21191
+ this.container.make(EventDispatcher).listen(JobProcessed, callback);
21192
+ }
21193
+ failing(callback) {
21194
+ this.container.make(EventDispatcher).listen(JobFailed, callback);
21195
+ }
20397
21196
  getDefaultDriver() {
20398
21197
  return optionalString2(this.config().get("queue.default")) || "sync";
20399
21198
  }
@@ -20444,6 +21243,7 @@ var QueueManager2 = class {
20444
21243
  if (!driver) throw new UnknownQueueDriverError(driverName);
20445
21244
  const queue = driver(config2, name);
20446
21245
  queue.setConnectionName?.(name);
21246
+ queue.setDispatchAfterCommit?.(config2.after_commit === true);
20447
21247
  return queue;
20448
21248
  }
20449
21249
  config() {
@@ -20859,12 +21659,16 @@ var Worker = class _Worker {
20859
21659
  process.on("unhandledRejection", onUnhandledRejection);
20860
21660
  return () => process.off("unhandledRejection", onUnhandledRejection);
20861
21661
  }
20862
- /** Processes one job: max-attempts check, fire (with timeout), and failure handling. `_connectionName` is unused (kept for Laravel's signature). */
20863
- async process(_connectionName, job, options) {
21662
+ /**
21663
+ * Processes one job: max-attempts check, fire (with timeout), and failure handling. Dispatches JobProcessing first
21664
+ * and JobProcessed once the job has run without failing (BaseJob.fail() dispatches JobFailed).
21665
+ */
21666
+ async process(connectionName, job, options) {
20864
21667
  const workable = job;
20865
21668
  const started = Date.now();
20866
21669
  try {
20867
21670
  this.listener.processing?.(job);
21671
+ await dispatchQueueEvent(this.container, new JobProcessing(connectionName, job));
20868
21672
  await this.markJobAsFailedIfAlreadyExceedsMaxAttempts(workable, options.maxTries);
20869
21673
  if (job.isDeleted()) return;
20870
21674
  await this.fireWithTimeout(workable, options);
@@ -20873,7 +21677,10 @@ var Worker = class _Worker {
20873
21677
  this.pendingRejection = void 0;
20874
21678
  await pending;
20875
21679
  }
20876
- if (!workable.hasFailed()) this.listener.processed?.(job, Date.now() - started);
21680
+ if (!workable.hasFailed()) {
21681
+ this.listener.processed?.(job, Date.now() - started);
21682
+ await dispatchQueueEvent(this.container, new JobProcessed(connectionName, job));
21683
+ }
20877
21684
  } catch (error) {
20878
21685
  await this.handleJobException(workable, options, error);
20879
21686
  }
@@ -21493,11 +22300,13 @@ var ThrottleRequestsError = class extends Error {
21493
22300
  status = 429;
21494
22301
  name = "ThrottleRequestsError";
21495
22302
  };
22303
+ var ELEMENT2 = /* @__PURE__ */ Symbol.for("oriel:view.element");
21496
22304
  async function toResponse(request2, value2) {
21497
22305
  if (value2 instanceof Response) return value2;
21498
22306
  if (value2 === null || value2 === void 0) return new Response(null, { status: 204 });
21499
22307
  if (typeof value2 === "string") return html2(value2);
21500
22308
  if (typeof value2 !== "object") return html2(String(value2));
22309
+ if (value2[ELEMENT2] === true) return html2(await renderElement(value2));
21501
22310
  const candidate = value2;
21502
22311
  if (typeof candidate.toResponse === "function") {
21503
22312
  return toResponse(request2, await candidate.toResponse.call(value2, request2));
@@ -21510,6 +22319,13 @@ async function toResponse(request2, value2) {
21510
22319
  }
21511
22320
  return json(JSON.stringify(value2));
21512
22321
  }
22322
+ async function renderElement(element) {
22323
+ const container = currentContainer();
22324
+ if (container === void 0 || !container.bound(ViewFactory)) {
22325
+ throw new RoutingError("Returning a TSX element needs the View service provider.");
22326
+ }
22327
+ return container.make(ViewFactory).renderToString(element);
22328
+ }
21513
22329
  function html2(body) {
21514
22330
  return new Response(body, { headers: { "content-type": "text/html; charset=utf-8" } });
21515
22331
  }
@@ -21571,10 +22387,14 @@ async function renderError(container, request2, error) {
21571
22387
  await handler3.report(error);
21572
22388
  return handler3.render(request2, error);
21573
22389
  }
21574
- async function guard(container, request2, run) {
22390
+ async function guard(container, request2, run, stage = "middleware") {
21575
22391
  try {
21576
22392
  const result = await run();
21577
- return result instanceof Response ? result : await toResponse(request2, result);
22393
+ if (result instanceof Response) return result;
22394
+ if (stage === "middleware" && (result === void 0 || result === null)) {
22395
+ throw new RoutingError("Middleware must return a Response.");
22396
+ }
22397
+ return await toResponse(request2, result);
21578
22398
  } catch (error) {
21579
22399
  return renderError(container, request2, error);
21580
22400
  }
@@ -21595,12 +22415,13 @@ async function runMiddleware(container, request2, middleware, instances2, destin
21595
22415
  })
21596
22416
  );
21597
22417
  }
21598
- return container.make(PipelineFactory).make().send(request2).through(pipes).then((passable) => guard(container, passable, () => destination(passable)));
22418
+ return container.make(PipelineFactory).make().send(request2).through(pipes).then((passable) => guard(container, passable, () => destination(passable), "action"));
21599
22419
  }
21600
22420
  function orderForBindings(router, middleware) {
21601
22421
  const aliases2 = router.getMiddleware();
21602
22422
  const groups = router.getMiddlewareGroups();
21603
22423
  const early = /* @__PURE__ */ new Set();
22424
+ const throttle = Object.hasOwn(aliases2, "throttle") ? aliases2["throttle"] : void 0;
21604
22425
  for (const name of ["auth", "guest"]) if (Object.hasOwn(aliases2, name)) early.add(aliases2[name]);
21605
22426
  for (const group of ["web", "api"]) {
21606
22427
  try {
@@ -21608,9 +22429,11 @@ function orderForBindings(router, middleware) {
21608
22429
  } catch {
21609
22430
  }
21610
22431
  }
21611
- const before = middleware.filter((entry) => early.has(entry.cls));
21612
- const after = middleware.filter((entry) => !early.has(entry.cls));
21613
- return { middleware: [...before, ...after], at: before.length };
22432
+ const isThrottle = (entry) => throttle !== void 0 && entry.cls === throttle;
22433
+ const before = middleware.filter((entry) => early.has(entry.cls) && !isThrottle(entry));
22434
+ const throttled = middleware.filter(isThrottle);
22435
+ const after = middleware.filter((entry) => !early.has(entry.cls) && !isThrottle(entry));
22436
+ return { middleware: [...before, ...throttled, ...after], at: before.length + throttled.length };
21614
22437
  }
21615
22438
  async function substituteBindings(router, route2, values, container) {
21616
22439
  const resolver2 = container.bound(RouteModelResolver) ? container.make(RouteModelResolver) : void 0;
@@ -22252,6 +23075,14 @@ function buildQuery2(values) {
22252
23075
  for (const [key, value2] of Object.entries(values)) add(key, value2);
22253
23076
  return pairs.join("&");
22254
23077
  }
23078
+ function acceptsSlash(pattern) {
23079
+ if (pattern === void 0) return false;
23080
+ try {
23081
+ return new RegExp(`^(?:${pattern})$`).test("a/b");
23082
+ } catch {
23083
+ return false;
23084
+ }
23085
+ }
22255
23086
  function routeKey(value2, field) {
22256
23087
  if (typeof value2 !== "object" || value2 === null) return value2;
22257
23088
  const model = value2;
@@ -22300,6 +23131,7 @@ var BaseUrlGenerator = class {
22300
23131
  const named = isPlainObject3(parameters) ? { ...parameters } : {};
22301
23132
  const positional = Array.isArray(parameters) ? [...parameters] : parameters === void 0 || parameters === null || isPlainObject3(parameters) ? [] : [parameters];
22302
23133
  const values = /* @__PURE__ */ new Map();
23134
+ const wheres = route2.wheres();
22303
23135
  const missing = [];
22304
23136
  for (const parameter of route2.parameters) {
22305
23137
  let value2;
@@ -22321,7 +23153,8 @@ var BaseUrlGenerator = class {
22321
23153
  }).map(
22322
23154
  (segment) => segment.replace(PARAMETER3, (_match, parameter) => {
22323
23155
  const value2 = values.get(parameter);
22324
- return value2 === void 0 ? "" : encodeURIComponent(value2);
23156
+ if (value2 === void 0) return "";
23157
+ return acceptsSlash(wheres[parameter]) ? value2.split("/").map(encodeURIComponent).join("/") : encodeURIComponent(value2);
22325
23158
  })
22326
23159
  ).join("/");
22327
23160
  const query = Object.fromEntries(Object.entries(named).map(([key, value2]) => [key, routeKey(value2, void 0)]));
@@ -22329,7 +23162,8 @@ var BaseUrlGenerator = class {
22329
23162
  }
22330
23163
  asset(path) {
22331
23164
  if (VALID_URL.test(path)) return path;
22332
- const base = this.#config("app.asset_url", void 0)?.replace(/\/+$/, "") ?? this.root();
23165
+ const assetUrl = this.#config("app.asset_url", void 0)?.replace(/\/+$/, "");
23166
+ const base = assetUrl === void 0 || assetUrl === "" ? this.root() : assetUrl;
22333
23167
  const trimmed = path.replace(/^\/+/, "");
22334
23168
  return trimmed === "" ? base : `${base}/${trimmed}`;
22335
23169
  }
@@ -22440,7 +23274,7 @@ var BaseUrlGenerator = class {
22440
23274
  var Route = facade(Router);
22441
23275
  var DiagnosingHealth = class {
22442
23276
  };
22443
- var escapeHtml2 = (value2) => value2.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
23277
+ var escapeHtml = (value2) => value2.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
22444
23278
  var STYLE = ':root{color-scheme:dark}*{box-sizing:border-box;margin:0}html{background:#05050b}body{min-height:100vh;display:grid;place-items:center;padding:20px;background:#1a1a1a;color:#fff;font:400 16px/1.7 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}main{display:flex;align-items:center;gap:20px;width:100%;max-width:640px;padding:20px 32px;border-radius:18px;background:#212121}.dot{flex:none;width:12px;height:12px;border-radius:50%;background:#74ec5a}.dot.down{background:#ff3543}h1{font-size:21px;line-height:1.4;font-weight:600}p{color:#a3a3a3}.time{color:#ba94ff}';
22445
23279
  function healthResponse(page = {}) {
22446
23280
  const healthy = page.healthy ?? true;
@@ -22450,7 +23284,7 @@ function healthResponse(page = {}) {
22450
23284
  <head>
22451
23285
  <meta charset="utf-8">
22452
23286
  <meta name="viewport" content="width=device-width, initial-scale=1">
22453
- <title>${escapeHtml2(page.appName ?? "Oriel")}</title>
23287
+ <title>${escapeHtml(page.appName ?? "Oriel")}</title>
22454
23288
  <style>${STYLE}</style>
22455
23289
  </head>
22456
23290
  <body>
@@ -22501,25 +23335,53 @@ function withHeaders2(response2, headers) {
22501
23335
  }
22502
23336
  }
22503
23337
  var ThrottleRequests = class {
22504
- async handle(request2, next, maxAttempts = "60", decayMinutes = "1", prefix = "") {
23338
+ async handle(request2, next, ...parameters) {
23339
+ if (parameters.length === 1 && !/^\d+$/.test(parameters[0].trim())) return this.#named(request2, next, parameters[0]);
23340
+ const [maxAttempts = "60", decayMinutes = "1", prefix = ""] = parameters;
23341
+ return this.#numbered(request2, next, maxAttempts, decayMinutes, prefix);
23342
+ }
23343
+ /** Laravel's handleRequestUsingNamedLimiter(): each limit checked and hit in order, under sha1(name + its key). */
23344
+ async #named(request2, next, name) {
23345
+ const limiter = inject(RateLimiter);
23346
+ const callback = limiter.limiter(name);
23347
+ if (callback === void 0) throw new RoutingError(`Rate limiter [${name}] is not defined.`);
23348
+ const result = await callback(request2);
23349
+ const limits = (Array.isArray(result) ? result : [result]).filter((limit) => limit.unlimited !== true);
23350
+ if (limits.length === 0) return next(request2);
23351
+ const keyed = limits.map((limit) => ({ key: sha12(name + limit.key), max: limit.maxAttempts, decay: limit.decaySeconds }));
23352
+ for (const limit of keyed) {
23353
+ if (await limiter.tooManyAttempts(limit.key, limit.max)) throw await this.#tooMany(limit.key, limit.max);
23354
+ await limiter.hit(limit.key, limit.decay);
23355
+ }
23356
+ let response2 = await next(request2);
23357
+ for (const limit of keyed) {
23358
+ response2 = withHeaders2(response2, {
23359
+ "X-RateLimit-Limit": String(limit.max),
23360
+ "X-RateLimit-Remaining": String(await limiter.remaining(limit.key, limit.max))
23361
+ });
23362
+ }
23363
+ return response2;
23364
+ }
23365
+ async #tooMany(key, max) {
23366
+ const retryAfter = await inject(RateLimiter).availableIn(key);
23367
+ return new ThrottleRequestsError({
23368
+ "X-RateLimit-Limit": String(max),
23369
+ "X-RateLimit-Remaining": "0",
23370
+ "Retry-After": String(retryAfter),
23371
+ "X-RateLimit-Reset": String(Math.floor(Date.now() / 1e3) + retryAfter)
23372
+ });
23373
+ }
23374
+ async #numbered(request2, next, maxAttempts, decayMinutes, prefix) {
22505
23375
  const max = Number(maxAttempts);
22506
23376
  const decay = Number(decayMinutes);
22507
23377
  if (maxAttempts.trim() === "" || !Number.isInteger(max) || max < 0 || decayMinutes.trim() === "" || !Number.isFinite(decay) || decay <= 0) {
22508
23378
  throw new RoutingError(
22509
- `Invalid throttle parameters "${maxAttempts},${decayMinutes}": use throttle:<maxAttempts>,<decayMinutes>[,<prefix>] (named rate limiters are not supported).`
23379
+ `Invalid throttle parameters "${maxAttempts},${decayMinutes}": use throttle:<maxAttempts>,<decayMinutes>[,<prefix>] or throttle:<name>.`
22510
23380
  );
22511
23381
  }
22512
23382
  const limiter = inject(RateLimiter);
22513
23383
  const key = prefix + await this.resolveRequestSignature(request2);
22514
- if (await limiter.tooManyAttempts(key, max)) {
22515
- const retryAfter = await limiter.availableIn(key);
22516
- throw new ThrottleRequestsError({
22517
- "X-RateLimit-Limit": String(max),
22518
- "X-RateLimit-Remaining": "0",
22519
- "Retry-After": String(retryAfter),
22520
- "X-RateLimit-Reset": String(Math.floor(Date.now() / 1e3) + retryAfter)
22521
- });
22522
- }
23384
+ if (await limiter.tooManyAttempts(key, max)) throw await this.#tooMany(key, max);
22523
23385
  await limiter.hit(key, Math.round(decay * 60));
22524
23386
  const response2 = await next(request2);
22525
23387
  return withHeaders2(response2, {
@@ -22632,9 +23494,8 @@ var RoutingServiceProvider = class extends ServiceProvider {
22632
23494
  };
22633
23495
 
22634
23496
  // ../Session/dist/index.js
22635
- import { mkdir as mkdir6, readdir as readdir3, readFile as readFile4, rename as rename3, rm as rm3, stat as stat3, writeFile as writeFile7 } from "fs/promises";
23497
+ import { mkdir as mkdir6, readdir as readdir3, readFile as readFile5, rename as rename3, rm as rm3, stat as stat3, writeFile as writeFile8 } from "fs/promises";
22636
23498
  import { join as join14 } from "path";
22637
- import { Redis as Redis3 } from "ioredis";
22638
23499
  import { randomInt as randomInt3 } from "crypto";
22639
23500
  import { timingSafeEqual as timingSafeEqual7 } from "crypto";
22640
23501
  var unique = (values) => [...new Set(values)];
@@ -22877,7 +23738,7 @@ var FileSessionHandler = class {
22877
23738
  try {
22878
23739
  const { mtimeMs } = await stat3(file);
22879
23740
  if (mtimeMs < this.clock() - this.minutes * 6e4) return "";
22880
- return await readFile4(file, "utf8");
23741
+ return await readFile5(file, "utf8");
22881
23742
  } catch {
22882
23743
  return "";
22883
23744
  }
@@ -22886,7 +23747,7 @@ var FileSessionHandler = class {
22886
23747
  if (!VALID_ID.test(id)) return;
22887
23748
  await mkdir6(this.path, { recursive: true });
22888
23749
  const temporary = join14(this.path, `.${id}.${Str.random(8)}.tmp`);
22889
- await writeFile7(temporary, data, "utf8");
23750
+ await writeFile8(temporary, data, "utf8");
22890
23751
  await rename3(temporary, join14(this.path, id));
22891
23752
  }
22892
23753
  async destroy(id) {
@@ -23032,23 +23893,27 @@ var RedisSessionHandler = class {
23032
23893
  client;
23033
23894
  minutes;
23034
23895
  prefix;
23896
+ async redis() {
23897
+ return typeof this.client === "function" ? this.client() : this.client;
23898
+ }
23035
23899
  async read(id) {
23036
- return await this.client.get(this.prefix + id) ?? "";
23900
+ return await (await this.redis()).get(this.prefix + id) ?? "";
23037
23901
  }
23038
23902
  async write(id, data) {
23039
- await this.client.set(this.prefix + id, data, "EX", Math.max(1, this.minutes * 60));
23903
+ await (await this.redis()).set(this.prefix + id, data, "EX", Math.max(1, this.minutes * 60));
23040
23904
  }
23041
23905
  async destroy(id) {
23042
- await this.client.del(this.prefix + id);
23906
+ await (await this.redis()).del(this.prefix + id);
23043
23907
  }
23044
23908
  /** Redis expires keys itself. */
23045
23909
  async gc() {
23046
23910
  }
23047
23911
  };
23048
- function makeRedisClient3(config2 = {}) {
23912
+ async function makeRedisClient3(config2 = {}) {
23913
+ const { Redis } = await importOptional("ioredis", "The redis session driver", () => import("ioredis"));
23049
23914
  const options = {};
23050
23915
  for (const key of ["host", "port", "password", "username", "db", "lazyConnect"]) if (config2[key] !== void 0) options[key] = config2[key];
23051
- return typeof config2.url === "string" && config2.url !== "" ? new Redis3(config2.url, options) : new Redis3(options);
23916
+ return typeof config2.url === "string" && config2.url !== "" ? new Redis(config2.url, options) : new Redis(options);
23052
23917
  }
23053
23918
  var SessionManager = class {
23054
23919
  constructor(app2) {
@@ -23087,7 +23952,7 @@ var SessionManager = class {
23087
23952
  case "file":
23088
23953
  return this.#share("file", () => new FileSessionHandler(config2.files ?? "storage/framework/sessions", lifetime));
23089
23954
  case "redis":
23090
- return this.#share("redis", () => new RedisSessionHandler(this.redis(), lifetime));
23955
+ return this.#share("redis", () => new RedisSessionHandler(() => this.redis(), lifetime));
23091
23956
  case "database":
23092
23957
  return new DatabaseSessionHandler(
23093
23958
  () => container.make(DatabaseManager).connection(config2.connection ?? void 0),
@@ -23108,7 +23973,10 @@ var SessionManager = class {
23108
23973
  throw new Error(`Driver [${driver}] not supported.`);
23109
23974
  }
23110
23975
  }
23111
- /** The redis client for config('session.connection') (an entry of config('database.redis'), default 'default'). */
23976
+ /**
23977
+ * The redis client for config('session.connection') (an entry of config('database.redis'), default 'default'), made
23978
+ * the first time it's asked for.
23979
+ */
23112
23980
  redis() {
23113
23981
  if (this.#redis === void 0) {
23114
23982
  const name = this.getSessionConfig().connection ?? "default";
@@ -23118,8 +23986,9 @@ var SessionManager = class {
23118
23986
  }
23119
23987
  /** Closes the redis connection, if one was opened. */
23120
23988
  async disconnect() {
23121
- await this.#redis?.quit();
23989
+ const pending = this.#redis;
23122
23990
  this.#redis = void 0;
23991
+ await (await pending?.catch(() => void 0))?.quit();
23123
23992
  }
23124
23993
  #share(driver, make) {
23125
23994
  let handler3 = this.#shared.get(driver);
@@ -23426,6 +24295,15 @@ var InvalidRuleParameterError = class extends Error {
23426
24295
  }
23427
24296
  };
23428
24297
  var FormRequest = class {
24298
+ /** Laravel's `$stopOnFirstFailure`: once a field has failed, the others aren't validated. */
24299
+ stopOnFirstFailure = false;
24300
+ /** Runs first, before authorize() and the rules: change the input here, with `request().merge()`. */
24301
+ prepareForValidation() {
24302
+ }
24303
+ /** Callbacks that run once the rules have (whether they passed or not); each may add failures with `fail()`. */
24304
+ after() {
24305
+ return [];
24306
+ }
23429
24307
  authorize() {
23430
24308
  return true;
23431
24309
  }
@@ -23437,19 +24315,25 @@ var FormRequest = class {
23437
24315
  }
23438
24316
  /**
23439
24317
  * `const data = await StorePostRequest.validate()` (spec §4.3). Resolves the current request and the
23440
- * ValidationFactory from the active container, runs authorize() first (throwing AuthorizationErrorImpl if it
23441
- * returns false), then validates request.all() against rules()/messages()/attributes() and returns the validated
23442
- * data (or throws the 422 ValidationError — see ValidatorImpl.validated()). The data is typed from rules(): write
23443
- * it without a return type and with `as const` (`return { title: 'required|string' } as const`), so its rule
23444
- * strings keep their text; a rules() typed `Rules` gives `Record<string, unknown>`.
24318
+ * ValidationFactory from the active container, runs prepareForValidation(), then authorize() (throwing
24319
+ * AuthorizationErrorImpl if it returns false), then validates request.all() against rules()/messages()/attributes(),
24320
+ * with stopOnFirstFailure and the after() callbacks, and returns the validated data (or throws the 422
24321
+ * ValidationError — see ValidatorImpl.validated()); `request().safe()` reads it afterwards. The data is typed from
24322
+ * rules(): write it without a return type and with `as const` (`return { title: 'required|string' } as const`), so
24323
+ * its rule strings keep their text; a rules() typed `Rules` gives `Record<string, unknown>`.
23445
24324
  */
23446
24325
  static async validate() {
23447
24326
  const instance = new this();
24327
+ await instance.prepareForValidation();
23448
24328
  if (!await instance.authorize()) throw new AuthorizationErrorImpl();
23449
24329
  const request2 = inject(HttpRequest);
23450
24330
  const factory = inject(ValidationFactory);
23451
24331
  const validator = factory.make(request2.all(), await instance.rules(), instance.messages(), instance.attributes());
23452
- return validator.validated();
24332
+ validator.stopOnFirstFailure(instance.stopOnFirstFailure);
24333
+ for (const callback of instance.after()) validator.after(callback);
24334
+ const data = await validator.validated();
24335
+ request2[VALIDATED_INPUT] = data;
24336
+ return data;
23453
24337
  }
23454
24338
  };
23455
24339
  function defaultAttributeName(key) {
@@ -24595,9 +25479,13 @@ var fileRules = {
24595
25479
  };
24596
25480
  var ASCII_RE = /^[\x09\x10\x13\x0A\x0D\x20-\x7E]*$/;
24597
25481
  var HEX_COLOR_RE = /^#(?:(?:[0-9a-f]{3}){1,2}|(?:[0-9a-f]{4}){1,2})$/i;
24598
- var ALPHA_RE = /^[A-Za-z]+$/;
24599
- var ALPHA_NUM_RE = /^[A-Za-z0-9]+$/;
24600
- var ALPHA_DASH_RE = /^[A-Za-z0-9_-]+$/;
25482
+ var ALPHA_RE = /^[\p{L}\p{M}]+$/u;
25483
+ var ALPHA_NUM_RE = /^[\p{L}\p{M}\p{N}]+$/u;
25484
+ var ALPHA_DASH_RE = /^[\p{L}\p{M}\p{N}_-]+$/u;
25485
+ var ASCII_ALPHA_RE = /^[A-Za-z]+$/;
25486
+ var ASCII_ALPHA_NUM_RE = /^[A-Za-z0-9]+$/;
25487
+ var ASCII_ALPHA_DASH_RE = /^[A-Za-z0-9_-]+$/;
25488
+ var alphaRule = (unicode, ascii) => (ctx) => typeof ctx.value === "string" && (ctx.parameters[0] === "ascii" ? ascii : unicode).test(ctx.value);
24601
25489
  function isEmail(value2) {
24602
25490
  const at = value2.indexOf("@");
24603
25491
  if (at < 1 || value2.includes("@", at + 1) || /\s/.test(value2)) return false;
@@ -24702,15 +25590,9 @@ var formatRules = {
24702
25590
  messageKey: () => "doesnt_end_with",
24703
25591
  replacements: listed3
24704
25592
  },
24705
- alpha: { validate: (ctx) => typeof ctx.value === "string" && ALPHA_RE.test(ctx.value), messageKey: () => "alpha" },
24706
- alpha_num: {
24707
- validate: (ctx) => typeof ctx.value === "string" && ALPHA_NUM_RE.test(ctx.value),
24708
- messageKey: () => "alpha_num"
24709
- },
24710
- alpha_dash: {
24711
- validate: (ctx) => typeof ctx.value === "string" && ALPHA_DASH_RE.test(ctx.value),
24712
- messageKey: () => "alpha_dash"
24713
- },
25593
+ alpha: { validate: alphaRule(ALPHA_RE, ASCII_ALPHA_RE), messageKey: () => "alpha" },
25594
+ alpha_num: { validate: alphaRule(ALPHA_NUM_RE, ASCII_ALPHA_NUM_RE), messageKey: () => "alpha_num" },
25595
+ alpha_dash: { validate: alphaRule(ALPHA_DASH_RE, ASCII_ALPHA_DASH_RE), messageKey: () => "alpha_dash" },
24714
25596
  lowercase: {
24715
25597
  validate: (ctx) => (typeof ctx.value === "string" || typeof ctx.value === "number") && String(ctx.value).toLowerCase() === String(ctx.value),
24716
25598
  messageKey: () => "lowercase"
@@ -25647,10 +26529,16 @@ var ValidatorImpl = class {
25647
26529
  excludedRuns = { run: "", next: /* @__PURE__ */ new Map(), excluded: false };
25648
26530
  /** What the rules keep while one pass runs (RuleContext.cache); a new pass starts with a new one. */
25649
26531
  cache = /* @__PURE__ */ new Map();
26532
+ stopsOnFirstFailure = false;
25650
26533
  after(callback) {
25651
26534
  this.afterCallbacks.push(callback);
25652
26535
  return this;
25653
26536
  }
26537
+ /** Laravel's stopOnFirstFailure(): once a field has failed, no other field is validated; after() callbacks still run. */
26538
+ stopOnFirstFailure(stop = true) {
26539
+ this.stopsOnFirstFailure = stop;
26540
+ return this;
26541
+ }
25654
26542
  /** Lets an after() hook add a failure. */
25655
26543
  fail(field, message) {
25656
26544
  this.bag ??= new MessageBagImpl();
@@ -25684,6 +26572,10 @@ var ValidatorImpl = class {
25684
26572
  if (this.excluded.size > 0) dropExcluded(nested);
25685
26573
  return nested;
25686
26574
  }
26575
+ /** validated() as a ValidatedInput, for `only()`, `except()` and `merge()`. */
26576
+ async safe() {
26577
+ return new ValidatedInput(await this.validated());
26578
+ }
25687
26579
  /** Takes the field (with its children) out of validation and of the validated data. */
25688
26580
  exclude(field) {
25689
26581
  this.excluded.add(field);
@@ -25777,18 +26669,19 @@ var ValidatorImpl = class {
25777
26669
  async run() {
25778
26670
  this.bag = new MessageBagImpl();
25779
26671
  this.cache = /* @__PURE__ */ new Map();
25780
- for (const [pattern, parsed] of this.parsed()) {
26672
+ fields: for (const [pattern, parsed] of this.parsed()) {
25781
26673
  const names = parsed.filter((r) => r.kind === "named").map((r) => r.name);
25782
26674
  const bail = names.includes("bail");
25783
26675
  const nullable = names.includes("nullable");
25784
26676
  const sometimes = names.includes("sometimes");
25785
26677
  for (const field of this.fieldsFor(pattern)) {
25786
26678
  if (this.isExcluded(field)) continue;
26679
+ if (this.stopsOnFirstFailure && !this.bag.isEmpty()) break fields;
25787
26680
  const present2 = Arr.has(this.data, field);
25788
26681
  if (sometimes && !present2) continue;
25789
26682
  const value2 = Arr.get(this.data, field);
25790
26683
  const isNull = value2 === null || value2 === void 0;
25791
- const isBlank2 = typeof value2 === "string" && value2.trim() === "";
26684
+ const isBlank = typeof value2 === "string" && value2.trim() === "";
25792
26685
  for (const rule of parsed) {
25793
26686
  if (rule.kind === "named" && SKIPPED_MODIFIERS.has(rule.name)) continue;
25794
26687
  const builtin = rule.kind === "named" ? this.registry[rule.name] : void 0;
@@ -25800,7 +26693,7 @@ var ValidatorImpl = class {
25800
26693
  continue;
25801
26694
  }
25802
26695
  const implicit = builtin?.implicit ?? false;
25803
- if (!implicit && (!present2 || isBlank2)) continue;
26696
+ if (!implicit && (!present2 || isBlank)) continue;
25804
26697
  if (!implicit && nullable && isNull) continue;
25805
26698
  const messages = await this.runRule(rule, field, pattern, value2, names);
25806
26699
  if (messages.length > 0) {
@@ -25870,9 +26763,9 @@ var ValidationServiceProvider = class extends ServiceProvider {
25870
26763
  };
25871
26764
 
25872
26765
  // ../Vercel/dist/index.js
25873
- import { existsSync as existsSync9, readdirSync as readdirSync8, readFileSync as readFileSync3, realpathSync, statSync as statSync4 } from "fs";
25874
- import { cp, mkdir as mkdir7, rm as rm4, writeFile as writeFile8 } from "fs/promises";
25875
- import { basename as basename3, dirname as dirname8, join as join15, relative as relative7, resolve as resolve4 } from "path";
26766
+ import { existsSync as existsSync10, readdirSync as readdirSync8, readFileSync as readFileSync3, realpathSync, statSync as statSync4 } from "fs";
26767
+ import { cp, mkdir as mkdir7, rm as rm4, writeFile as writeFile9 } from "fs/promises";
26768
+ import { basename as basename4, dirname as dirname9, join as join15, relative as relative7, resolve as resolve4 } from "path";
25876
26769
  import { CronExpressionParser as CronExpressionParser2 } from "cron-parser";
25877
26770
  import { timingSafeEqual as timingSafeEqual8 } from "crypto";
25878
26771
  import { CronExpressionParser as CronExpressionParser3 } from "cron-parser";
@@ -25924,6 +26817,13 @@ import { fileURLToPath } from 'node:url'
25924
26817
 
25925
26818
  let ready
25926
26819
 
26820
+ // Vercel's waitUntil(), as @vercel/functions reads it: the request context its runtime keeps on globalThis.
26821
+ const REQUEST_CONTEXT = Symbol.for('@vercel/request-context')
26822
+ function waitUntil() {
26823
+ const context = globalThis[REQUEST_CONTEXT]?.get?.()
26824
+ return typeof context?.waitUntil === 'function' ? (work) => context.waitUntil(work) : undefined
26825
+ }
26826
+
25927
26827
  async function boot() {
25928
26828
  // Vercel's disk is read-only, so a log file can't open; stderr is what Vercel's log view shows.
25929
26829
  process.env.LOG_CHANNEL ??= 'stderr'
@@ -25941,7 +26841,7 @@ async function boot() {
25941
26841
  const config = app.make(ConfigRepository)
25942
26842
  const proxies = config.get('http.trusted_proxies', [])
25943
26843
  if (proxies === undefined || proxies === null || proxies.length === 0) config.set('http.trusted_proxies', '*')
25944
- return nodeRequestHandler(app, { fallbackHost: 'localhost' })
26844
+ return nodeRequestHandler(app, { fallbackHost: 'localhost', waitUntil })
25945
26845
  }
25946
26846
 
25947
26847
  export default async function handler(req, res) {
@@ -25967,39 +26867,39 @@ var APP_FOLDERS = ["app", "bootstrap", "config", "routes", "resources", "lang",
25967
26867
  var APP_FILES = ["package.json", "tsconfig.json"];
25968
26868
  var BUILD_FILES = ["manifest.json"];
25969
26869
  var VITE_CONFIGS = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
25970
- var isEnvFile = (path) => /^\.env(\..*)?$/.test(basename3(path));
25971
- var isSqliteFile = (path) => /\.(sqlite3?|db)(-wal|-shm|-journal)?$/.test(basename3(path));
26870
+ var isEnvFile = (path) => /^\.env(\..*)?$/.test(basename4(path));
26871
+ var isSqliteFile = (path) => /\.(sqlite3?|db)(-wal|-shm|-journal)?$/.test(basename4(path));
25972
26872
  var PLATFORM_NAMES = { darwin: "macOS", win32: "Windows" };
25973
26873
  async function buildVercelOutput(app2, options = {}) {
25974
26874
  const base = app2.basePath();
25975
26875
  const publicPath = app2.publicPath();
25976
- if (existsSync9(join15(publicPath, "hot"))) {
26876
+ if (existsSync10(join15(publicPath, "hot"))) {
25977
26877
  throw new Error("The Vite dev server is running (public/hot exists): stop `npm run dev` and build the assets with `npm run build` first.");
25978
26878
  }
25979
- if (VITE_CONFIGS.some((file) => existsSync9(join15(base, file))) && !existsSync9(join15(publicPath, "build/manifest.json"))) {
26879
+ if (VITE_CONFIGS.some((file) => existsSync10(join15(base, file))) && !existsSync10(join15(publicPath, "build/manifest.json"))) {
25980
26880
  throw new Error("The assets aren't built (public/build/manifest.json is missing): run `npm run build` first.");
25981
26881
  }
25982
26882
  const output = resolve4(base, options.output ?? ".vercel/output");
25983
26883
  await rm4(output, { recursive: true, force: true });
25984
26884
  const staticFolder = join15(output, "static");
25985
26885
  await mkdir7(staticFolder, { recursive: true });
25986
- if (existsSync9(publicPath)) {
25987
- await cp(publicPath, staticFolder, { recursive: true, filter: (source) => basename3(source) !== "hot" && !isEnvFile(source) && isPublicAsset(relative7(publicPath, source)) });
26886
+ if (existsSync10(publicPath)) {
26887
+ await cp(publicPath, staticFolder, { recursive: true, filter: (source) => basename4(source) !== "hot" && !isEnvFile(source) && isPublicAsset(relative7(publicPath, source)) });
25988
26888
  }
25989
26889
  const fn = join15(output, "functions/index.func");
25990
26890
  for (const folder of APP_FOLDERS) {
25991
26891
  const filter = (source) => !isEnvFile(source) && !(folder === "database" && isSqliteFile(source));
25992
- if (existsSync9(join15(base, folder))) await cp(join15(base, folder), join15(fn, folder), { recursive: true, filter });
26892
+ if (existsSync10(join15(base, folder))) await cp(join15(base, folder), join15(fn, folder), { recursive: true, filter });
25993
26893
  }
25994
- for (const file of APP_FILES) if (existsSync9(join15(base, file))) await cp(join15(base, file), join15(fn, file));
26894
+ for (const file of APP_FILES) if (existsSync10(join15(base, file))) await cp(join15(base, file), join15(fn, file));
25995
26895
  for (const file of BUILD_FILES) {
25996
26896
  const source = join15(publicPath, "build", file);
25997
- if (existsSync9(source)) await cp(source, join15(fn, relative7(base, publicPath), "build", file));
26897
+ if (existsSync10(source)) await cp(source, join15(fn, relative7(base, publicPath), "build", file));
25998
26898
  }
25999
26899
  await copyDependencies(base, fn);
26000
- await writeFile8(join15(fn, "index.mjs"), LAUNCHER);
26900
+ await writeFile9(join15(fn, "index.mjs"), LAUNCHER);
26001
26901
  const vcConfig = { runtime: options.runtime ?? "nodejs22.x", handler: "index.mjs", launcherType: "Nodejs", shouldAddHelpers: false, supportsResponseStreaming: true };
26002
- await writeFile8(join15(fn, ".vc-config.json"), `${JSON.stringify(vcConfig, null, 2)}
26902
+ await writeFile9(join15(fn, ".vc-config.json"), `${JSON.stringify(vcConfig, null, 2)}
26003
26903
  `);
26004
26904
  const { crons, cronWarnings } = await scheduleCron(app2, options.cron);
26005
26905
  const config2 = {
@@ -26012,7 +26912,7 @@ async function buildVercelOutput(app2, options = {}) {
26012
26912
  { src: "/(.*)", dest: "/index" }
26013
26913
  ]
26014
26914
  };
26015
- await writeFile8(join15(output, "config.json"), `${JSON.stringify(config2, null, 2)}
26915
+ await writeFile9(join15(output, "config.json"), `${JSON.stringify(config2, null, 2)}
26016
26916
  `);
26017
26917
  const functionBytes = sizeOf2(fn);
26018
26918
  const limit = options.maxFunctionBytes ?? VERCEL_FUNCTION_LIMIT;
@@ -26061,7 +26961,7 @@ async function copyDependencies(base, fn) {
26061
26961
  await cp(real, destination, {
26062
26962
  recursive: true,
26063
26963
  dereference: true,
26064
- filter: (source) => source === real || !["node_modules", ".bin", ".git"].includes(basename3(source))
26964
+ filter: (source) => source === real || !["node_modules", ".bin", ".git"].includes(basename4(source))
26065
26965
  });
26066
26966
  const pkg = JSON.parse(readFileSync3(join15(real, "package.json"), "utf8"));
26067
26967
  for (const dependency of [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.optionalDependencies ?? {})]) {
@@ -26071,10 +26971,10 @@ async function copyDependencies(base, fn) {
26071
26971
  for (const name of [...Object.keys(manifest.dependencies ?? {}), "tsx"]) await visit(name, base, join15(fn, "node_modules"));
26072
26972
  }
26073
26973
  function locate(name, from) {
26074
- for (let dir = from; ; dir = dirname8(dir)) {
26075
- const candidate = basename3(dir) === "node_modules" ? join15(dir, name) : join15(dir, "node_modules", name);
26076
- if (existsSync9(join15(candidate, "package.json"))) return candidate;
26077
- if (dirname8(dir) === dir) return void 0;
26974
+ for (let dir = from; ; dir = dirname9(dir)) {
26975
+ const candidate = basename4(dir) === "node_modules" ? join15(dir, name) : join15(dir, "node_modules", name);
26976
+ if (existsSync10(join15(candidate, "package.json"))) return candidate;
26977
+ if (dirname9(dir) === dir) return void 0;
26078
26978
  }
26079
26979
  }
26080
26980
  function sizeOf2(folder) {
@@ -26113,17 +27013,17 @@ var VercelServiceProvider = class extends ServiceProvider {
26113
27013
  };
26114
27014
 
26115
27015
  // ide/IdeInfoCommand.ts
26116
- import { existsSync as existsSync11, readdirSync as readdirSync10, readFileSync as readFileSync4 } from "fs";
26117
- import { join as join17, relative as relative9, sep as sep7 } from "path";
27016
+ import { existsSync as existsSync12, readdirSync as readdirSync10, readFileSync as readFileSync4 } from "fs";
27017
+ import { join as join17, relative as relative9, sep as sep8 } from "path";
26118
27018
 
26119
27019
  // ide/sections.ts
26120
- import { existsSync as existsSync10, readdirSync as readdirSync9 } from "fs";
26121
- import { join as join16, relative as relative8, sep as sep6 } from "path";
27020
+ import { existsSync as existsSync11, readdirSync as readdirSync9 } from "fs";
27021
+ import { join as join16, relative as relative8, sep as sep7 } from "path";
26122
27022
  import { parse as parse2 } from "dotenv";
26123
27023
  var SECRET = /key|secret|password|token|credential|salt|private/i;
26124
27024
  var CREDENTIALS = /^[a-z][a-z0-9+.-]*:\/\/[^/?#\s]*@/i;
26125
27025
  var byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
26126
- var posix3 = (path) => path.split(sep6).join("/");
27026
+ var posix3 = (path) => path.split(sep7).join("/");
26127
27027
  function commandSection(all) {
26128
27028
  return Object.entries(all).map(([name, command]) => {
26129
27029
  const signature = parseSignature(command.signature);
@@ -26159,7 +27059,7 @@ function envSection(env3, example) {
26159
27059
  function viewSection(paths, hints, extensions, basePath) {
26160
27060
  const views = /* @__PURE__ */ new Map();
26161
27061
  const collect2 = (root, prefix) => {
26162
- if (!existsSync10(root)) return;
27062
+ if (!existsSync11(root)) return;
26163
27063
  for (const item of readdirSync9(root, { recursive: true, withFileTypes: true })) {
26164
27064
  if (!item.isFile()) continue;
26165
27065
  const extension = extensions.find((candidate) => item.name.endsWith(`.${candidate}`));
@@ -26175,8 +27075,8 @@ function viewSection(paths, hints, extensions, basePath) {
26175
27075
  }
26176
27076
 
26177
27077
  // ide/IdeInfoCommand.ts
26178
- var posix4 = (path) => path.split(sep7).join("/");
26179
- var read = (file) => existsSync11(file) ? readFileSync4(file, "utf8") : null;
27078
+ var posix4 = (path) => path.split(sep8).join("/");
27079
+ var read = (file) => existsSync12(file) ? readFileSync4(file, "utf8") : null;
26180
27080
  var IdeInfoCommand = class extends Command {
26181
27081
  signature = "ide:info {--pretty : Indent the JSON}";
26182
27082
  description = "Describe the application for editors, as JSON";
@@ -26209,7 +27109,7 @@ function describe(app2, container) {
26209
27109
  const get = (key, fallback) => config2 ? config2.get(key, fallback) : fallback;
26210
27110
  const relativeTo = (file) => posix4(relative9(basePath, file));
26211
27111
  const configDirectory = app2.configPath();
26212
- const configFiles = existsSync11(configDirectory) ? readdirSync10(configDirectory).filter((file) => /\.(ts|js|mjs)$/.test(file)).map((file) => relativeTo(join17(configDirectory, file))) : [];
27112
+ const configFiles = existsSync12(configDirectory) ? readdirSync10(configDirectory).filter((file) => /\.(ts|js|mjs)$/.test(file)).map((file) => relativeTo(join17(configDirectory, file))) : [];
26213
27113
  const factory = optional(ViewFactory);
26214
27114
  const finder = factory instanceof Factory ? factory.getFinder() : void 0;
26215
27115
  const registry2 = optional(ClassRegistry);
@@ -26223,7 +27123,7 @@ function describe(app2, container) {
26223
27123
  }) : [];
26224
27124
  const validation = optional(ValidationFactory);
26225
27125
  const pagePaths = get("inertia.pages.paths", []);
26226
- const inertia2 = pagePaths.some((path) => existsSync11(path)) ? { pages: pageNames(pagePaths, get("inertia.pages.extensions", [])).map((page) => ({ name: page.name, file: relativeTo(page.file) })) } : null;
27126
+ const inertia2 = pagePaths.some((path) => existsSync12(path)) ? { pages: pageNames(pagePaths, get("inertia.pages.extensions", [])).map((page) => ({ name: page.name, file: relativeTo(page.file) })) } : null;
26227
27127
  return {
26228
27128
  schema: 1,
26229
27129
  oriel: { version: app2.version, runtime: process.versions.bun ? "bun" : "node", runtimeVersion: process.versions.bun ?? process.versions.node, environment: app2.environment(), basePath },
@@ -26303,7 +27203,6 @@ function Notifiable(Base) {
26303
27203
  return RoutesNotifications(HasDatabaseNotifications(Base));
26304
27204
  }
26305
27205
  export {
26306
- API_ROUTES_STUB,
26307
27206
  AboutCommand,
26308
27207
  AbstractPaginator,
26309
27208
  AccessGate,
@@ -26311,6 +27210,7 @@ export {
26311
27210
  AllMailersFailedError,
26312
27211
  AlwaysProp,
26313
27212
  AnonymousNotifiable,
27213
+ AnonymousResourceCollection,
26314
27214
  Application3 as Application,
26315
27215
  ApplicationBuilder,
26316
27216
  ArgonHasher,
@@ -26363,7 +27263,6 @@ export {
26363
27263
  ClassNameMap,
26364
27264
  ClassRegistry2 as ClassRegistry,
26365
27265
  ClosureCommand,
26366
- ClosureKernel,
26367
27266
  Collection,
26368
27267
  ColumnDefinition,
26369
27268
  Command,
@@ -26458,6 +27357,7 @@ export {
26458
27357
  GenericLock,
26459
27358
  Grammar,
26460
27359
  GroupRegistrar,
27360
+ HandleCors,
26461
27361
  HandlePrecognitiveRequests,
26462
27362
  HasApiTokens,
26463
27363
  HasDatabaseNotifications,
@@ -26504,12 +27404,18 @@ export {
26504
27404
  ItemNotFoundError,
26505
27405
  JOBS_TABLE_MIGRATION,
26506
27406
  JobClassNotFoundError,
27407
+ JobFailed,
27408
+ JobProcessed,
27409
+ JobProcessing,
27410
+ JobQueued,
26507
27411
  JobSerializationError,
26508
27412
  JoinClause,
27413
+ JsonResource,
26509
27414
  KEY_GENERATE_SIGNATURE,
26510
27415
  LEVEL_SEVERITY,
26511
27416
  LazyCollection,
26512
27417
  LengthAwarePaginator,
27418
+ Limit,
26513
27419
  ListCommand,
26514
27420
  Live,
26515
27421
  LiveComponentManager,
@@ -26566,6 +27472,8 @@ export {
26566
27472
  MemoryStore,
26567
27473
  MergeProp,
26568
27474
  MessageBagImpl,
27475
+ MessageSending,
27476
+ MessageSent,
26569
27477
  MethodNotAllowedHttpError,
26570
27478
  MethodNotCallableError,
26571
27479
  MiddlewareConfiguration,
@@ -26578,6 +27486,7 @@ export {
26578
27486
  MissingModelError,
26579
27487
  MissingPackageError,
26580
27488
  MissingRecipientError,
27489
+ MissingValue,
26581
27490
  Model,
26582
27491
  ModelNotFoundError,
26583
27492
  ModelRegistry,
@@ -26597,7 +27506,10 @@ export {
26597
27506
  Dispatcher3 as NotificationDispatcherImpl,
26598
27507
  NotificationDispatcherUnavailableError,
26599
27508
  NotificationFacade,
27509
+ NotificationFailed,
26600
27510
  NotificationQueueUnavailableError,
27511
+ NotificationSending,
27512
+ NotificationSent,
26601
27513
  NotificationsServiceProvider,
26602
27514
  NullFailedJobProvider,
26603
27515
  NullLogger,
@@ -26628,6 +27540,7 @@ export {
26628
27540
  PipelineServiceProvider,
26629
27541
  Pivot,
26630
27542
  PostgresSchemaGrammar,
27543
+ PreventRequestsDuringMaintenance,
26631
27544
  PropertyNotUpdatableError,
26632
27545
  PropsResolver,
26633
27546
  ProviderBootError,
@@ -26662,7 +27575,10 @@ export {
26662
27575
  RelationNotLoadedError,
26663
27576
  RenameClasses,
26664
27577
  Repository,
27578
+ RequirePassword,
26665
27579
  ResetPassword,
27580
+ ResourceCollection,
27581
+ ResourceResponse,
26666
27582
  Route,
26667
27583
  RouteDefinition,
26668
27584
  RouteModelNotFoundError,
@@ -26686,6 +27602,10 @@ export {
26686
27602
  ScheduleRunCommand,
26687
27603
  ScheduleWorkCommand,
26688
27604
  ScheduledEventImpl,
27605
+ ScheduledTaskFailed,
27606
+ ScheduledTaskFinished,
27607
+ ScheduledTaskSkipped,
27608
+ ScheduledTaskStarting,
26689
27609
  Schema,
26690
27610
  SchemaBuilder,
26691
27611
  SchemaBuilderToken,
@@ -26731,6 +27651,7 @@ export {
26731
27651
  TokenMismatchError,
26732
27652
  TokenRepository,
26733
27653
  TrimStrings,
27654
+ TrustHosts,
26734
27655
  TsxView,
26735
27656
  TwoFactor,
26736
27657
  TwoFactorAppAlreadyEnabledError,
@@ -26772,6 +27693,7 @@ export {
26772
27693
  VERCEL_FUNCTION_LIMIT,
26773
27694
  ValidateSignature,
26774
27695
  Validated,
27696
+ ValidatedInput,
26775
27697
  ValidationErrorImpl,
26776
27698
  ValidationException,
26777
27699
  ValidationFactoryImpl,
@@ -26801,11 +27723,8 @@ export {
26801
27723
  abort,
26802
27724
  abortIf,
26803
27725
  abortUnless,
26804
- addApiRouting,
26805
27726
  allowGuests,
26806
27727
  app,
26807
- applyExceptionCallbacks,
26808
- applyMiddlewareCallbacks,
26809
27728
  applyReplacements,
26810
27729
  auth,
26811
27730
  back,
@@ -26813,16 +27732,13 @@ export {
26813
27732
  blobStoreUrl,
26814
27733
  buildVercelOutput,
26815
27734
  builtinRules,
26816
- bunRuntime,
26817
27735
  cache,
26818
27736
  castGet,
26819
27737
  castSet,
26820
27738
  classNameOf,
26821
27739
  classNames,
26822
- clientAddress,
26823
27740
  collect,
26824
27741
  columnKey,
26825
- compareRoutes,
26826
27742
  componentName,
26827
27743
  config,
26828
27744
  contentDisposition,
@@ -26838,10 +27754,8 @@ export {
26838
27754
  csrfToken,
26839
27755
  currentContainer,
26840
27756
  currentLogContext,
26841
- currentRequest,
26842
27757
  currentVite,
26843
27758
  databaseConfigDefaults,
26844
- debugPage,
26845
27759
  decodePayload,
26846
27760
  decrypt,
26847
27761
  defaultAttributeName,
@@ -26852,14 +27766,12 @@ export {
26852
27766
  delaySeconds,
26853
27767
  describeError,
26854
27768
  deserialize,
26855
- detectRuntime,
26856
27769
  discoverClasses,
26857
27770
  discoverFactories,
26858
27771
  discoverJobs,
26859
27772
  discoverListeners,
26860
27773
  discoverPolicies,
26861
27774
  dispatch,
26862
- dispatchRoute,
26863
27775
  dispatchSync,
26864
27776
  e,
26865
27777
  encodePayload,
@@ -26868,34 +27780,25 @@ export {
26868
27780
  env,
26869
27781
  errorBagFrom,
26870
27782
  errors,
26871
- escapeHtml,
26872
27783
  event,
26873
- exceedsJsonDepth,
26874
27784
  expandWildcardKeys,
26875
27785
  exportSite,
26876
- extensionFromMime,
26877
27786
  facade,
26878
27787
  fake,
26879
- filterRouteList,
26880
27788
  formatAddress,
26881
27789
  formatDate,
26882
27790
  formatDateTime,
26883
- formatRouteList,
26884
27791
  formatTimestamp,
26885
- fromEntries,
26886
27792
  generateAppKey,
26887
27793
  generateModelTypes,
26888
27794
  getMorphAlias,
26889
27795
  getMorphedModel,
26890
27796
  guessTable,
26891
27797
  hashInfo,
26892
- healthResponse,
26893
27798
  inertia,
26894
27799
  inertiaBody,
26895
27800
  inertiaHead,
26896
27801
  inject,
26897
- ipMatches,
26898
- isBlank,
26899
27802
  isBun,
26900
27803
  isDateCast,
26901
27804
  isElement,
@@ -26921,35 +27824,22 @@ export {
26921
27824
  logger,
26922
27825
  makeFailedJobProvider,
26923
27826
  meetsLevel,
26924
- mergeGroup,
26925
27827
  mergeLogContext,
26926
- mergeRecursive,
26927
27828
  methodField,
26928
27829
  migrationDatePrefix,
26929
- minimalPage,
26930
27830
  modelEventName,
26931
27831
  morphMap,
26932
27832
  nodeRequestHandler,
26933
27833
  normalizeAddress,
26934
27834
  normalizeAddresses,
26935
27835
  normalizeBackoff,
26936
- normalizeLists,
26937
- normalizePath,
26938
- normalizeUri,
26939
27836
  now,
26940
27837
  old,
26941
27838
  openSqlite,
26942
- optionalCookieJar,
26943
- optionalSession,
26944
- orderForBindings,
26945
- parseArgv,
26946
- parseBracketKey,
26947
27839
  parseCookieHeader,
26948
27840
  parseDateTime,
26949
27841
  parseKey,
26950
- parseParameters,
26951
27842
  parseRuleSpec,
26952
- parseSignature,
26953
27843
  passwordVerify,
26954
27844
  persistentMiddleware,
26955
27845
  prepareValue,
@@ -26959,36 +27849,28 @@ export {
26959
27849
  raw2 as rawSql,
26960
27850
  rawWithBindings,
26961
27851
  redirect,
26962
- registerHttpCommands,
26963
27852
  registerKeyGenerateCommand,
26964
27853
  registerMigrationCommands,
26965
27854
  registerModelTypesCommand,
26966
27855
  registerQueueCommands,
26967
27856
  registerStorageLinkCommand,
26968
27857
  renderContent,
26969
- renderError,
26970
27858
  renderToStream,
26971
27859
  renderToString,
27860
+ report,
26972
27861
  request,
26973
- requestScope,
26974
- resolveArguments,
27862
+ rescue,
26975
27863
  resolveDiskPath,
26976
- resolveMiddleware,
26977
27864
  resolveMorphClass,
26978
- resolveOptions,
26979
- resourceRoutes,
26980
27865
  response,
26981
27866
  restoreJob,
26982
27867
  restoreValue,
26983
27868
  retry,
26984
27869
  roundTrip,
26985
27870
  route,
26986
- routeListRows,
26987
27871
  runConsole,
26988
27872
  runConsoleAndExit,
26989
- runMiddleware,
26990
27873
  runSeeder,
26991
- sanitize,
26992
27874
  sendEmailVerificationUsing,
26993
27875
  sendNotification,
26994
27876
  serialize,
@@ -26997,36 +27879,21 @@ export {
26997
27879
  serializeDate,
26998
27880
  serializeValue,
26999
27881
  serve,
27000
- serveBun,
27001
- serveNode,
27002
- servePublicFile,
27003
27882
  session,
27004
- setClientAddress,
27005
- stackFrames,
27006
- statusFor,
27007
- statusText,
27008
27883
  storageLinkHandler,
27009
27884
  styleString,
27010
- substituteBindings,
27011
- suggest,
27012
- summarizeValidation,
27013
27885
  tap,
27014
27886
  toNotifiableList,
27015
- toResponse,
27016
- toWebRequest,
27017
27887
  tokenableType,
27018
27888
  totpCode,
27019
- transformLeaves,
27020
27889
  url,
27021
27890
  usePaginationResolvers,
27022
- validateRequiredArguments,
27023
27891
  value,
27024
27892
  view,
27025
27893
  vite,
27026
27894
  viteReactRefresh,
27027
27895
  withHeaders,
27028
- workerOptionsFrom,
27029
- writeResponse
27896
+ workerOptionsFrom
27030
27897
  };
27031
27898
  /*!
27032
27899
  * Laravel's default notification mail (the `notifications::email` view in the `mail::` markdown components with the