@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
@@ -1,5 +1,5 @@
1
1
  import { Htmlable, OrielError, ErrorKind, View as View$1, ViewFactory } from './contracts.js';
2
- import { F as Facade, S as ServiceProvider } from './index.d-lffxurFs.js';
2
+ import { F as Facade, S as ServiceProvider } from './index.d-DA-Iu2a2.js';
3
3
 
4
4
  /** Marks the objects jsx() returns (Symbol.for, so two copies of the package agree). */
5
5
  declare const ELEMENT: unique symbol;
@@ -1,3 +1,3 @@
1
- export { a as Fragment, H as HtmlAttributes, J as JSX, u as jsx, w as jsxs } from './jsx-runtime-Bc5KJzwb.js';
1
+ export { a as Fragment, H as HtmlAttributes, J as JSX, u as jsx, w as jsxs } from './jsx-runtime-CenT41Y0.js';
2
2
  import './contracts.js';
3
- import './index.d-lffxurFs.js';
3
+ import './index.d-DA-Iu2a2.js';
@@ -2,9 +2,9 @@ import {
2
2
  Fragment,
3
3
  jsx,
4
4
  jsxs
5
- } from "./chunk-GCMPAXIK.js";
6
- import "./chunk-FVI6X3VJ.js";
7
- import "./chunk-BKA5F3TH.js";
5
+ } from "./chunk-3QHTNAMZ.js";
6
+ import "./chunk-YNDMTTWL.js";
7
+ import "./chunk-6AXJB4CD.js";
8
8
  export {
9
9
  Fragment,
10
10
  jsx,
@@ -1,5 +1,5 @@
1
- import { BusDispatcher, Job, PendingBatchOptions, Class, PendingChain, PendingBatch, Batch, EventDispatcher, Listener, MailManager, Mailable, Address, MailRecipient, Mailer, PendingMail, SentMessage, MailTransport, NotificationDispatcher, Notifiable, Notification, NotificationChannel, QueueManager, QueuePayload, Queue, QueueJob, FilesystemManager, Filesystem, PutOptions, UploadedFile, Application, Session, View, Authenticatable, Container, AuthFactory, InertiaPage, ServiceProvider, ServiceProviderClass, DatabaseManager, ModelInstance, Row, Encrypter, Token, ExceptionHandler, ViewFactory, RouteName, RouteArguments, Rules, InferValidatedType, MessageBag, LiveSnapshot, LiveEffects, OrielError, ErrorKind, Htmlable, LiveManager, HttpRequest, LiveUpdateRequest, LiveUpdateResponse, MiddlewareClass, Router } from './contracts.js';
2
- import { S as ServiceProvider$1 } from './index.d-lffxurFs.js';
1
+ import { BusDispatcher, Job, PendingBatchOptions, Class, PendingChain, PendingBatch, Batch, EventDispatcher, Listener, MailManager, Mailable, Address, MailRecipient, Mailer, PendingMail, SentMessage, MailTransport, NotificationDispatcher, Notifiable, Notification, NotificationChannel, QueueManager, QueuePayload, Queue, QueueJob, QueueJobEvent, QueueJobFailedEvent, FilesystemManager, Filesystem, PutOptions, UploadedFile, Application, Session, View, Authenticatable, Container, AuthFactory, InertiaPage, ServiceProvider, ServiceProviderClass, DatabaseManager, ModelInstance, Row, Encrypter, Token, ExceptionHandler, ViewFactory, RouteName, RouteArguments, Rules, InferValidatedType, MessageBag, LiveSnapshot, LiveEffects, OrielError, ErrorKind, Htmlable, LiveManager, HttpRequest, LiveUpdateRequest, LiveUpdateResponse, MiddlewareClass, Router } from './contracts.js';
2
+ import { S as ServiceProvider$1 } from './index.d-DA-Iu2a2.js';
3
3
 
4
4
  /** A date the tests travel to: a Date, an ISO string or milliseconds since the epoch. */
5
5
  type TravelDate = Date | string | number;
@@ -861,6 +861,10 @@ declare class QueueFake implements QueueManager {
861
861
  /** Removes the jobs size() counts and returns how many. */
862
862
  clear(queue?: string): Promise<number>;
863
863
  extend(_driver: string, _factory: (config: Record<string, unknown>) => Queue): void;
864
+ /** The real manager's, so a job pushed past the fake still reaches the callback. */
865
+ before(callback: (event: QueueJobEvent) => unknown): void;
866
+ after(callback: (event: QueueJobEvent) => unknown): void;
867
+ failing(callback: (event: QueueJobFailedEvent) => unknown): void;
864
868
  /** Pushed at least once; a number asserts the count; a filter gets (job, queue, connection). */
865
869
  assertPushed<J extends Job>(job: Target<J>, callback?: CountOrFilter<[J, string | undefined, string | undefined]>): void;
866
870
  assertPushedTimes<J extends Job>(job: Target<J>, times?: number): void;
package/dist/testing.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { V as AnonymousNotifiable, X as AssertableInertia, Y as AssertableJson, Z as BatchRecord, _ as BootOptions, B as BusFake, $ as CountOrFilter, a0 as DatabaseMigrations, a1 as DatabaseTestOptions, a2 as DatabaseTransactions, a3 as DispatchedEvent, E as EventFake, a4 as ExpectedErrors, a5 as ExpectedListener, a6 as FakeDisk, a7 as FakeFile, a8 as HttpClient, a9 as InteractsWithApplication, aa as InteractsWithConsole, ab as InteractsWithDatabase, ac as InteractsWithTime, ad as JsonStructure, L as Live, M as MailFake, ae as MailRecord, af as MakesHttpRequests, N as NotificationFake, ag as PendingCommand, ah as PushedJob, Q as QueueFake, ai as RefreshDatabase, aj as RefreshDatabaseState, ak as RequestData, al as RequestOptions, am as ResponseContext, an as ResponseCookie, ao as SentNotification, S as StorageFake, ap as TESTING_ENVIRONMENT, aq as TableOrModel, ar as Target, as as TestCase, at as TestHooks, au as TestResponse, av as TestTrait, z as Testable, aw as TravelDate, ax as Wormhole, ay as actingAsAuthFactory, az as addresses, aA as applyEnvironment, aB as cookieHeader, aC as cookiePrefix, aD as decryptCookie, aE as encryptCookie, aF as flatten, aG as freezeSecond, aH as freezeTime, aI as guessMimeType, aJ as inertiaPageOf, aK as install, aL as isExpired, aM as matches, aN as nameOf, aO as recordingExceptionHandler, aP as recordingViewFactory, aQ as responseCookies, aR as runCommand, aS as testingConfig, aT as travel, aU as travelBack, aV as travelTo, aW as usingInMemoryDatabase } from './testing-CVpo7aRl.js';
1
+ export { V as AnonymousNotifiable, X as AssertableInertia, Y as AssertableJson, Z as BatchRecord, _ as BootOptions, B as BusFake, $ as CountOrFilter, a0 as DatabaseMigrations, a1 as DatabaseTestOptions, a2 as DatabaseTransactions, a3 as DispatchedEvent, E as EventFake, a4 as ExpectedErrors, a5 as ExpectedListener, a6 as FakeDisk, a7 as FakeFile, a8 as HttpClient, a9 as InteractsWithApplication, aa as InteractsWithConsole, ab as InteractsWithDatabase, ac as InteractsWithTime, ad as JsonStructure, L as Live, M as MailFake, ae as MailRecord, af as MakesHttpRequests, N as NotificationFake, ag as PendingCommand, ah as PushedJob, Q as QueueFake, ai as RefreshDatabase, aj as RefreshDatabaseState, ak as RequestData, al as RequestOptions, am as ResponseContext, an as ResponseCookie, ao as SentNotification, S as StorageFake, ap as TESTING_ENVIRONMENT, aq as TableOrModel, ar as Target, as as TestCase, at as TestHooks, au as TestResponse, av as TestTrait, z as Testable, aw as TravelDate, ax as Wormhole, ay as actingAsAuthFactory, az as addresses, aA as applyEnvironment, aB as cookieHeader, aC as cookiePrefix, aD as decryptCookie, aE as encryptCookie, aF as flatten, aG as freezeSecond, aH as freezeTime, aI as guessMimeType, aJ as inertiaPageOf, aK as install, aL as isExpired, aM as matches, aN as nameOf, aO as recordingExceptionHandler, aP as recordingViewFactory, aQ as responseCookies, aR as runCommand, aS as testingConfig, aT as travel, aU as travelBack, aV as travelTo, aW as usingInMemoryDatabase } from './testing-B8J_HhF4.js';
2
2
  import './contracts.js';
3
- import './index.d-lffxurFs.js';
3
+ import './index.d-DA-Iu2a2.js';
package/dist/testing.js CHANGED
@@ -53,9 +53,9 @@ import {
53
53
  travelBack,
54
54
  travelTo,
55
55
  usingInMemoryDatabase
56
- } from "./chunk-7GPMFMS7.js";
57
- import "./chunk-FVI6X3VJ.js";
58
- import "./chunk-BKA5F3TH.js";
56
+ } from "./chunk-MG4YEWMV.js";
57
+ import "./chunk-YNDMTTWL.js";
58
+ import "./chunk-6AXJB4CD.js";
59
59
  export {
60
60
  AnonymousNotifiable,
61
61
  AssertableInertia,
@@ -299,9 +299,6 @@ export class LogoutController extends Controller {
299
299
  }
300
300
  ```
301
301
 
302
- > [!NOTE]
303
- > Laravel's password confirmation pages (`password.confirm`) aren't in Oriel.
304
-
305
302
  ### Invalidating sessions on other devices
306
303
 
307
304
  A new password usually means someone else may have the old one, so it should end the user's other sessions. The
@@ -339,6 +336,51 @@ await Auth.logoutOtherDevices(String(request().input('password')))
339
336
  It works by rehashing the password, so it needs the middleware to take effect. `Auth.logoutCurrentDevice()` signs out here
340
337
  only: unlike `logout()`, it leaves the remember token alone, so the user's other remembered devices keep working.
341
338
 
339
+ ## Password confirmation
340
+
341
+ Some pages ask a signed-in user for their password again before they open, such as the two-factor settings: the
342
+ `password.confirm` middleware sends the user to confirm it, then back to the page. A confirmation lasts
343
+ `auth.password_timeout` seconds, three hours by default.
344
+
345
+ ### Routing
346
+
347
+ Two routes do it: one shows a form with a password field, the other checks the password, records the time in the
348
+ session (`auth.password_confirmed_at`, in Unix seconds) and goes back to the page that asked:
349
+
350
+ ```ts title="routes/web.ts"
351
+ import { __, back, Hash, redirect, request, Route, view } from '@orieljs/framework'
352
+
353
+ Route.get('/confirm-password', () => view('auth.confirm-password')).middleware('auth').name('password.confirm')
354
+
355
+ Route.post('/confirm-password', async () => {
356
+ const user = await request().user<{ password: string }>()
357
+
358
+ if (!(await Hash.check(String(request().input('password')), user!.password))) {
359
+ return back().withErrors({ password: __('auth.password') })
360
+ }
361
+
362
+ request().session().put('auth.password_confirmed_at', Math.floor(Date.now() / 1000))
363
+
364
+ return redirect().intended()
365
+ }).middleware('auth', 'throttle:6,1')
366
+ ```
367
+
368
+ The browser starter kits have these routes and their page.
369
+
370
+ ### Protecting routes
371
+
372
+ Give a route the `password.confirm` middleware, after `auth`:
373
+
374
+ ```ts title="routes/web.ts"
375
+ import { Route } from '@orieljs/framework'
376
+
377
+ Route.get('/settings/security', () => 'Security').middleware('auth', 'password.confirm')
378
+ ```
379
+
380
+ `password.confirm:route.name` sends the user to another route, and `password.confirm:,600` confirms for ten minutes. A
381
+ JSON request that needs a confirmation gets `423 Locked`, as Laravel's does. On a [Live](live.md) page, an update past
382
+ the timeout gets the same 423, and the page reloads into the confirmation.
383
+
342
384
  ## API tokens
343
385
 
344
386
  A client that isn't a browser, such as a mobile app or another service, signs in with an API token. Oriel's tokens are
@@ -174,10 +174,8 @@ actions, typed with your `User` and the model, each denying until you write it:
174
174
  node oriel make:policy PostPolicy --model=Post
175
175
  ```
176
176
 
177
- > [!WARNING]
178
- > Without `--model`, `make:policy` writes `view()`, `create()`, `update()` and `delete()` methods that return `true`,
179
- > so the policy allows everything until you write them. Since Oriel finds the policy by its name, it applies as soon
180
- > as the file exists.
177
+ Without `--model`, it writes an empty policy class, as Laravel's does, and you add the methods. Since Oriel finds the
178
+ policy by its name, it applies as soon as the file exists, and a policy without a method for an action denies it.
181
179
 
182
180
  ### Registering policies
183
181
 
package/docs/cache.md CHANGED
@@ -77,8 +77,9 @@ A store's `connection` names the database connection to use, the default one whe
77
77
 
78
78
  The `redis` store talks to the Redis server of `config/database.ts`: `connection` names an entry of `database.redis`.
79
79
  A new app's `cache` entry is its own Redis database, number 1 unless you set `REDIS_CACHE_DB`, so that flushing the
80
- cache leaves your sessions and queued jobs alone. Oriel's Redis client, `ioredis`, comes with the framework, and the
81
- connection is closed when your app shuts down.
80
+ cache leaves your sessions and queued jobs alone. The store needs Oriel's Redis client, `ioredis`, which you install
81
+ yourself (`npm install ioredis`): it's loaded the first time the store is used, and an app without it gets an error
82
+ saying to install it. The connection is closed when your app shuts down.
82
83
 
83
84
  ## Cache usage
84
85
 
@@ -289,6 +290,18 @@ and `redis` stores. The `file` store deletes its folder, and the `array` store e
289
290
  > A `redis` store with no prefix flushes every key of its Redis database. Give the cache a Redis database of its own,
290
291
  > as a new app's `cache` connection does.
291
292
 
293
+ `cache:clear` flushes the default store from the command line, or the store you name, and `cache:forget` removes one
294
+ key:
295
+
296
+ ```sh
297
+ node oriel cache:clear
298
+ node oriel cache:clear redis
299
+ node oriel cache:forget users.count
300
+ ```
301
+
302
+ Clearing the store that keeps [maintenance mode](configuration.md#maintenance-mode), when `APP_MAINTENANCE_DRIVER` is
303
+ `cache`, brings the app back up, as in Laravel.
304
+
292
305
  ### The cache helper
293
306
 
294
307
  `cache()` reads and writes the default store too. With a key, it returns the key's value. With an object, it stores
@@ -524,9 +537,20 @@ Once the window ends, the count starts again from 0. The other methods:
524
537
 
525
538
  A key's accents don't count: `zoë` and `zoe` share a count.
526
539
 
527
- > [!NOTE]
528
- > Laravel's `RateLimiter::attempt()`, which runs a function while the count allows it, and `RateLimiter::for()`,
529
- > which names a limit for routes, aren't in Oriel. Check with `tooManyAttempts()` and count with `hit()`, as above.
540
+ `attempt()` does both in one call: it runs the function and counts it while the key has attempts left, and returns
541
+ `false` without running it when it hasn't. The function's result comes back, or `true` when it returns nothing:
542
+
543
+ ```ts
544
+ const sent = await RateLimiter.attempt('send-message:7', 5, async () => {
545
+ // Send the message...
546
+ }, 60)
547
+
548
+ if (!sent) {
549
+ // Too many messages sent...
550
+ }
551
+ ```
552
+
553
+ `RateLimiter.for()` names a limiter for routes, which [Rate limiting](routing.md#rate-limiting) covers.
530
554
 
531
555
  ## Adding custom cache drivers
532
556
 
@@ -69,14 +69,18 @@ be committed (`env:encrypt`); Oriel can't, so give your servers their values thr
69
69
 
70
70
  When `APP_ENV` is set in the environment before your app starts, and a `.env.<APP_ENV>` file exists, Oriel loads that
71
71
  file instead of `.env`, not as well: with `APP_ENV=staging`, a variable that is only in `.env` isn't set. When the
72
- file doesn't exist, `.env` is loaded. `APP_ENV` inside `.env` doesn't choose a file, and there is no `--env` option.
72
+ file doesn't exist, `.env` is loaded. `APP_ENV` inside `.env` doesn't choose a file.
73
+
74
+ A command's `--env` option does the same for one run: `node oriel migrate --env=staging` sets `APP_ENV` to `staging`,
75
+ over the environment's, and loads `.env.staging` when it exists, else `.env`.
73
76
 
74
77
  Your tests run with `APP_ENV=testing`, so a `.env.testing` file, when you add one, replaces `.env` in your tests.
75
78
 
76
79
  > [!WARNING]
77
80
  > Bun loads `.env`, and its own files such as `.env.local`, into the environment itself, before your app starts. As
78
81
  > Oriel never overwrites a variable, on Bun the values in `.env` win over those in `.env.<APP_ENV>`, which only adds
79
- > the variables `.env` doesn't have. On Bun, keep one `.env` per machine, or set the variables in the environment.
82
+ > the variables `.env` doesn't have, `--env` included. On Bun, keep one `.env` per machine, or set the variables in the
83
+ > environment.
80
84
 
81
85
  ### Environment variable types
82
86
 
@@ -148,7 +152,7 @@ arguments. The application has shortcuts too:
148
152
  | `app().isLocal()` | The environment is `local` |
149
153
  | `app().isProduction()` | The environment is `production` |
150
154
  | `app().runningUnitTests()` | The environment is `testing`, as in your tests |
151
- | `app().runningInConsole()` | The app was started by an `oriel` command, `oriel serve` included, or by your tests |
155
+ | `app().runningInConsole()` | The app was started by an `oriel` command other than `oriel serve`, which serves it as `public/index.ts` does, or by your tests |
152
156
 
153
157
  Since a variable set in the environment wins over `.env`, your server can set `APP_ENV=production` even when its
154
158
  `.env` says `local`.
@@ -174,6 +178,10 @@ To set values while your app runs, pass an object to `config()`. A value you set
174
178
  config({ 'app.timezone': 'America/Chicago' })
175
179
  ```
176
180
 
181
+ Your app answers every request from the same process, so a value set while one request runs changes it for all the
182
+ requests after it, not only that one. Set values in a service provider's `boot()`; in the `local` environment, a
183
+ `config()` write inside a request logs a warning saying so.
184
+
177
185
  With no arguments, `config()` returns the configuration itself, with `get()`, `set()`, `has()`, `push()` and `all()`.
178
186
 
179
187
  ### The `Config` facade
@@ -328,7 +336,76 @@ needs one, with "No application encryption key has been specified.".
328
336
 
329
337
  ## Maintenance mode
330
338
 
331
- > [!NOTE]
332
- > Laravel's maintenance mode, the `down` and `up` commands with their 503 page, isn't in Oriel. To update an app
333
- > without stopping it, start the new version beside the old one and switch your load balancer or proxy over to it.
334
- > [Deployment](deployment.md) covers running your app in production.
339
+ While your app is in maintenance mode, every request gets a 503 page: your `resources/views/errors/503.tsx` when you
340
+ have one, else Oriel's. Put your app in maintenance mode with `down`, as you update it:
341
+
342
+ ```sh
343
+ node oriel down
344
+ ```
345
+
346
+ `--refresh` asks browsers to reload the page after that many seconds, and `--retry` sets the `Retry-After` header:
347
+
348
+ ```sh
349
+ node oriel down --refresh=15 --retry=60
350
+ ```
351
+
352
+ The health route, `/up`, still answers 200 while the app is down, so a load balancer doesn't take it out of service.
353
+
354
+ #### Bypassing maintenance mode
355
+
356
+ To let yourself in while everyone else sees the 503 page, give `down` a secret, or `--with-secret` to make one:
357
+
358
+ ```sh
359
+ node oriel down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"
360
+ ```
361
+
362
+ Visiting your app's URL followed by the secret, `https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515`, sets a
363
+ cookie that lets that browser through for 12 hours, and redirects it to `/`.
364
+
365
+ #### Pre-rendering the maintenance mode view
366
+
367
+ `--render` renders a view when the app goes down and sends it while the app is down, so the page shows even while your
368
+ dependencies are being updated:
369
+
370
+ ```sh
371
+ node oriel down --render="errors.503"
372
+ ```
373
+
374
+ #### Redirecting maintenance mode requests
375
+
376
+ `--redirect` sends every request to one path instead:
377
+
378
+ ```sh
379
+ node oriel down --redirect=/
380
+ ```
381
+
382
+ #### Disabling maintenance mode
383
+
384
+ `up` brings your app back:
385
+
386
+ ```sh
387
+ node oriel up
388
+ ```
389
+
390
+ `--status` changes the status code, 503 unless you give another.
391
+
392
+ #### Maintenance mode on multiple servers
393
+
394
+ Maintenance mode is kept in a file, `storage/framework/down`, so `down` reaches only the server it runs on. On several
395
+ servers, or on Vercel, keep it in a cache store they all share instead, in `.env`:
396
+
397
+ ```ini
398
+ APP_MAINTENANCE_DRIVER=cache
399
+ APP_MAINTENANCE_STORE=database
400
+ ```
401
+
402
+ The store is a `database` or `redis` one from `config/cache.ts`. Then `down` and `up`, run anywhere that reaches that
403
+ store, apply to every server. Clearing that store with `cache:clear` brings the app back up, as in Laravel.
404
+
405
+ Paths that should still answer while the app is down, such as a webhook, go in `bootstrap/app.ts`:
406
+
407
+ ```ts
408
+ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
409
+ middleware.preventRequestsDuringMaintenance({ except: ['webhooks/*'] })
410
+ })
411
+ ```
package/docs/console.md CHANGED
@@ -30,6 +30,28 @@ node oriel migrate --help
30
30
  A name `oriel` doesn't know is an error, with the names closest to it: "Command "migrat" is not defined.", then "Did
31
31
  you mean one of these?" and up to three names.
32
32
 
33
+ ### Global options
34
+
35
+ Every command takes these options, as in Laravel, before its name or after it:
36
+
37
+ | Option | What it does |
38
+ | --- | --- |
39
+ | `-h`, `--help` | Shows the command's help screen |
40
+ | `-q`, `--quiet` | Prints nothing but errors |
41
+ | `-V`, `--version` | Prints Oriel's version, "Oriel Framework 0.1.0-alpha.16", and runs nothing |
42
+ | `-n`, `--no-interaction` | Asks no questions: `ask()`, `confirm()` and `choice()` take their defaults, and a `secret()`, or a `choice()` without a default, fails the command |
43
+ | `--env=<environment>` | Runs the command under that environment: sets `APP_ENV` and loads `.env.<environment>` (see [Additional environment files](configuration.md#additional-environment-files)) |
44
+ | `-v`, `-vv`, `-vvv`, `--verbose` | Sets the command's `verbosity()` to 1, 2 or 3 |
45
+ | `--ansi`, `--no-ansi` | Accepted for scripts written for Laravel; Oriel's output has no colours either way |
46
+
47
+ ```sh
48
+ node oriel migrate --force --no-interaction
49
+ node oriel -n db:seed
50
+ ```
51
+
52
+ A command that declares one of these names itself, such as a `{--env=}` option, keeps it. After `--`, they reach the
53
+ command as arguments.
54
+
33
55
  On Node, the script loads your TypeScript with `tsx`, which a new app has among its dependencies; Bun runs it as it
34
56
  is. Either way, it creates your app from `bootstrap/app.ts`, boots it, runs the command, and shuts the app down,
35
57
  closing its database connections and writing out its logs, before it exits with the command's exit code.
@@ -55,12 +77,16 @@ These are the commands every app has. A new app adds one of its own, `inspire`,
55
77
  | Command | What it does |
56
78
  | --- | --- |
57
79
  | `about` | Shows your app's name, the Oriel and Node versions, the environment, debug mode and URL |
80
+ | `down` | Puts your app in [maintenance mode](configuration.md#maintenance-mode) |
58
81
  | `export` | Saves your app's pages as files any static host serves ([Static export](export.md)) |
59
82
  | `help` | Shows a command's help screen |
60
83
  | `list` | Lists the commands, all of them or one group's |
61
84
  | `serve` | Serves your app on Oriel's server; `--watch` restarts it when your code changes |
62
85
  | `test` | Runs your tests with Vitest |
63
86
  | `tinker` | Opens Node's REPL with your app in it |
87
+ | `up` | Brings your app out of maintenance mode |
88
+ | `cache:clear` | Flushes the default cache store, or the one you name |
89
+ | `cache:forget` | Removes a key from the cache |
64
90
  | `db:seed` | Seeds the database, with `DatabaseSeeder` or the seeder you name |
65
91
  | `event:list` | Lists your events and their listeners |
66
92
  | `ide:info` | Prints your app's routes, commands, config keys, `.env` names, views, Live components, rules and Inertia pages as JSON, for editors (the OrielJS extension for VS Code reads it); secret values are left out |
@@ -88,7 +114,7 @@ These are the commands every app has. A new app adds one of its own, `inspire`,
88
114
  | `make:policy` | Writes a policy in `app/Policies`; `--model` names its model |
89
115
  | `make:provider` | Writes a service provider in `app/Providers` |
90
116
  | `make:request` | Writes a form request in `app/Http/Requests` |
91
- | `make:resource` | Writes a resource class, whose `toArray()` shapes a model for JSON, in `app/Http/Resources`; `--collection` writes one for a list |
117
+ | `make:resource` | Writes an [API resource](eloquent-resources.md), whose `toArray()` shapes a model's JSON, in `app/Http/Resources`; a name ending in `Collection`, or `--collection`, writes a resource collection |
92
118
  | `make:rule` | Writes a validation rule object in `app/Rules` |
93
119
  | `make:seeder` | Writes a seeder in `database/seeders` |
94
120
  | `make:test` | Writes a test in `tests/Feature`, or in `tests/Unit` with `--unit` |
@@ -116,6 +142,7 @@ These are the commands every app has. A new app adds one of its own, `inspire`,
116
142
  | `schedule:run` | Runs the scheduled tasks that are due |
117
143
  | `schedule:work` | Runs the tasks that are due, every minute, until you stop it |
118
144
  | `storage:link` | Links `public/storage` to `storage/app/public` |
145
+ | `two-factor:install` | Writes the migration that adds [two-factor login](two-factor.md#turning-it-on)'s columns to `users` |
119
146
  | `vercel:build` | Writes your app's build for Vercel into `.vercel/output` ([Deploying to Vercel](deployment.md#deploying-to-vercel)); `--cron=` sets when Vercel calls the scheduler ([Scheduled tasks](deployment.md#scheduled-tasks)) |
120
147
 
121
148
  `node oriel help <command>` lists a command's options. A few that are worth knowing up front:
@@ -185,7 +212,7 @@ export class SendEmails extends Command {
185
212
  override description = 'Send a marketing email to a user'
186
213
 
187
214
  async handle(): Promise<void> {
188
- const user = await User.findOrFail(this.argument('user'))
215
+ const user = await User.findOrFail(String(this.argument('user')))
189
216
 
190
217
  await inject(DripEmailer).send(user)
191
218
  }
@@ -417,6 +444,9 @@ for an option array. An argument or an option that the signature doesn't declare
417
444
 
418
445
  ### Prompting for input
419
446
 
447
+ With `-n` or `--no-interaction`, no question is asked: each method below returns its default, and `secret()` fails the
448
+ command with "The "…" question needs an answer, which --no-interaction can't give.".
449
+
420
450
  `ask()` asks a question and returns the answer. A second argument is the default, shown in parentheses and returned
421
451
  when the answer is empty:
422
452
 
@@ -497,6 +527,15 @@ command.newLine()
497
527
  command.newLine(3)
498
528
  ```
499
529
 
530
+ With `-q`, only `error()` prints. `verbosity()` returns -1 then, 1, 2 or 3 with `-v`, `-vv` or `-vvv`, and 0 otherwise,
531
+ so a command can print more when asked to:
532
+
533
+ ```ts
534
+ declare const command: Command
535
+ // ---cut---
536
+ if (command.verbosity() >= 2) command.line('Connected to the queue.')
537
+ ```
538
+
500
539
  > [!NOTE]
501
540
  > Laravel prints each kind of message in its own colour. Oriel prints them as plain text; `warn()` and `error()` go to
502
541
  > the standard error, so a script that runs your command can tell them apart.
package/docs/container.md CHANGED
@@ -381,6 +381,10 @@ await scope.run(async () => {
381
381
  })
382
382
  ```
383
383
 
384
+ Inside a request, `app().bind()`, `singleton()` and `extend()` change the application, so every request after it sees
385
+ the change; in the `local` environment they log a warning that says so. `app().instance()` binds on the request's
386
+ scope.
387
+
384
388
  > [!NOTE]
385
389
  > Laravel's `scoped()` instances are flushed when a new request or job starts, as under Octane or a queue worker. Oriel
386
390
  > gives each request, job and command a scope of its own, and they can run at the same time: two requests never see
package/docs/csrf.md CHANGED
@@ -59,8 +59,8 @@ A form that should reach a `PUT`, `PATCH` or `DELETE` route posts with a hidden
59
59
 
60
60
  A single-page app served from your app's own domain sends the token in the `X-XSRF-TOKEN` header, as Inertia does. A
61
61
  frontend on another domain, or a mobile app, uses your API routes instead, which have no session and no CSRF check, and
62
- signs in with [personal access tokens](authentication.md#api-tokens). Oriel sends no CORS headers, so a browser frontend
63
- on another domain needs a middleware of your own that adds them.
62
+ signs in with [personal access tokens](authentication.md#api-tokens). Your API routes send
63
+ [CORS headers](routing.md#cross-origin-resource-sharing-cors), so a browser frontend on another domain can call them.
64
64
 
65
65
  ### Excluding URIs from CSRF protection
66
66
 
package/docs/database.md CHANGED
@@ -224,6 +224,28 @@ try {
224
224
  Prefer `transaction()`: a manual transaction takes in the queries of every request until it ends, which suits a
225
225
  script or a test, not a request.
226
226
 
227
+ ### Running code after the commit
228
+
229
+ `DB.afterCommit()` runs a function once the transaction it's called in commits, the outermost one when transactions
230
+ are nested, and never when it rolls back, as in Laravel. Called outside a transaction, it runs the function at once:
231
+
232
+ ```ts
233
+ declare const sendWelcomeMail: () => Promise<void>
234
+ // ---cut---
235
+ await DB.transaction(async () => {
236
+ await DB.table('users').insert({ name: 'Taylor', email: 'taylor@example.com', password: '' })
237
+
238
+ await DB.afterCommit(() => sendWelcomeMail())
239
+ })
240
+ ```
241
+
242
+ The function runs on the connection, outside the ended transaction, and an error it throws makes `transaction()`
243
+ reject, after the commit. An inner transaction that rolls back drops only the functions given inside it. A
244
+ transaction opened with `beginTransaction()` holds them too, until `commit()`, and `rollBack()` drops them. The one
245
+ `RefreshDatabase` and `DatabaseTransactions` open around each test holds none, as Laravel's: inside it, a test's own
246
+ transaction runs its functions when it commits. Queued jobs can wait for the commit in the same way (see
247
+ [Jobs and database transactions](queues.md#jobs-and-database-transactions)).
248
+
227
249
  ## Logging queries
228
250
 
229
251
  `DB.enableQueryLog()` records each query the default connection runs, with its bindings and how many milliseconds it
@@ -71,23 +71,37 @@ checklist.
71
71
  node --import tsx public/index.ts
72
72
  ```
73
73
 
74
- On Bun, run `bun public/index.ts`. The server listens on `127.0.0.1`, on the port the `PORT` variable names, or
75
- `SERVER_PORT`, or 8000. It serves with `node:http` on Node and `Bun.serve()` on Bun.
74
+ On Bun, run `bun public/index.ts`. The server listens on the address the `HOST` variable names, or `SERVER_HOST`, or
75
+ `127.0.0.1`, and on the port `PORT` names, or `SERVER_PORT`, or 8000. It serves with `node:http` on Node and
76
+ `Bun.serve()` on Bun.
76
77
 
77
78
  `node oriel serve` runs the same server through your app's command line, and takes `--host` and `--port`; `npm start`
78
79
  runs it too, and so does the CI workflow the installer writes. Leave `--watch` out in production: it restarts the
79
80
  server on every file change.
80
81
 
82
+ While you update the app, `node oriel down` answers every request with a 503 page, and `node oriel up` brings it back
83
+ ([Maintenance mode](configuration.md#maintenance-mode)). With several servers, keep maintenance mode in a shared cache
84
+ store.
85
+
81
86
  ### Containers
82
87
 
83
88
  In a container, the server must listen on every interface, not only on `127.0.0.1`, or nothing outside the container
84
- reaches it. With `node oriel serve`, pass `--host=0.0.0.0`:
89
+ reaches it. Set `HOST=0.0.0.0` in the container's environment: `public/index.ts` and `node oriel serve` both read it.
90
+ `node oriel serve --host=0.0.0.0` does the same for one run.
85
91
 
86
- ```sh
87
- node oriel serve --host=0.0.0.0 --port=8000
88
- ```
92
+ `serve()` takes these options, in `public/index.ts`:
89
93
 
90
- With `public/index.ts`, give `serve()` the host:
94
+ | Option | What it does |
95
+ | --- | --- |
96
+ | `hostname` | The address to listen on (default: `HOST`, then `SERVER_HOST`, then `127.0.0.1`) |
97
+ | `port` | The port (default: `PORT`, then `SERVER_PORT`, then 8000; 0 picks a free one) |
98
+ | `keepAliveTimeout` | How long an idle keep-alive connection stays open, in seconds, on Node (default: 65, past the 60 of common load balancers) |
99
+ | `requestTimeout` | How long a request may take, in seconds; on Bun, how long a connection may stay idle, at most 255 (default: 300; 0 is none) |
100
+ | `publicPath` | The folder whose files are sent as they are (default: `public`); `false` turns it off |
101
+ | `shutdownTimeout` | How long a shutdown waits for the requests in flight, in milliseconds (default: 10000) |
102
+ | `signals` | Whether SIGINT and SIGTERM shut the server down (default: `true`) |
103
+ | `runtime` | `'node'` or `'bun'` (default: the one running) |
104
+ | `onListen` | Called once the server listens, with its `url` (default: prints "Server running on [url].") |
91
105
 
92
106
  ```ts title="public/index.ts"
93
107
  // @filename: bootstrap/app.ts
@@ -98,18 +112,11 @@ import { serve } from '@orieljs/framework'
98
112
  import { createApplication } from '../bootstrap/app'
99
113
 
100
114
  // Production entry: `node --import tsx public/index.ts`, or `bun public/index.ts`.
101
- await serve(await createApplication(), { hostname: '0.0.0.0' })
115
+ await serve(await createApplication(), { keepAliveTimeout: 75 })
102
116
  ```
103
117
 
104
- `serve()` takes these options:
105
-
106
- | Option | What it does |
107
- | --- | --- |
108
- | `hostname` | The address to listen on (default: `127.0.0.1`) |
109
- | `port` | The port (default: `PORT`, then `SERVER_PORT`, then 8000; 0 picks a free one) |
110
- | `publicPath` | The folder whose files are sent as they are (default: `public`); `false` turns it off |
111
- | `shutdownTimeout` | How long a shutdown waits for the requests in flight, in milliseconds (default: 10000) |
112
- | `signals` | Whether SIGINT and SIGTERM shut the server down (default: `true`) |
118
+ Behind a load balancer, keep `keepAliveTimeout` longer than the balancer's own idle timeout, so the app never closes a
119
+ connection the balancer is about to reuse.
113
120
 
114
121
  Point your container's health check at the [health route](#the-health-route), `/up`.
115
122
 
@@ -130,6 +137,11 @@ address. List your proxies in `http.trusted_proxies`, in `config/http.ts`, so th
130
137
  `route()` use the client's address, scheme and host from the `X-Forwarded-*` headers.
131
138
  [Configuring trusted proxies](requests.md#configuring-trusted-proxies) shows the settings.
132
139
 
140
+ When the proxy passes any `Host` on to your app, as a catch-all virtual host does, turn on
141
+ [`trustHosts()`](requests.md#configuring-trusted-hosts), so your app answers only your own host names. A proxy that
142
+ routes only your domains to the app already does that. A load balancer whose health check sends an IP address or an
143
+ internal name as `Host` gets a 404 from `/up` then: list that host in `at`.
144
+
133
145
  ### Directory permissions
134
146
 
135
147
  Your app writes into `storage`: its logs, uploaded files, and the file cache and sessions when you use those drivers.
@@ -309,6 +321,9 @@ and each instance has its own, so:
309
321
  - **Sessions and the cache** need a store every instance shares: `database` (the kits have the `sessions` and `cache`
310
322
  tables' migrations) or `redis`. Sessions can also use `cookie`. `file` and `array` don't outlast the instance.
311
323
  - **Logs** go to stderr, which Vercel's logs show: the function sets `LOG_CHANNEL=stderr` when you don't set it.
324
+ - **Work after the response** goes to Vercel's `waitUntil()`: the function answers as soon as the response is written,
325
+ and Vercel keeps it running for the [terminating work](lifecycle.md#finishing-up), such as the jobs you dispatched
326
+ with `dispatchAfterResponse()`, up to the function's time limit.
312
327
  - **Vercel's proxy is trusted.** Every request reaches the function through it, and it sets the `X-Forwarded-*`
313
328
  headers itself, so the function trusts them when `trusted_proxies`, in `config/http.ts`, is empty: your URLs keep
314
329
  the browser's `https`, and `request().ip()` is the visitor's (see
@@ -322,6 +337,13 @@ and each instance has its own, so:
322
337
  scheduled tasks run through Vercel Cron (see [Scheduled tasks](#scheduled-tasks)).
323
338
  - **Inertia pages render in the browser**, as they do when no SSR server answers: the SSR server doesn't run on
324
339
  Vercel. `INERTIA_SSR_ENABLED=false` skips asking it.
340
+ - **Maintenance mode needs a shared cache store**: set `APP_MAINTENANCE_DRIVER=cache` and `APP_MAINTENANCE_STORE` to a
341
+ `database` or `redis` store, then run `node oriel down --env=production` on your machine, with the production
342
+ database or Redis in your `.env.production` ([Maintenance mode](configuration.md#maintenance-mode)). The default,
343
+ a file, doesn't reach the function. Run it with Node: Bun loads `.env` first, and its values win, so
344
+ `bun oriel down --env=production` would take down the store your local `.env` names.
345
+ - **Each preview has its own host**, so with [`trustHosts()`](requests.md#configuring-trusted-hosts) on, list them
346
+ beside `APP_URL`'s: `middleware.trustHosts({ at: [/^my-app-[a-z0-9-]+-my-team\.vercel\.app$/] })`.
325
347
 
326
348
  ### Caching pages on the CDN
327
349
 
@@ -148,8 +148,8 @@ class UserFactory extends Factory<User> {
148
148
 
149
149
  ### Instantiating models
150
150
 
151
- `make()` makes models without saving them. With `count()`, or a number given to `factory()`, it makes a collection: a
152
- plain `Collection`, where Laravel's is an Eloquent collection, so `modelKeys()` and `load()` aren't on it:
151
+ `make()` makes models without saving them. With `count()`, or a number given to `factory()`, it makes the model's
152
+ [Eloquent collection](eloquent-collections.md), as Laravel's, so `modelKeys()` and `load()` are on it:
153
153
 
154
154
  ```ts
155
155
  const user = await User.factory().make()
@@ -184,7 +184,8 @@ const users = await User.factory().count(3).create()
184
184
  ```
185
185
 
186
186
  `makeOne()` and `createOne()` always return one model, typed as one. `createMany()` takes a number, or a list of
187
- attributes, one model each. `raw()` returns the attributes without making a model.
187
+ attributes, one model each, and returns them in an Eloquent collection. `raw()` returns the attributes without making a
188
+ model.
188
189
 
189
190
  ### Sequences
190
191
 
@@ -156,7 +156,8 @@ export class User extends Model {
156
156
  ```
157
157
 
158
158
  Until `save()`, reading the attribute gives what you set. A value that is already a hash made with your current
159
- settings is kept as it is; one made with other settings is refused.
159
+ settings is kept as it is; one made with other settings is refused. A new app's `User` casts `password` this way, so
160
+ `User.create({ password: 'secret' })` stores a hash, and a password hashed with `Hash.make()` first is kept.
160
161
 
161
162
  > [!NOTE]
162
163
  > Laravel hashes as soon as you set the attribute. Hashing is asynchronous in Oriel, so it happens in `save()`, before