@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/docs/live.md CHANGED
@@ -796,7 +796,8 @@ rather than an `o:` directive.
796
796
  > [!WARNING]
797
797
  > Every upload must also pass `live.temporary_file_upload.rules`, which allow 12 MB. A request body larger than
798
798
  > `http.max_body_size`, 8 MB, gets a 413, and the field gets "The photo failed to upload.". To accept files up to the
799
- > rule's size, raise `max_body_size` in `config/http.ts`.
799
+ > rule's size, raise `max_body_size` in `config/http.ts`. On Vercel, a function takes request bodies up to 4.5 MB
800
+ > whatever `max_body_size` says, so larger files need another way in ([Live uploads](storage.md#live-uploads)).
800
801
 
801
802
  ## Navigating
802
803
 
@@ -846,9 +847,11 @@ action redirects: then it is there on the next page.
846
847
 
847
848
  ## Middleware on updates
848
849
 
849
- Each update runs the `auth`, `verified`, `guest` and `can` middleware of the route that rendered the page again, with
850
- that route's parameters, before the component's actions. A user who signed out in another tab gets a 401, and one who
851
- lost an ability a 403. The list is `live.persistent_middleware`.
850
+ Each update runs the `auth`, `verified`, `guest`, `can` and `password.confirm` middleware of the route that rendered
851
+ the page again, with that route's parameters, before the component's actions. A user who signed out in another tab gets
852
+ a 401, one who lost an ability a 403, and one whose [password confirmation](authentication.md#password-confirmation)
853
+ ran out a 423. On a 401 or a 423 the page reloads, so its middleware sends the browser to log in or to confirm the
854
+ password. The list is `live.persistent_middleware`.
852
855
 
853
856
  ## Announcing status messages
854
857
 
@@ -901,6 +904,81 @@ the region to text: its children are taken out for 100 ms, so a button in it wou
901
904
  A component has `get(name)`, `set(name, value)`, which sends the value with the next request, `call(method, params)`,
902
905
  with the arguments in an array, `call('publish', [5])`, which resolves with the action's return value, and `commit()`.
903
906
 
907
+ ## Live in an Inertia app
908
+
909
+ An [Inertia](inertia.md) app can have Live pages too, as a Laravel app can have Livewire pages beside Inertia's. Each
910
+ page is one or the other: the Inertia pages keep their root view and client, and the Live pages get a layout and a
911
+ client of their own.
912
+
913
+ Add `@orieljs/live-client` to the app, and give Vite a second input that starts it:
914
+
915
+ ```ts title="resources/js/live.ts"
916
+ import { Live } from '@orieljs/live-client'
917
+
918
+ Live.start()
919
+ ```
920
+
921
+ ```ts title="vite.config.ts"
922
+ import { oriel } from '@orieljs/vite'
923
+ import { defineConfig } from 'vite'
924
+
925
+ export default defineConfig({
926
+ plugins: [oriel({ framework: 'react', input: ['resources/css/app.css', 'resources/js/app.tsx', 'resources/js/live.ts'] })],
927
+ })
928
+ ```
929
+
930
+ The Live pages' layout loads that input with `vite()`, and the Inertia root view doesn't, so neither page runs the
931
+ other's client. Name the layout in `config/live.ts`, or on a component with `static layout`:
932
+
933
+ ```tsx title="resources/views/components/layouts/live.tsx"
934
+ import { vite, type Renderable } from '@orieljs/framework'
935
+
936
+ export default function LiveLayout({ title, children }: { title?: string; children?: Renderable }) {
937
+ return (
938
+ <html lang="en">
939
+ <head>
940
+ <meta charset="utf-8" />
941
+ <title>{title}</title>
942
+ {vite(['resources/css/app.css', 'resources/js/live.ts'])}
943
+ </head>
944
+ <body>{children}</body>
945
+ </html>
946
+ )
947
+ }
948
+ ```
949
+
950
+ ```ts title="config/live.ts"
951
+ export default {
952
+ layout: 'components.layouts.live',
953
+ }
954
+ ```
955
+
956
+ A component's route sits beside the Inertia ones:
957
+
958
+ ```ts title="routes/web.ts"
959
+ // @filename: app/Live/Counter.tsx
960
+ import { Component } from '@orieljs/framework'
961
+ export default class Counter extends Component {
962
+ render() {
963
+ return <p />
964
+ }
965
+ }
966
+ // ---cut---
967
+ import { Route } from '@orieljs/framework'
968
+ import Counter from '../app/Live/Counter'
969
+
970
+ Route.inertia('/', 'Welcome')
971
+ Route.get('/counter', Counter).middleware('auth')
972
+ ```
973
+
974
+ Both kinds of page share the session, so a user signs in once. The Inertia middleware's shared props reach the
975
+ Inertia pages only; a Live component reads what it needs itself, such as `request().user()`. Live's updates go through
976
+ the `web` group, the Inertia middleware with them, which lets them pass, as they aren't Inertia visits.
977
+
978
+ To go from an Inertia page to a Live page, use a plain `<a>`: the browser loads the page in full. Inertia's `<Link>`
979
+ expects an Inertia response, which a Live page isn't. From a Live page, `o:navigate` to an Inertia page loads it in
980
+ full too: the Inertia root view's `vite()` tags track another entry, so Live doesn't swap it in.
981
+
904
982
  ## Configuration
905
983
 
906
984
  Live's settings are under `live`. A new app has no `config/live.ts`; add one to change them:
@@ -910,7 +988,7 @@ Live's settings are under `live`. A new app has no `config/live.ts`; add one to
910
988
  | `class_path` | `app/Live` | The folder whose components are registered at boot |
911
989
  | `layout` | `components.layouts.app` | The layout of full-page components |
912
990
  | `lazy_placeholder` | none | The view lazy components show before they load |
913
- | `persistent_middleware` | `auth`, `verified`, `guest`, `can` | The page route's middleware each update runs again |
991
+ | `persistent_middleware` | `auth`, `verified`, `guest`, `can`, `password.confirm` | The page route's middleware each update runs again |
914
992
  | `temporary_file_upload.disk` | Your default disk | Where uploads wait until they are stored |
915
993
  | `temporary_file_upload.directory` | `live-tmp` | The folder on that disk |
916
994
  | `temporary_file_upload.rules` | `required`, `file`, `max:12288` | The rules every upload must pass |
@@ -927,6 +1005,8 @@ tests](live-tests.md) covers it.
927
1005
  ## Differences from Livewire
928
1006
 
929
1007
  > [!NOTE]
930
- > Live has no Alpine.js, `wire:stream`, `#[Url]` query-string binding, `#[Reactive]`, `#[Modelable]`, form objects or
931
- > JavaScript hooks (`Livewire.hook()`). `temporaryUrl()` previews don't answer range requests, which Safari needs to
932
- > play a `<video>`.
1008
+ > Livewire bundles Alpine.js; Live doesn't, but works beside it: a morph keeps an Alpine component's state (through
1009
+ > `Alpine.cloneNode()`, as Livewire's does), and an Alpine `$dispatch` event reaches the Live components that listen for
1010
+ > it. Live has no `wire:stream`, `#[Url]` query-string binding, `#[Reactive]`, `#[Modelable]`, form objects, JavaScript
1011
+ > hooks (`Livewire.hook()`), `#[Validate]` attributes or `validateOnly()`, and `o:navigate` has no progress bar and no
1012
+ > `@persist`. `temporaryUrl()` previews don't answer range requests, which Safari needs to play a `<video>`.
package/docs/mail.md CHANGED
@@ -5,8 +5,8 @@ it to the log, or queues it for a worker.
5
5
 
6
6
  ## Introduction
7
7
 
8
- Oriel sends mail with [Nodemailer](https://nodemailer.com), which comes with the framework. A new app writes every
9
- mail to its log instead of sending it, so you can work on your mail before you set up a mail server.
8
+ Oriel sends mail over SMTP with [Nodemailer](https://nodemailer.com), which a new app lists in its dependencies. A new
9
+ app writes every mail to its log instead of sending it, so you can work on your mail before you set up a mail server.
10
10
 
11
11
  ### Configuration
12
12
 
@@ -45,7 +45,10 @@ Oriel has four transports:
45
45
  - `array` keeps the mails in memory, in the app's process, and sends nothing.
46
46
  - `failover` tries the mailers of its `mailers` list in turn (see [Failover configuration](#failover-configuration)).
47
47
 
48
- To send real mail, set `MAIL_MAILER=smtp` and the `MAIL_*` variables of your mail server in `.env`.
48
+ To send real mail, set `MAIL_MAILER=smtp` and the `MAIL_*` variables of your mail server in `.env`. The `smtp`
49
+ transport sends through `nodemailer`, which a new app lists in its dependencies; an app made before 0.1.0-alpha.16
50
+ installs it with `npm install nodemailer`. It's loaded when the first mail goes out, so an app that only logs its mail
51
+ never needs it.
49
52
 
50
53
  > [!NOTE]
51
54
  > Laravel also has transports for Mailgun, Postmark, Resend, Amazon SES and `sendmail`, and a `roundrobin` mailer.
@@ -534,6 +537,28 @@ Route.get('/mailable', async () => {
534
537
  > Laravel renders a mailable you return from a route. Oriel sends a returned mailable as JSON, like any other object,
535
538
  > so render it first, as above.
536
539
 
540
+ ## Mail events
541
+
542
+ Each message dispatches two [events](events.md), as in Laravel: `MessageSending` before it goes, and `MessageSent`
543
+ once the transport has taken it. Each has the `message` (its addresses, subject, HTML and text, which a
544
+ `MessageSending` listener may change) and `data.mailable`; `MessageSent` has what the transport returned, `sent`. A
545
+ `MessageSending` listener that returns `false` stops the message, and `sendNow()` then resolves `undefined`:
546
+
547
+ ```ts title="app/Providers/AppServiceProvider.ts"
548
+ import { Event, MessageSending, ServiceProvider } from '@orieljs/framework'
549
+
550
+ export class AppServiceProvider extends ServiceProvider {
551
+ override boot(): void {
552
+ Event.listen(MessageSending, (event: MessageSending) => {
553
+ if (event.message.to.some((address) => address.address.endsWith('@example.test'))) return false
554
+ return undefined
555
+ })
556
+ }
557
+ }
558
+ ```
559
+
560
+ A queued mailable dispatches them on the worker, when it's sent. `Mail.fake()` sends nothing, so it dispatches neither.
561
+
537
562
  ## Testing
538
563
 
539
564
  `Mail.fake()` swaps the mailer for a fake that sends nothing and records each mail. Its assertions check what your
@@ -36,7 +36,8 @@ To let the request pass, call `next(request)` and return what it returns. Think
36
36
  passes through on its way to your route: each layer can examine the request and turn it away.
37
37
 
38
38
  `handle()` returns a `Response`, so turn a redirect into one with its `toResponse(request)`, or throw: `abort(403)`
39
- ends the request with a 403.
39
+ ends the request with a 403. A middleware that returns nothing is an error, a 500 "Middleware must return a Response.":
40
+ return what `next(request)` gives.
40
41
 
41
42
  #### Middleware and responses
42
43
 
@@ -112,9 +113,12 @@ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
112
113
  })
113
114
  ```
114
115
 
115
- `append()` adds it at the end of the global list, and `prepend()` at the start. The list starts with `TrimStrings`,
116
- which trims every text input except `password`, `password_confirmation` and `current_password`, and
117
- `ConvertEmptyStringsToNull`, which turns empty inputs into `null`.
116
+ `append()` adds it at the end of the global list, and `prepend()` at the start. The list starts with `HandleCors`, which
117
+ answers [CORS](routing.md#cross-origin-resource-sharing-cors) on `api/*`, then `TrimStrings`, which trims every text
118
+ input except `password`, `password_confirmation` and `current_password`, and `ConvertEmptyStringsToNull`, which turns
119
+ empty inputs into `null`. `remove()` takes a middleware out of the list, and `trimStrings()` and
120
+ `convertEmptyStringsToNull()` give those two their exceptions, as
121
+ [Requests](requests.md#input-trimming-and-normalization) shows.
118
122
 
119
123
  Laravel's global list also checks trusted proxies and the size of the body. In Oriel these aren't middleware: the
120
124
  request applies them from `config/http.ts`, as [Requests](requests.md) explains.
@@ -231,13 +235,16 @@ they own.
231
235
  | Alias | Middleware | What it does |
232
236
  | --- | --- | --- |
233
237
  | `auth` | `Authenticate` | Lets signed-in users through. A guest gets a 401 for JSON, or a redirect to the login page. `auth:token` names the guard; with several, the first that has a user wins |
238
+ | `auth.session` | `AuthenticateSession` | Signs a session out once the user's password changed elsewhere, on every session driver (see [invalidating sessions on other devices](authentication.md#invalidating-sessions-on-other-devices)) |
234
239
  | `cache.headers` | `SetCacheHeaders` | Sets `Cache-Control` on GET and HEAD responses, as `cache.headers:public;max_age=3600;s_maxage=86400;etag` (`etag` adds an ETag and answers 304 when it matches); a response that sets a cookie is left alone, so a CDN never stores one visitor's page |
235
240
  | `can` | `Authorize` | Checks an ability with the gate, as `can:update,post`; a parameter that names a route parameter passes the bound model. A denial is a 403 |
236
241
  | `guest` | `RedirectIfAuthenticated` | Lets guests through, and redirects signed-in users |
237
242
  | `inertia.encrypt` | `EncryptHistory` | Encrypts the browser history state of the Inertia pages behind it |
243
+ | `password.confirm` | `RequirePassword` | Wants the password confirmed within `auth.password_timeout` seconds: JSON gets a 423, a page a redirect to the `password.confirm` route (see [password confirmation](authentication.md#password-confirmation)) |
238
244
  | `precognitive` | `HandlePrecognitiveRequests` | Answers a precognitive request once its data is validated (see [precognitive requests](#precognitive-requests)) |
239
245
  | `signed` | `ValidateSignature` | Wants a valid, unexpired signed URL, else a 403; `signed:relative` checks a URL signed without its host |
240
- | `throttle` | `ThrottleRequests` | Limits a client's requests in a window of minutes, as `throttle:60,1` for 60 a minute (see [rate limiting](routing.md#rate-limiting)) |
246
+ | `throttle` | `ThrottleRequests` | Limits a client's requests in a window of minutes, as `throttle:60,1` for 60 a minute, or by a limiter `RateLimiter.for()` names, as `throttle:api` (see [rate limiting](routing.md#rate-limiting)) |
247
+ | `two-factor.challenge` | `TwoFactorChallenge` | Lets only a login waiting for its second factor through; anyone else is sent to log in (see [two-factor login](two-factor.md#the-challenge-page)) |
241
248
  | `verified` | `EnsureEmailIsVerified` | Wants a verified email address: JSON gets a 403, a page a redirect to the `verification.notice` route, or the route you name, as `verified:profile.edit` |
242
249
 
243
250
  #### Redirecting guests and signed-in users
@@ -263,15 +270,14 @@ group first, then its own. Among a route's middleware, the same middleware with
263
270
  it first appears.
264
271
 
265
272
  Within a route's middleware, the `web` and `api` groups' middleware and `auth` and `guest` run first, keeping their
266
- order. Then route model binding runs, then everything else. So `can:update,post` sees the bound `Post`, and a guest
267
- is redirected before any database lookup. `throttle` is among everything else, so it runs after binding: a throttled
268
- route with a model parameter looks the model up before it counts the request, and a missing model is a 404 that isn't
269
- counted.
273
+ order, then `throttle`. Then route model binding runs, then everything else. So `can:update,post` sees the bound
274
+ `Post`, a guest is redirected before any database lookup, and a throttled request is refused before its model is looked
275
+ up: a request for a missing model counts toward the limit, as in Laravel.
270
276
 
271
277
  > [!NOTE]
272
278
  > Laravel sorts route middleware by a priority list, which `priority()` changes. Oriel keeps only the part of it that
273
- > route model binding needs, the session and the signed-in user before the lookup, and has no `priority()`: when two
274
- > of your middleware depend on each other, list them in that order.
279
+ > route model binding needs, the session, the signed-in user and `throttle` before the lookup, and has no
280
+ > `priority()`: when two of your middleware depend on each other, list them in that order.
275
281
 
276
282
  ## Middleware parameters
277
283
 
@@ -360,7 +366,9 @@ Angular forms don't offer it.
360
366
  - When the data passes, the request ends there: a 204 with a `Precognition-Success: true` header.
361
367
  - When it fails, the usual 422 with the errors.
362
368
 
363
- A `Precognition-Validate-Only: name,email` header limits the check to those fields. Every response of the route varies
369
+ A `Precognition-Validate-Only: name,email` header limits the check to those fields. A `*` in one stands for one segment,
370
+ as in Laravel 12: `items.*.name` checks the rules for `items.0.name`, `items.1.name` and `items.*.name`, while
371
+ `items.0.name` doesn't check a rule written `items.*.name`. Every response of the route varies
364
372
  on `Precognition`, and a precognitive one carries a `Precognition: true` header.
365
373
 
366
374
  ```ts
@@ -7,6 +7,10 @@
7
7
  "slug": "installation",
8
8
  "title": "Installation"
9
9
  },
10
+ {
11
+ "slug": "laravel",
12
+ "title": "Oriel for Laravel developers"
13
+ },
10
14
  {
11
15
  "slug": "upgrade",
12
16
  "title": "Upgrade guide"
@@ -225,6 +229,10 @@
225
229
  "slug": "eloquent-mutators",
226
230
  "title": "Accessors and casts"
227
231
  },
232
+ {
233
+ "slug": "eloquent-resources",
234
+ "title": "API resources"
235
+ },
228
236
  {
229
237
  "slug": "eloquent-factories",
230
238
  "title": "Factories"
@@ -223,3 +223,25 @@ await notification.markAsUnread()
223
223
 
224
224
  `Notification.extend(name, factory)` adds a channel: an object with `send(notifiable, notification)`. List its name in
225
225
  `via()`.
226
+
227
+ ## Notification events
228
+
229
+ Each channel a notification goes through dispatches Laravel's [events](events.md): `NotificationSending` before it
230
+ sends, and `NotificationSent` after, with what the channel returned as `response`. Each has the `notifiable`, the
231
+ `notification` and the `channel`'s name. A `NotificationSending` listener that returns `false` skips that channel, and
232
+ the others still send. A channel that throws dispatches `NotificationFailed`, with the error as `data.exception`, and
233
+ the error goes on as before:
234
+
235
+ ```ts title="app/Providers/AppServiceProvider.ts"
236
+ import { Event, NotificationSent, ServiceProvider } from '@orieljs/framework'
237
+
238
+ export class AppServiceProvider extends ServiceProvider {
239
+ override boot(): void {
240
+ Event.listen(NotificationSent, (event: NotificationSent) => {
241
+ console.log(`${event.notification.constructor.name} sent by ${event.channel}`)
242
+ })
243
+ }
244
+ }
245
+ ```
246
+
247
+ A queued notification dispatches them on the worker, when its job runs.
@@ -141,6 +141,10 @@ methods describe the page:
141
141
  | `cursor()`, `nextCursor()`, `previousCursor()` | The cursors (`cursorPaginate()` only) |
142
142
  | `getCollection()`, `through(fn)` | The items as a collection, and a paginator of the items passed through `fn` |
143
143
 
144
+ An Eloquent query's `getCollection()` is the models' [Eloquent collection](eloquent-collections.md), as in Laravel, so
145
+ `load()` and `modelKeys()` work on a page; a query builder's is a plain `Collection`. After `through()`, the items are
146
+ in a plain `Collection` unless the function returned models.
147
+
144
148
  ### In views
145
149
 
146
150
  Oriel's views are TSX, so there is no `links()` that prints the links for you. `linkCollection()` gives them as objects,
package/docs/passwords.md CHANGED
@@ -22,12 +22,10 @@ per email address, with the token and when it was made. A new token for an addre
22
22
 
23
23
  ### Configuring trusted hosts
24
24
 
25
- > [!WARNING]
26
- > The reset link in the mail starts with the scheme and host of the request that asked for it, as Laravel's does.
27
- > Laravel can restrict the hosts it answers (`trustHosts()`); Oriel can't. Have your web server or proxy answer only
28
- > your app's own host names, or build the link from `APP_URL` yourself, as
29
- > [Reset link customization](#reset-link-customization) shows, so that a request with a forged `Host` header can't
30
- > send your users a link to another site.
25
+ The reset link in the mail starts with the scheme and host of the request that asked for it, as Laravel's does. So
26
+ that a request with a forged `Host` header can't send your users a link to another site, answer only your own hosts
27
+ with [`trustHosts()`](requests.md#configuring-trusted-hosts), have your web server or proxy answer only them, or build
28
+ the link from `APP_URL` yourself, as [Reset link customization](#reset-link-customization) shows.
31
29
 
32
30
  ## Routing
33
31
 
package/docs/providers.md CHANGED
@@ -42,11 +42,9 @@ export class RiakServiceProvider extends ServiceProvider {
42
42
  }
43
43
  ```
44
44
 
45
- `make:provider` doesn't register the provider: add it to `bootstrap/providers.ts` yourself, as [Registering
46
- providers](#registering-providers) shows. `--force` overwrites a provider that exists.
47
-
48
- > [!NOTE]
49
- > Laravel's `make:provider` adds the new provider to `bootstrap/providers.php` for you. Oriel's writes the class only.
45
+ `make:provider` also registers the provider: it imports it in `bootstrap/providers.ts` and adds it at the end of the
46
+ list, as Laravel's does with `bootstrap/providers.php` (see [Registering providers](#registering-providers)). When it
47
+ can't find the list there, it says what to add. `--force` overwrites a provider that exists, without listing it twice.
50
48
 
51
49
  ### The register method
52
50
 
package/docs/queues.md CHANGED
@@ -24,8 +24,11 @@ export default {
24
24
  ```
25
25
 
26
26
  The `sync` driver runs each job straight away, in the same process, which is handy in tests; `redis` reads its server
27
- from `database.redis` in `config/database.ts`. Within a connection, jobs go onto named **queues**, so a worker can run
28
- the urgent ones first. Without a name, a job goes onto the connection's `queue`, here `default`.
27
+ from `database.redis` in `config/database.ts`, and needs Oriel's Redis client, `ioredis`, which you install yourself
28
+ (`npm install ioredis`). Within a connection, jobs go onto named **queues**, so a worker can run
29
+ the urgent ones first. Without a name, a job goes onto the connection's `queue`, here `default`. `after_commit` holds
30
+ jobs dispatched inside a database transaction until it commits (see
31
+ [Jobs and database transactions](#jobs-and-database-transactions)).
29
32
 
30
33
  ## Creating jobs
31
34
 
@@ -126,6 +129,39 @@ await ProcessPodcast.dispatchSync(podcast)
126
129
  ProcessPodcast.dispatchAfterResponse(podcast)
127
130
  ```
128
131
 
132
+ ### Jobs and database transactions
133
+
134
+ A job dispatched inside a database transaction can reach the worker before the transaction commits, and the worker
135
+ then can't find the rows the job is about, or reads them as they were. With `after_commit: true` on the connection in
136
+ `config/queue.ts`, a job dispatched inside a transaction is pushed only once the transaction commits, the outermost one
137
+ when they're nested, and is dropped if it rolls back: a `DB.transaction()`, or one `DB.beginTransaction()` opened,
138
+ until `DB.commit()` or `DB.rollBack()`. Outside a transaction, it's pushed at once, and so it is inside the transaction
139
+ `RefreshDatabase` opens around a test. A new app has it off:
140
+
141
+ ```ts
142
+ declare const podcast: Podcast
143
+ // ---cut---
144
+ await DB.transaction(async () => {
145
+ await podcast.update({ title: 'Episode 1, remastered' })
146
+
147
+ await ProcessPodcast.dispatch(podcast)
148
+ })
149
+ ```
150
+
151
+ `afterCommit()` and `beforeCommit()` decide for one dispatch, whatever the connection says, and a job class decides
152
+ for itself with an `afterCommit` field set to `true` or `false`:
153
+
154
+ ```ts
155
+ declare const podcast: Podcast
156
+ // ---cut---
157
+ await ProcessPodcast.dispatch(podcast).afterCommit()
158
+ await ProcessPodcast.dispatch(podcast).beforeCommit()
159
+ ```
160
+
161
+ Queued listeners, mail and notifications wait in the same way, with the field on the listener, the mailable or the
162
+ notification. Inside the transaction, the dispatch resolves with an empty job ID, since nothing is queued yet, and a
163
+ unique job that's dropped frees its lock. The waiting is [`DB.afterCommit()`](database.md#running-code-after-the-commit)'s.
164
+
129
165
  ### Choosing the queue and the connection
130
166
 
131
167
  ```ts
@@ -334,3 +370,29 @@ node oriel queue:flush
334
370
  ```
335
371
 
336
372
  `queue:clear` deletes the jobs still waiting on a queue: `node oriel queue:clear redis --queue=emails`.
373
+
374
+ ## Job events
375
+
376
+ The queue dispatches Laravel's job events through the [event dispatcher](events.md):
377
+
378
+ - `JobQueued` once a job is on a queue, with its `connectionName`, `queue`, `id`, `job`, `payload` and `delay`;
379
+ - `JobProcessing` before a worker runs a job, and `JobProcessed` after one that ran without failing, each with the
380
+ `connectionName` and the `job`;
381
+ - `JobFailed` when a job has failed for good, with the `exception` too. An attempt that's released for a retry
382
+ dispatches none.
383
+
384
+ The `sync` queue runs a job at once, so it dispatches `JobProcessing`, `JobProcessed` and `JobFailed`, and no
385
+ `JobQueued`. `Queue.before()`, `Queue.after()` and `Queue.failing()` listen for the last three, in a service
386
+ provider's `boot()`:
387
+
388
+ ```ts title="app/Providers/AppServiceProvider.ts"
389
+ import { Log, Queue, ServiceProvider } from '@orieljs/framework'
390
+
391
+ export class AppServiceProvider extends ServiceProvider {
392
+ override boot(): void {
393
+ Queue.failing((event) => {
394
+ void Log.error(`${event.job.payload().displayName} failed on ${event.connectionName}`, { error: String(event.exception) })
395
+ })
396
+ }
397
+ }
398
+ ```
package/docs/requests.md CHANGED
@@ -400,7 +400,21 @@ with `EncryptCookies.except('appearance')` in `bootstrap/app.ts` to read it as i
400
400
  Two global middleware tidy the input of every request before your code sees it, as in Laravel: `TrimStrings` trims
401
401
  every text value, except the `password`, `password_confirmation` and `current_password` fields, and
402
402
  `ConvertEmptyStringsToNull` turns empty text into `null`. They apply to the query string and to the body, JSON
403
- included. They always run: Laravel's switches to turn them off, for every request or some, aren't in Oriel.
403
+ included.
404
+
405
+ To leave some fields as sent, or some requests, list them in `bootstrap/app.ts`. A string is a field (dotted for nested
406
+ input) and a callback leaves the whole request untouched when it returns `true`:
407
+
408
+ ```ts
409
+ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
410
+ middleware.trimStrings({ except: ['secret', (request) => request.is('admin/*')] })
411
+ middleware.convertEmptyStringsToNull({ except: [(request) => request.is('admin/*')] })
412
+ })
413
+ ```
414
+
415
+ `TrimStrings.skipWhen(callback)` and `ConvertEmptyStringsToNull.skipWhen(callback)` do the same for every app in the
416
+ process, until `flushState()`. To turn one off for every request, take it out of the global list:
417
+ `middleware.remove(TrimStrings)`.
404
418
 
405
419
  ## Files
406
420
 
@@ -487,7 +501,9 @@ Oriel reads a JSON, URL-encoded or multipart body into memory before your code r
487
501
  `Content-Length` header gives the size, the body isn't read at all. The limit is the same for every route.
488
502
 
489
503
  A JSON body can also nest objects and arrays only so deep: past `http.max_json_depth`, 512 levels unless you change
490
- it, the request gets a 400 ("The request body is nested too deeply.").
504
+ it, the request gets a 400 ("The request body is nested too deeply."). A form field or query key may have 64 levels
505
+ of brackets, as in PHP: `a[b][c]` has two. One with more gets a 400 ("The request input is nested too deeply."), which
506
+ no setting changes.
491
507
 
492
508
  Raise them in `config/http.ts`, where `max_body_size` is a number of bytes, and `null` turns either limit off:
493
509
 
@@ -530,4 +546,27 @@ browser asked for. The list may also be a comma-separated string, so it can come
530
546
  When you can't know your load balancers' addresses, as with many cloud providers, trust them all with `'*'`. Do it
531
547
  only when nothing can reach your app except through them: any client could then set the `X-Forwarded-*` headers.
532
548
 
533
- Laravel's trusted hosts (`trustHosts()`) aren't in Oriel: let your web server or load balancer refuse unknown hosts.
549
+ ## Configuring trusted hosts
550
+
551
+ Your app answers a request whatever its `Host` header says, so links it builds from the request, such as a password
552
+ reset link, could point to another site. To answer only your own hosts, turn on `TrustHosts` in `bootstrap/app.ts`, as
553
+ in Laravel:
554
+
555
+ ```ts
556
+ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
557
+ middleware.trustHosts()
558
+ })
559
+ ```
560
+
561
+ It then answers only `APP_URL`'s host and its subdomains; another host gets a 404, "Bad hostname provided.". List
562
+ more hosts, or patterns, with `at`, and leave `APP_URL`'s out with `subdomains: false`:
563
+
564
+ ```ts
565
+ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
566
+ middleware.trustHosts({ at: ['shop.example.com', /^preview-\d+\.example\.net$/], subdomains: false })
567
+ })
568
+ ```
569
+
570
+ A host name in `at` matches as a whole, in any case, and `at` may be a function that returns the list. The host checked
571
+ is the one from `X-Forwarded-Host` when a [trusted proxy](#configuring-trusted-proxies) sends it. It checks nothing in
572
+ the `local` environment or while your tests run.
package/docs/responses.md CHANGED
@@ -56,9 +56,11 @@ Route.get('/', () => view('welcome', { name: 'Taylor' }))
56
56
 
57
57
  [Views](views.md) covers writing them.
58
58
 
59
- > [!WARNING]
60
- > Return a view, not a TSX element. A route that returns `<Welcome />` sends the element's description as JSON. To
61
- > send TSX that isn't a view file, render it first: `response(await View.renderToString(<Welcome />))`.
59
+ A route may return a TSX element too: it's sent rendered, as a view is, and an `<html>` root gets its doctype:
60
+
61
+ ```tsx
62
+ Route.get('/hello', () => <h1>Hello</h1>)
63
+ ```
62
64
 
63
65
  ### Attaching headers to responses
64
66
 
@@ -352,7 +354,8 @@ const created = response().json({ name: 'Abigail' }, 201)
352
354
  ```
353
355
 
354
356
  The data goes through `JSON.stringify()`, so models and collections become JSON as they do when a route returns
355
- them, and dates become ISO strings. Laravel's JSONP `withCallback()` isn't in Oriel.
357
+ them, and dates become ISO strings. Laravel's JSONP `withCallback()` isn't in Oriel. To choose a model's keys for an
358
+ API, return an [API resource](eloquent-resources.md) instead.
356
359
 
357
360
  ### Empty responses
358
361
 
package/docs/routing.md CHANGED
@@ -707,10 +707,62 @@ a 404.
707
707
 
708
708
  ## Rate limiting
709
709
 
710
+ ### Defining rate limiters
711
+
712
+ A named rate limiter says how often a request may reach the routes that use it. Define one with `RateLimiter.for()`,
713
+ in a service provider's `boot()`, as in Laravel. Its function gets the request and returns a `Limit`:
714
+
715
+ ```ts title="app/Providers/AppServiceProvider.ts"
716
+ import { Limit, RateLimiter, ServiceProvider } from '@orieljs/framework'
717
+ import type { User } from '../Models/User'
718
+
719
+ export class AppServiceProvider extends ServiceProvider {
720
+ override boot(): void {
721
+ RateLimiter.for('api', async (request) => {
722
+ const user = await request.user<User>()
723
+
724
+ return Limit.perMinute(60).by(user?.id ?? request.ip())
725
+ })
726
+ }
727
+ }
728
+ ```
729
+
730
+ `Limit.perSecond()`, `perMinute()`, `perHour()` and `perDay()` take the number of requests, and a number of seconds,
731
+ minutes, hours or days for the window (1 unless you give it); `Limit.perMinutes(5, 100)` allows 100 every five
732
+ minutes. `by()` names what is counted, such as the user or the IP address. A limit without `by()` is one count for
733
+ every client. `Limit.none()` doesn't limit at all, for a user who shouldn't be:
734
+
735
+ ```ts
736
+ declare const isVip: (request: unknown) => Promise<boolean>
737
+ // ---cut---
738
+ RateLimiter.for('uploads', async (request) =>
739
+ (await isVip(request)) ? Limit.none() : Limit.perMinute(100).by(request.ip()),
740
+ )
741
+ ```
742
+
743
+ The function may return several limits, each counted on its own: past any of them, the request is refused.
744
+
745
+ ```ts
746
+ RateLimiter.for('login', (request) => [Limit.perMinute(500), Limit.perMinute(3).by(String(request.input('email')))])
747
+ ```
748
+
749
+ Oriel defines no limiter of its own, not even `api`: `throttle:<name>` with a name nothing defined is an error,
750
+ "Rate limiter [api] is not defined.".
751
+
710
752
  ### Attaching rate limiters to routes
711
753
 
712
- The `throttle` middleware limits how often a client may call a route. Its parameters are the number of requests and
713
- the window in minutes:
754
+ Attach a named limiter with `throttle:<name>`:
755
+
756
+ ```ts
757
+ declare const handler: () => string
758
+ // ---cut---
759
+ Route.middleware('throttle:uploads').group(() => {
760
+ Route.post('/audio', handler)
761
+ Route.post('/video', handler)
762
+ })
763
+ ```
764
+
765
+ Or give `throttle` its numbers, the number of requests and the window in minutes:
714
766
 
715
767
  ```ts
716
768
  declare const handler: () => string
@@ -726,11 +778,9 @@ cache's default store, or in the store that a `limiter` key in `config/cache.ts`
726
778
  `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers. Past the limit, the route answers 429 ("Too Many Attempts.")
727
779
  with `Retry-After`, the seconds to wait, and `X-RateLimit-Reset`, the Unix time the window ends.
728
780
 
729
- Every route behind `throttle` adds to the same count for a client, whatever its numbers. To count a group of routes
730
- on its own, give `throttle` a third parameter, a prefix for its key: `throttle:10,1,uploads`.
731
-
732
- > [!WARNING]
733
- > Laravel's named rate limiters (`RateLimiter::for()`) aren't in Oriel: give `throttle` its numbers directly.
781
+ Every route behind `throttle` with numbers adds to the same count for a client, whatever its numbers. To count a
782
+ group of routes on its own, give `throttle` a third parameter, a prefix for its key: `throttle:10,1,uploads`. A named
783
+ limiter's counts are its own: two limiters never share one, even with the same `by()`.
734
784
 
735
785
  ## Form method spoofing
736
786
 
@@ -769,3 +819,31 @@ const parameters = request().route() // every parameter, by name
769
819
 
770
820
  `Route.has('login')` tells you whether a route of that name exists, as a new app's welcome page does to show its login
771
821
  link.
822
+
823
+ ## Cross-origin resource sharing (CORS)
824
+
825
+ Oriel answers CORS `OPTIONS` requests with the values you configure, as Laravel does. The `HandleCors` middleware,
826
+ in the global list, answers a browser's preflight request at once, and adds the CORS headers to every other response
827
+ on the paths it covers, errors included.
828
+
829
+ By default it covers `api/*`: any origin may call your API routes, with any method and header, but without cookies or
830
+ other credentials. To change that, publish the configuration with `node oriel install:api`, which writes
831
+ `config/cors.ts` (or create the file yourself):
832
+
833
+ ```ts title="config/cors.ts"
834
+ export default {
835
+ paths: ['api/*'],
836
+ allowed_methods: ['*'],
837
+ allowed_origins: ['https://app.example.com', '*.example.org'],
838
+ allowed_origins_patterns: [],
839
+ allowed_headers: ['*'],
840
+ exposed_headers: [],
841
+ max_age: 0,
842
+ supports_credentials: false,
843
+ }
844
+ ```
845
+
846
+ `paths` are patterns as `request().is()` takes them. A `*` in an origin is a wildcard, and
847
+ `allowed_origins_patterns` takes regular expressions. With `supports_credentials`, the response names the caller's
848
+ origin instead of `*` and allows credentials, so list your origins. `paths: []`, or
849
+ `middleware.remove(HandleCors)` in `bootstrap/app.ts`, turns it off.