@appweaver/skill 0.0.0-stage → 3.1.0

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.
@@ -0,0 +1,1217 @@
1
+ # Core patterns
2
+
3
+ The patterns of an Appweaver application with their code: scaffolding, the application, modules, resources (model,
4
+ service, routes, policy, auth model), filters, sorting, aggregates, custom routes, templates, errors, logging,
5
+ telemetry, audit, realtime, AI, MCP, custom models, plugins, dependency injection and seeders. Each part links to its
6
+ full reference.
7
+
8
+ ## Scaffolding a new application
9
+
10
+ Use `@appweaver/create` (the `create-appweaver` binary) to scaffold a new project. It copies the base template, a
11
+ minimal application of the core module, adds the selected modules (`data` and `web` by default), installs dependencies,
12
+ and generates the Prisma schema and the types with `data` (only the JSON Schema of `appweaver.json` without it). It is a
13
+ one-shot command without prompts.
14
+
15
+ ```sh
16
+ npx @appweaver/create <name> [description] [options]
17
+ npm create @appweaver <name> [description] -- [options] # the same, npm passes the options after --
18
+ ```
19
+
20
+ **Options:**
21
+
22
+ | Flag | Description | Default |
23
+ | ------------------------ | ----------------------------------------------------------------------------- | ------------ |
24
+ | `--add <modules...>` | Modules to add to the default ones, separated by spaces or commas | `data web` |
25
+ | `--all` | Add every module | false |
26
+ | `--exclude <modules...>` | Modules to leave out of the default ones or of `--all` (e.g. `--exclude web`) | none |
27
+ | `-o, --output-dir <dir>` | Output directory (use ./ for current working directory) | project name |
28
+ | `--database <type>` | Database of `data`: `sqlite`, `postgresql`, `mysql`, `sqlserver` | `sqlite` |
29
+ | `--host <host>` | Hostname or IP address the server of `web` binds to | `0.0.0.0` |
30
+ | `--port <port>` | Port number the server of `web` listens on | `5000` |
31
+ | `--bun` | Use Bun as the application runtime (Node and npm otherwise) | Node |
32
+ | `--agent <agent>` | The AI agent to configure the guidelines and skill files for | `claude` |
33
+ | `--no-install` | Skip the installation of the dependencies | installs |
34
+
35
+ **Modules:** the base project depends only on `@appweaver/cli`, `@appweaver/common`, `@appweaver/core` and TypeBox: an
36
+ application with neither a database nor a server (`src/main.ts`, an e2e test of its health checks). `data` and `web`
37
+ are the default modules, added to it unless excluded, so a project is a web API by default. Every other module is added
38
+ with `--add`, `--all`, or later with `weaver module add` (see [Managing modules](#managing-modules)). `--exclude` leaves
39
+ out any module, with or without `--all`: `--exclude web` for a database worker without a server, `--exclude data web`
40
+ for the core application alone, i.e. a one-shot task (`weaver run`). `--database`, `--host` and `--port` apply only
41
+ with `data` and `web`:
42
+
43
+ | Module | Adds | Without it |
44
+ | ---------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
45
+ | `data` (default) | `@appweaver/data`, `@appweaver/sharp`, Prisma, `database/`, the generated types, the test database | no database, no resources |
46
+ | `web` (default) | `@appweaver/web` (requires `data`), the server config, the `User` auth resource and its admin seeder, `public/` | no HTTP server, no auth model |
47
+ | `redis` | `@appweaver/redis`, the `memory.redis.url`, the docker-compose Redis service | memory, cache and rate limit in the process |
48
+ | `queue` | `@appweaver/bullmq` (requires `redis`, added along with it) | in-memory queue |
49
+ | `scheduler` | `@appweaver/cron` | scheduler disabled |
50
+ | `mailer` | `@appweaver/nodemailer` | mailer disabled (no email routes) |
51
+ | `templates` | `@appweaver/handlebars`, `templates/`, the account emails with the mailer | no template engine |
52
+ | `locales` | `locales/en.json`, the account email texts with the mailer | English texts written into the templates |
53
+ | `timeseries` | The `series` fields in the database (requires `data`), `timescale` and the TimescaleDB image on PostgreSQL | time series in the database (`auto`) |
54
+ | `telemetry` | `@appweaver/opentelemetry`, the OTLP endpoint, telemetry off in the `test` environment | no telemetry exported |
55
+ | `realtime` | `@appweaver/realtime` (requires `web`): channels, resource events, actions and streams over WebSocket and SSE | no realtime connections |
56
+ | `mcp` | `@appweaver/mcp` (requires `web`): the MCP server of the AI agents at `/mcp` | no MCP server |
57
+ | `ai` | `@appweaver/ai` and `@appweaver/openai`: `AiService` on a local Ollama in `dev`, the `mock` model in `test` | no AI models |
58
+ | `payments` | `@appweaver/payments`, `@appweaver/stripe` (requires `data`), the Stripe keys of `.env`, `fake` gateway in test | no online payments |
59
+ | `docker` | `Dockerfile`, `.dockerignore`, `docker-compose.yml`, `start.sh` | no Docker files |
60
+
61
+ Options are given after the positional arguments, since `--add` and `--exclude` take every following value up to the
62
+ next option.
63
+
64
+ **Example — PostgreSQL API with Redis, mailer and Docker:**
65
+
66
+ ```sh
67
+ npx @appweaver/create MyBlogAPI "My own CMS for blogging" --database postgresql --add redis mailer docker
68
+ npx @appweaver/create MyBlogAPI "My own CMS for blogging" --database postgresql --all --exclude queue
69
+ npx @appweaver/create Reports "Nightly reports" --add scheduler --exclude web # a database worker without a server
70
+ npx @appweaver/create Calculator "Loan calculator" --exclude data web # the core application alone
71
+ ```
72
+
73
+ This creates a `./my-blog-api` directory, installs all dependencies, and runs the initial schema and type generation.
74
+ The default test runner is `jest` with `swc` transpiler.
75
+
76
+ The connections are configured in the committed `appweaver.json` (the test database in its `environments.test`
77
+ section), whose `${VAR}` references are expanded from the environment. Only the database password goes to the gitignored
78
+ `.env` (copied to a committed `.env.example`):
79
+
80
+ ```json
81
+ {
82
+ "config": {
83
+ "database": {
84
+ "url": "postgresql://${DB_USER:-my-blog-api}:${DB_PASSWORD}@${DB_HOST:-localhost}:5432/${DB_NAME:-my-blog-api}"
85
+ },
86
+ "memory": {
87
+ "redis": {
88
+ "url": "redis://${REDIS_HOST:-localhost}:6379/0"
89
+ }
90
+ }
91
+ },
92
+ "environments": {
93
+ "test": {
94
+ "database": {
95
+ "url": "postgresql://${DB_USER:-my-blog-api}:${DB_PASSWORD}@${DB_HOST:-localhost}:5432/${DB_NAME:-my-blog-api}-test"
96
+ }
97
+ }
98
+ }
99
+ }
100
+ ```
101
+
102
+ ```dotenv
103
+ NODE_ENV=dev
104
+
105
+ DB_PASSWORD=my-blog-api
106
+ ```
107
+
108
+ With the `docker` module, the generated `docker-compose.yml` of a PostgreSQL, MySQL, or SQL Server project runs the
109
+ database server (and Redis, with the `redis` module) on their default ports (`5432`, `3306`, `1433`, and `6379` for
110
+ Redis), also published on the host, with the `.env` credentials. So `docker compose up` runs the whole stack, while
111
+ `docker compose up -d postgres redis` and `npm run dev`
112
+ run the app locally against the same containers. The application containers read `.env` and set only `DB_HOST` and
113
+ `REDIS_HOST` to the service names, which the URLs default to `localhost` without. To use another server, change the
114
+ URL in `appweaver.json`, or set `DB_HOST` / `REDIS_HOST` in `.env`. Setting `DB_NAME` renames the database (the test
115
+ database is `${DB_NAME}-test`), also in the docker-compose database service, and `DB_USER` changes the user. For MySQL,
116
+ the generated `database/mariadb-init.sh` grants the user every database when the MariaDB container initializes its
117
+ volume, since Prisma Migrate creates a shadow database and the end-to-end tests the `-test` one.
118
+
119
+ The migrations connect with `database.migrationUrl`, `database.url` when not set, so the application can query the
120
+ data as a user that only reads and writes the rows, while the migrations run as the owner of the tables. `weaver
121
+ migrate` also sets up the TimescaleDB hypertables and the PostGIS geometry triggers with it (see
122
+ [database](./database.md#separate-migration-and-application-users)).
123
+
124
+ A SQLite project keeps its database file in the `data/` directory (`file:./data/<name>.db`), which the
125
+ generated `docker-compose.yml` mounts as the `sqlite-data` volume shared by the migration, seed, and application
126
+ containers.
127
+
128
+ The generated `Dockerfile` builds the application and its production dependencies in a build stage, so the final image
129
+ carries no build tools. The image runs as the unprivileged `node` user (`bun` for Bun) and defaults to `NODE_ENV=prod`.
130
+ It declares no health check, which belongs to the orchestrator: point the Docker Compose `healthcheck` or the Kubernetes
131
+ probes at `GET /health/ready`, which answers `{ "ready": true }` once every service has started (503 with
132
+ `{ "ready": false }` before, and again from the start of the shutdown) and needs no authentication. The
133
+ `docker-compose.yml` services read `NODE_ENV` from `.env`, so the environment a container starts
134
+ in stays up to the project. Mounted `storage`, `logs`, and `data` directories must be writable by the image user.
135
+
136
+ **Linux hosts:** the `docker-compose.yml` services bind-mount the project's `./storage` and `./logs` directories, which
137
+ on Linux keep the owner they have on the host. A directory Docker creates itself is owned by `root`, so the image user
138
+ (uid `1000`) cannot write uploaded files, logs, or the generated JWT keys into it. Create both directories before the
139
+ first `docker compose up` and give them to uid `1000`:
140
+
141
+ ```sh
142
+ mkdir -p storage logs && sudo chown -R 1000:1000 storage logs
143
+ ```
144
+
145
+ Volumes created by an image version that still ran as `root` need the same change of owner, or recreating. Docker
146
+ Desktop on macOS and Windows maps the ownership of bind mounts itself and needs neither step.
147
+
148
+ **Example — Bun project with Sqlite:**
149
+
150
+ ```sh
151
+ npx @appweaver/create BunApp "Bun application with simple API" --bun --database sqlite
152
+ ```
153
+
154
+ This creates a `./bun-app` directory, installs all dependencies using bun package manager, and runs the initial schema
155
+ and type generation. The default test runner is `bun`.
156
+
157
+ After the application is scaffolded, the following commands need to be run to finish the application setup:
158
+
159
+ ```sh
160
+ npx weaver migration new init # use --no-install flag if npx tries to install package
161
+ npm run seed
162
+ ```
163
+
164
+ Or, for bun runtime:
165
+
166
+ ```sh
167
+ bun weaver migration new init
168
+ bun run seed
169
+ ```
170
+
171
+ **Install scripts:** npm 12+ blocks dependency install scripts by default. The scaffolded `package.json` ships an
172
+ `allowScripts` field (Bun: `trustedDependencies`) covering the packages Appweaver needs to build. Without it,
173
+ `npm install` skips the native builds and `weaver generate` fails. It also denies (`false`) `@parcel/watcher`, which
174
+ Jest pulls in with prebuilt binaries, so its fallback native build is never needed. To approve a newly added
175
+ dependency, run `npm install-scripts approve <pkg>`, or `npm deny-scripts <pkg>` to silence the warning for one that
176
+ does not need its script; both write the entry to the root `package.json`. Note that a `package.json`
177
+ `allowScripts` field makes npm ignore `.npmrc` `allow-scripts` entirely.
178
+
179
+ ## Creating and starting the application server
180
+
181
+ The main entrypoint to the application. This function creates an application object and initializes all resources and
182
+ services.
183
+
184
+ Default application bootstrap:
185
+
186
+ ```ts
187
+ // src/main.ts
188
+ import { createApp } from '@appweaver/core';
189
+ import { logger } from '@appweaver/common';
190
+
191
+ createApp().catch((err) => logger.error(err));
192
+ ```
193
+
194
+ Manually starting an application:
195
+
196
+ ```ts
197
+ // src/main.ts
198
+ import { createApp } from '@appweaver/core';
199
+
200
+ const app = await createApp({
201
+ autoStart: false,
202
+ scanPath: './dist/my/app/path'
203
+ });
204
+
205
+ // custom init logic...
206
+
207
+ await app.start(); // with SERVER_LISTEN=false, every service starts without the server listening
208
+ ```
209
+
210
+ `app.server` is the Fastify instance of the `HttpServer` service (`inject(HttpServer).instance`), and `app.spec()`
211
+ returns the OpenAPI document. `@appweaver/web` adds both to `Application`, so neither is available when the module is
212
+ not installed or disabled.
213
+
214
+ ## Modules and application kinds
215
+
216
+ Every part of the framework is a module declared with `defineModule`: `@appweaver/core` (always), `@appweaver/data`
217
+ (Prisma, the resources), `@appweaver/web` (the Fastify server, authentication, requires data) and one driver package
218
+ per library or service (`@appweaver/redis`, `@appweaver/bullmq`, `@appweaver/cron`, `@appweaver/nodemailer`,
219
+ `@appweaver/twilio`, `@appweaver/handlebars`, `@appweaver/sharp`). Every package but core is enabled by being a
220
+ dependency of the application's `package.json`, and carries the library it wraps, so install `@appweaver/redis`, not
221
+ `ioredis`. The
222
+ `provider` key of each contract (`auto` by default) picks the driver of an enabled module, `none` turns the contract
223
+ off. An application adds its own modules in `src/modules/<name>/module.ts` (`weaver module new <name>`) or as npm
224
+ packages (`weaver module add <package>`), and a module package is created with `npm create @appweaver module
225
+ <package>`, its driver tested with the contract suites of `@appweaver/testing`. See [modules.md](./modules.md)
226
+ and the [providers](./configuration.md#providers).
227
+
228
+ | Application | How |
229
+ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
230
+ | HTTP API | The default: `createApp()` starts the server on `SERVER_PORT`. |
231
+ | Queue worker, scheduled jobs | `APP_MODULES_DISABLED=@appweaver/web`: no server, kept alive by its workers or cron jobs. `HEALTH_CHECK_PORT` answers the health checks. |
232
+ | One-shot task | `weaver run <task> [args...]`: runs a `createTask` of `src/tasks/` by its name (`weaver run` lists them), then exits. |
233
+
234
+ ```ts
235
+ // src/tasks/orders/count.ts, run with `weaver run orders:count Pending`
236
+ import { createTask, injectService } from '@appweaver/core';
237
+
238
+ export default createTask({
239
+ description: 'Counts the orders of a status.',
240
+ arguments: { status: { required: true, choices: ['Pending', 'Paid'] } },
241
+ options: { min: { type: 'number', default: 1 } }, // --min <min>
242
+ run: async ({ args, options }) => {
243
+ const count = await injectService('Order').count({ status: args.status });
244
+ console.log(`${count} orders`);
245
+ return count >= options.min ? 0 : 1; // the exit code
246
+ }
247
+ });
248
+ ```
249
+
250
+ `weaver run` runs the task without the server or the scheduled jobs, `--help` showing its arguments. A task is named by
251
+ its path in `src/tasks/` (`orders/count.ts` is `orders:count`) unless it has a `name`. See
252
+ [cli.md](./cli.md#weaver-run).
253
+
254
+ ## Creating resources
255
+
256
+ Resources are the core building blocks for a web application. There are four resource types: **model**, **service**,
257
+ **routes**, and **policy**. Created and exported resources are loaded automatically on application start. Except for a
258
+ resource model, other resource types are optional and do not need to be created. A service requires the model, and
259
+ routes require the service. A policy only requires the model and applies to the service whether routes exist or not.
260
+
261
+ Dependencies: **model** ← **service** ← **routes**, and **model** ← **policy** (optional)
262
+
263
+ **DOS:**
264
+
265
+ - Use default configuration values whenever possible
266
+ - Rely on library defaults for `omit`/`pick`, ad `input`/`output` settings
267
+ - Use default `mimeType` and `namePattern` patterns in file configurations unless specifically requested
268
+ - Prefer storing configuration in JSON file (`appweaver.json`) over environment (`.env`) file, but keep secrets in
269
+ `.env`
270
+ and reference them from the JSON file as `${VAR}` (i.e. `"url": "postgresql://${DB_USER:-app}:${DB_PASSWORD}@..."`)
271
+ - Always create all four resource configs (model, service, routes, and policy) unless specified otherwise
272
+
273
+ **DON'TS:**
274
+
275
+ - Don't explicitly set default values in configuration unless specifically requested
276
+ - Don't override `omit`/`pick` for `read`, `create` and `update` settings unnecessarily
277
+ - Don't specify `input`/`output` configurations if defaults suffice
278
+ - Don't modify file's `mimeType` and `namePattern` patterns unless specifically instructed
279
+ - Don't customize index arrays without an explicit requirement
280
+
281
+ ### Creating a resource model
282
+
283
+ Resource model defines all aspects of the domain model: database table fields, relations, files, virtual fields, CRUD
284
+ data transfer objects. The exported model is used to construct Prisma schema, generate TypeScript types for all model
285
+ variations, define schema for CRUD routes, and input/output arguments to resource service methods.
286
+
287
+ `weaver resource new <name>` creates the `model.ts`, `service.ts`, `routes.ts` and `policy.ts` of a new resource
288
+ (`--no-service`, `--no-routes` and `--no-policy` leave them out), to edit before `weaver generate`.
289
+
290
+ ```ts
291
+ // src/resources/product/model.ts
292
+ import { createModel } from '@appweaver/data';
293
+
294
+ export default createModel({
295
+ name: 'Product',
296
+ scalars: {
297
+ title: {
298
+ type: 'string',
299
+ minLength: 1,
300
+ maxLength: 200
301
+ },
302
+ price: {
303
+ type: 'float',
304
+ minimum: 0
305
+ },
306
+ status: {
307
+ type: 'enum',
308
+ default: 'Draft',
309
+ values: ['Draft', 'Active', 'Sold']
310
+ },
311
+ description: {
312
+ type: 'string',
313
+ required: false
314
+ },
315
+ lastViewedAt: {
316
+ type: 'dateTime',
317
+ defaultGenerator: 'now()'
318
+ },
319
+ enabled: {
320
+ type: 'boolean',
321
+ default: true
322
+ }
323
+ },
324
+ relations: {
325
+ category: {
326
+ model: 'Category',
327
+ type: 'manyToOne',
328
+ mappedBy: 'products',
329
+ output: {
330
+ type: 'always'
331
+ }
332
+ }
333
+ },
334
+ files: {
335
+ photo: {
336
+ mimeType: 'image/*',
337
+ maxSize: '2 MB',
338
+ image: { quality: 80, maxWidth: 1200 }
339
+ }
340
+ },
341
+ create: {
342
+ omit: ['status']
343
+ },
344
+ update: {
345
+ pick: ['title', 'price', 'status', 'description']
346
+ },
347
+ index: ['title']
348
+ });
349
+ ```
350
+
351
+ A model has an auto-incrementing integer primary key unless the `id` block asks for a generated string one:
352
+
353
+ ```ts
354
+ export default createModel({
355
+ name: 'Comment',
356
+ id: {
357
+ type: 'string',
358
+ generator: 'cuid(2)' // or uuid(), uuid(7), cuid(), nanoid()
359
+ },
360
+ scalars: { body: { type: 'string' } }
361
+ });
362
+ ```
363
+
364
+ The choice flows through the Prisma column, the generated TypeScript type, the `:id` route path parameter, and the
365
+ relation inputs and foreign keys of every model pointing at it. Both ID types can be mixed across models.
366
+
367
+ A relation holding the foreign key of a one-to-many relation is declared with `type: 'manyToOne'`, as `category` above,
368
+ and the model it points at lists the inverse side with `type: 'oneToMany'`. The `omit` and `pick` lists of `read`,
369
+ `create`, and `update` only accept the fields the model declares, its `id`, and its audit fields.
370
+
371
+ A field to hide everywhere is `hidden`. One to hide only where a relation shows it, i.e. the email of the author of a
372
+ public post, goes into the `omit` of that relation's `output` (`output: { type: 'always', omit: ['email'] }`), which
373
+ leaves it out of the routes, the MCP tools and the realtime events while the related model's own routes keep it.
374
+
375
+ Index entries are field names, nested in an array for a composite index. Prefix a name with `-` for a descending index
376
+ or `+` for an ascending one; without a prefix, the database default order is used:
377
+
378
+ ```ts
379
+ index: ['-createdAt', ['status', '-createdAt']];
380
+ ```
381
+
382
+ Foreign key columns are indexed automatically, unless an explicit index already leads with them. `unique` takes the
383
+ same shape as `index` for composite unique constraints, i.e. `unique: [['provider', 'providerAccountId']]`. An entry
384
+ can be a definition with a `type` and `ops` (PostgreSQL), a `where` (partial index) or an `expression`, and
385
+ `generatedColumns` declares the columns PostgreSQL computes, i.e. a `tsvector` for a full-text search; both are
386
+ described in [resources.md](./resources.md#index-config).
387
+
388
+ `views` declares named projections of a model for one audience (`public: { read: { omit: ['seo'], audit: false },
389
+ write: { pick: ['viewCount'] } }`), bound by `createRoutes({ modelName, view })`, `createPolicy({ modelName, view })`
390
+ (composed with the policy of the model), a relation `output: { view: 'public' }` and the MCP tools of the routes; see
391
+ [resources.md](./resources.md#views).
392
+
393
+ Set `softDelete: true` to keep deleted records in the database, marked by the `deletedAt` and `deletedById` columns,
394
+ instead of removing them. Soft deleted records are hidden from every read, so the API behaves exactly as after a real
395
+ delete, and a record can only be restored manually in the database. The relations cascading on delete are soft deleted
396
+ with the record, so every model a soft deleted model cascades into must enable `softDelete` too, or the application
397
+ fails to start. Stored files are removed on a regular delete but kept on a soft delete by default, configurable per
398
+ file field with `onResourceDeleted` and `onResourceSoftDeleted`. A kept file stays in the storage, e.g. for audit, but
399
+ is never served again.
400
+
401
+ With `storage.versions.enabled` (off by default), uploading a file again keeps the replaced one as a previous version:
402
+ a single file field always does, an array field for a file named by a `<field>:replace` multipart text part. A previous
403
+ version is served only by the current file's name with `?version=<n>`, listed by `GET /:id/file-versions?name=` and
404
+ deleted by `POST /:id/delete-file-versions` (deleting the `latest` one restores the previous one), kept up to
405
+ `maxCount` (default `10`) and `maxAge` (unlimited by default), overridden per field by `versions` (`false` for none).
406
+ See [storage.md](./storage.md#file-versions).
407
+
408
+ The `series` section declares fields measured over time (`float`, `int`, `boolean`), whose points belong to a resource
409
+ and live apart from its record: in the `<Model>Series` table of the database (`database`, every database), or a
410
+ TimescaleDB hypertable on PostgreSQL (`timescale`). They are written and queried through the
411
+ series routes (`POST /:id/series`, `GET /:id/series?bucket=1h&aggregate=avg`, `POST /series/query`) and the
412
+ `TimeSeriesService`, directly or through the queue (`seriesOptions.ingest`):
413
+
414
+ ```ts
415
+ series: {
416
+ temperature: { type: 'float', minimum: -50, maximum: 150 },
417
+ online: { type: 'boolean' }
418
+ },
419
+ seriesOptions: { ingest: 'queue', retention: '365d', compressAfter: '30d' }
420
+ ```
421
+
422
+ See [timeseries.md](./timeseries.md) for the stores, the ingestion, the routes, the policies and the service.
423
+
424
+ The `spatial` section declares fields holding GeoJSON geometries (`point`, `multiPoint`, `lineString`, `multiLineString`,
425
+ `polygon`, `multiPolygon`, `geometry`), written and read like scalars (a point also as `{ lat, lng }`), and filtered
426
+ with the operators `_near` (meters), `_within`, `_withinBox`, `_intersects` and `_exists`. A record matched by `_near`
427
+ carries its distance as `<field>Distance`, and sorting by the spatial field orders by it. `_near`, `_within` and
428
+ `_intersects` are matched by PostGIS on PostgreSQL (`spatial.provider: postgis`, the default there, needing PostGIS on
429
+ the server) and by the application on every other database (`database`):
430
+
431
+ ```ts
432
+ spatial: {
433
+ location: { type: 'point' },
434
+ deliveryArea: { type: 'polygon', required: false }
435
+ }
436
+ // filter: { location: { _near: { point: { lat: 45.8, lng: 15.97 }, maxDistance: 5000 } } }, sort: 'location'
437
+ // items[0].locationDistance → 412.7
438
+ ```
439
+
440
+ See [spatial.md](./spatial.md) for the values, the operators, the providers and their limits.
441
+
442
+ ### Creating a resource service
443
+
444
+ Resource service defines the business logic layer for a resource: lifecycle hooks (before/after create, update, delete),
445
+ custom data access behavior, and text search configuration. The exported service is automatically invoked by the CRUD
446
+ route handlers to perform database operations for a bound model and trigger side effects.
447
+
448
+ ```ts
449
+ // src/resources/product/service.ts
450
+ import { createService } from '@appweaver/data';
451
+
452
+ export default createService({
453
+ modelName: 'Product',
454
+ afterCreate: (resource) => {
455
+ console.log('Product created:', resource.id);
456
+ },
457
+ textSearch: {
458
+ title: {
459
+ contains: '{input}', // replaced by the searched text
460
+ mode: 'insensitive' // PostgreSQL and MongoDB only
461
+ }
462
+ }
463
+ });
464
+ ```
465
+
466
+ Beyond a few thousand records, use the full-text mode, `textSearch: { mode: 'fts', fields: ['title', 'content'] }`:
467
+ the words of the text are matched with the full-text index of the database, which the application sets up when it
468
+ starts and `weaver migrate` creates (see [resources.md](./resources.md#text-search-example)).
469
+
470
+ The types `weaver generate` emits register every model by name, so the factories and `injectService` infer the model
471
+ types from the model name alone: the hooks of `createService({ modelName: 'Product' })` receive `Product`,
472
+ `ProductCreate`, and `ProductUpdate` values, and a misspelled model name fails to compile. Never pass the types as
473
+ generic arguments. Any code can reach a resource service with `injectService`, typed by the `<Model>ResourceService`
474
+ alias of the model:
475
+
476
+ ```ts
477
+ import { injectService } from '@appweaver/core';
478
+
479
+ const products = injectService('Product'); // ProductResourceService
480
+ const product = await products.find(1);
481
+ const cheapest = await products.single({ price: { _lt: 10 } }, 'price'); // the first match or null
482
+ const count = await products.count({ status: 'Active' });
483
+ const any = await products.exists({ status: 'Sold' });
484
+ ```
485
+
486
+ The `afterUpdate` hook receives the updated resource along with the state it had before the update, i.e.
487
+ `afterUpdate: (product, previous) => { ... }`. The update hooks also run for `replace` (`PUT`).
488
+
489
+ ### Creating the resource routes
490
+
491
+ Resource routes define which endpoints are exposed for a resource and how they behave: the base URL path, the actions
492
+ registered (`actions`, the CRUD ones by default), per-action role and permission requirements, caching settings and
493
+ rate-limiting. The exported routes are registered automatically on application start and derive their request/response schemas
494
+ from the resource model.
495
+
496
+ ```ts
497
+ // src/resources/product/routes.ts
498
+ import { createRoutes } from '@appweaver/web';
499
+
500
+ export default createRoutes({
501
+ modelName: 'Product',
502
+ // Only the listed actions are registered, `crud` standing for find, query, create, update, replace and delete
503
+ actions: ['find', 'query', 'create', 'update', 'replace', 'export'],
504
+ // Applied to every route, unless the route sets the option itself
505
+ defaults: {
506
+ roles: ['Admin', 'User']
507
+ },
508
+ find: {
509
+ cache: true,
510
+ rateLimit: {
511
+ max: 100
512
+ }
513
+ },
514
+ query: {
515
+ cache: { ttl: 5000 },
516
+ // Also serve GET /products/query
517
+ method: 'get-post'
518
+ },
519
+ create: {
520
+ permissions: ['product:create']
521
+ }
522
+ });
523
+ ```
524
+
525
+ `actions` lists the routes of the resource: `crud` (the default) stands for `find`, `query`, `create`, `update`,
526
+ `replace` and `delete`; `aggregate`, `export` and the bulk routes are registered only when listed, i.e.
527
+ `actions: ['crud', 'aggregate', 'export']`. The file and time series routes of a model with such fields too: `files`
528
+ and `series` (`['crud', 'files']`), never for a read only route group that does not list them. The `events` and `mcp` of the routes list their actions the same way, none unless set.
529
+ `weaver routes` prints every route, event and tool of every model, with its access and cache.
530
+
531
+ The `method` option of `query` and `aggregate` (`post` by default, `get`, or `get-post`) registers a GET route taking
532
+ the criteria as query parameters. The defaults come from the `RESOURCE_QUERY_METHOD` and `RESOURCE_AGGREGATE_METHOD`
533
+ config (see `references/resources.md`).
534
+
535
+ The `update` config covers both `PATCH /:id` (partial update) and `PUT /:id` (full replace: required fields must be
536
+ present, omitted ones reset to their `default` or `null`). The `replace` config inherits it and overrides it for
537
+ `PUT /:id` only (i.e. `replace: { roles: ['Admin'] }`; leave `replace` out of `actions` for `PATCH` alone). Likewise the `update`
538
+ `omit`/`pick` of the model shapes the input of both routes, so they always accept the same fields.
539
+
540
+ The bulk routes (`POST`, `PATCH`, `PUT`, `DELETE` on `/bulk`) are registered when `actions` lists `bulkCreate`,
541
+ `bulkUpdate`, `bulkReplace` or `bulkDelete`; `bulkReplace` inherits the config of `bulkUpdate`. Each
542
+ request runs all items in one transaction, all or none, and responds with the array of created, updated, or deleted
543
+ records, like its single route, or only with `{ success, count }` when `RESOURCE_BULK_RETURN_RECORDS` or the route's
544
+ `returnRecords` is `false` (see `references/resources.md`).
545
+
546
+ ### Creating a resource policy
547
+
548
+ Resource policy defines row-level security for a resource: dynamic access checks against individual resource instances,
549
+ read restrictions that filter which records are visible to the requester, and file access control. The service layer
550
+ evaluates the exported policy on every CRUD operation to enforce fine-grained authorization beyond a static role or
551
+ permission checks.
552
+
553
+ ```ts
554
+ // src/resources/product/policy.ts
555
+ import { createPolicy } from '@appweaver/data';
556
+
557
+ export default createPolicy({
558
+ modelName: 'Product',
559
+ checkAccess: (user, resource, action) =>
560
+ action !== 'delete' || resource.status === 'Draft',
561
+ readRestrictions: (user) => (user ? undefined : { enabled: true }), // anonymous users see enabled products only
562
+ files: {
563
+ photo: {
564
+ accessType: 'public'
565
+ }
566
+ }
567
+ });
568
+ ```
569
+
570
+ `checkAccess` denies the action by returning `false`, `readRestrictions` returns extra filter conditions for the reads
571
+ (or nothing to restrict none), and `writeRestrictions` returns data merged into the created or updated record.
572
+
573
+ A record's creator is its `createdById`, an audit field every model has unless its `audit` leaves it out, set to the
574
+ user of the request on create. Restricting a write to the creator (the route keeping the roles allowed to write):
575
+
576
+ ```ts
577
+ // src/resources/book/policy.ts: editors update only the books they created, admins any book
578
+ import { createPolicy, hasRole } from '@appweaver/data';
579
+
580
+ export default createPolicy({
581
+ modelName: 'Book',
582
+ checkAccess: (user, resource, action) =>
583
+ action !== 'update' || (!!user && (hasRole(user, 'Admin') || resource.createdById === user.id))
584
+ });
585
+ ```
586
+
587
+ Policy and file policy callbacks may be `async`, and receive a `null` user for an unauthenticated request. The
588
+ application's own calls outside of a request (jobs, seeders, tasks, tests) skip the policies, unless run as a user with
589
+ `runAs(user, fn)`; inside a request, wrap trusted system code in `withoutPolicies(() => ...)`.
590
+
591
+ Wrap several service calls in `runTransaction(async () => ...)` (optionally with an isolation level first) to commit
592
+ or roll them back together.
593
+
594
+ ### Creating an authentication model and service
595
+
596
+ Use `createAuthModel` and `createAuthService` instead of `createModel`/`createService` when the resource represents an
597
+ authenticatable user. They cannot be used independently! If an auth model is created, then also auth service must exist.
598
+
599
+ `createAuthModel` extends the config with: `email`, `passwordHash`, `verifiedEmail`, `phone`, `verifiedPhone`,
600
+ `enabled`, `logoutAt` scalars; a virtual `password` field (write-only); a `roles` relation; a `twoFactorMethods`
601
+ relation (while 2FA is enabled, managed by the 2FA routes only); and an optional `apiKeys` relation (when
602
+ `SECURITY_API_KEY_ENABLED` is set). An API key acts as its owner, or within the `roles` and `permissions` it
603
+ lists,
604
+ a subset of its owner's (`AUTH_API_KEY_PERMISSION_DENIED` otherwise), narrowed on every request; see
605
+ [security.md](./security.md#api-key-scope). A declared `email` overrides only its `hidden`, `redact`,
606
+ `example`, `minLength`, `maxLength` and `pattern` (it stays the required unique address the sign-in looks the user up
607
+ by), a declared `phone` only its `unique`, `hidden`, `redact` and `example` (the routes never write it, the phone
608
+ verification does),
609
+ and any other auth field replaces a declared one of the same name.
610
+
611
+ `createAuthService` extends the config with automatic password hashing on create/update, an optional
612
+ `registrationData` callback to customize registration payload (for OAuth2 logins its `additionalData` argument includes
613
+ `firstName`, `lastName`, `avatarUrl`, and a downloaded `avatarFile` unless `SECURITY_OAUTH2_FETCH_AVATAR_ENABLED` is
614
+ turned off), an optional `registrationFiles` callback that maps the model's file fields to files stored right after
615
+ the user is created (the avatar included, since a file must be linked to an existing resource), and an optional
616
+ `checkOAuth2User` callback invoked before a user is registered or authenticated via OAuth2 (return nothing to proceed,
617
+ or a string, an `Error`, or an `AppweaverError` to abort the login, the last one thrown as it is).
618
+
619
+ ```ts
620
+ // src/resources/user/model.ts
621
+ import { createAuthModel } from '@appweaver/data';
622
+
623
+ export default createAuthModel({
624
+ name: 'User',
625
+ scalars: {
626
+ name: {
627
+ type: 'string',
628
+ maxLength: 100
629
+ }
630
+ },
631
+ files: {
632
+ avatar: {
633
+ mimeType: 'image/(png|jpeg|gif)',
634
+ maxSize: '2 MB',
635
+ image: { quality: 80, maxHeight: 800, fit: 'inside' }
636
+ }
637
+ }
638
+ });
639
+ ```
640
+
641
+ ```ts
642
+ // src/resources/user/service.ts
643
+ import { createAuthService } from '@appweaver/data';
644
+
645
+ export default createAuthService({
646
+ modelName: 'User',
647
+ registrationData: (_, email, password) => ({
648
+ email,
649
+ password,
650
+ roles: [1, 2]
651
+ }),
652
+ registrationFiles: (_, data) => ({ avatar: data?.avatarFile })
653
+ });
654
+ ```
655
+
656
+ The create and update inputs of an auth model include its `roles`, `password`, and `enabled` fields, so a project
657
+ scaffolded with `web` lets only the `Admin` role create, update, delete, and change the files of users through the
658
+ `User` routes, and
659
+ signs new users up with the `User` role. A policy on the auth model applies only to the API routes: the framework's own
660
+ sign-up, logout, password change, and 2FA flows run with `withoutPolicies`, so a policy never blocks them.
661
+
662
+ Two-factor authentication, off by default (`SECURITY_ACCOUNT_TWO_FACTOR_ENABLED`), offers three methods per user, `Email` and `Sms` codes and an authenticator app (`Totp`),
663
+ each enabled, ordered and disabled by the user with the `/auth/account/two-factor` routes; the first one is their default. A
664
+ sign-in of a user with a method (or of every user with `SECURITY_ACCOUNT_TWO_FACTOR_FORCED`) returns the tokens of the `twoFactor`
665
+ scope with `twoFactorMethods`, passed by `POST /auth/account/two-factor/challenge { method? }` and
666
+ `POST /auth/account/two-factor/verify { challengeId, code }`, then `POST /auth/exchange-token`. The SMS method needs a phone
667
+ number verified with `/auth/account/send-verify-phone` and an SMS sender (`@appweaver/twilio`), the TOTP method the
668
+ `SECURITY_ACCOUNT_TWO_FACTOR_TOTP_ENCRYPTION_KEY`. A user who lost their methods signs in once per code with the recovery codes
669
+ of `POST /auth/account/two-factor/recovery-codes` (challenge `method: 'Recovery'`). With
670
+ `SECURITY_ACCOUNT_TWO_FACTOR_REMEMBER_DEVICE_ENABLED`, `verify { rememberDevice: true }` makes the exchange answer a
671
+ `deviceToken`, sent with the next `login` (or OAuth2 exchange) to skip 2FA on that device. A route that needs a missing feature is not
672
+ registered, so the OpenAPI spec lists only the usable ones: the email verification and password reset need a mailer,
673
+ the phone verification an SMS sender, the 2FA routes 2FA enabled, and `/auth/exchange-token` an OAuth2 provider or 2FA. See
674
+ [security.md](./security.md#two-factor-authentication-2fa).
675
+
676
+ ### Querying resources with filters
677
+
678
+ The `filter` option of the `query` and `aggregate` service methods, the `filter` argument of `single`, `count`,
679
+ `exists`, and `export` (and the `filter` of the matching `POST /query`, `POST /aggregate`, `POST /export` bodies)
680
+ mirrors the WHERE part of a database query. It combines `_`-prefixed operators
681
+ with plain value shorthands and nests through relations:
682
+
683
+ - **Logical**: `_and`, `_or`, `_not`, `_nor` — take a filter object (each entry becomes one condition) or a list of
684
+ filter objects.
685
+ - **Comparison**: `_eq`, `_ne`, `_gt`, `_gte`, `_lt`, `_lte`, `_in`, `_nin`, `_between`, `_like`, `_ilike`, `_starts`,
686
+ `_ends`, `_contains`, `_exists`, `_not`. Operators combined in one object must all match.
687
+ - **List fields**: `_has`, `_hasSome`, `_hasEvery`, `_isEmpty`.
688
+ - **Relations**: `_some`, `_every`, `_none` for list relations, `_exists` for any relation.
689
+ - **Shorthands**: a bare value matches by equality, a list by inclusion, a two-value list on a numeric or date field as
690
+ an inclusive range, and a bare value or list on a relation matches by id.
691
+ - **Limits**: at most `resource.filterMaxConditions` conditions, `filterMaxDepth` levels and `filterMaxListValues`
692
+ values in a list, else `400 RESOURCE_FILTER_TOO_COMPLEX`; the fields a relation `omit`s from its output cannot be
693
+ filtered or sorted on through it.
694
+
695
+ ```ts
696
+ import { injectService } from '@appweaver/core';
697
+ import { UserQuery } from '@/types/generated';
698
+
699
+ const filter: UserQuery = {
700
+ _and: {
701
+ firstName: { _eq: 'John', _exists: true },
702
+ avatar: {
703
+ _or: { title: { _eq: 'Avatar' }, description: { _like: '%avatar%' } }
704
+ }
705
+ },
706
+ _or: [{ firstName: { _like: 'Jo%' } }, { lastName: 'Doe' }],
707
+ roles: { _some: { name: { _contains: 'Admin' } } }
708
+ };
709
+
710
+ const users = await injectService('User').query({
711
+ filter,
712
+ page: 1,
713
+ size: 50,
714
+ sort: '-createdAt'
715
+ });
716
+ ```
717
+
718
+ `query` takes a single options object, the same shape as the `POST /query` body: `filter`, `page` (default `1`),
719
+ `size` (default `50`), `sort` (default `-createdAt`), `cursor`, and `totalCount` (default `false`, bounded by
720
+ `resource.countLimit`; ask for it on the first page only). An offset beyond `resource.maxOffset` is refused, page deeper
721
+ with the cursors.
722
+
723
+ Filters are typed by `QueryFilter<T>` from `@appweaver/common`, and `weaver generate` emits a
724
+ `<Model>Query = QueryFilter<Model>` alias per model. Over HTTP, they are validated against a generated per-model
725
+ `<Model>QueryFilter` JSON schema, which rejects unknown and hidden fields with a `400` `VALIDATION_FAILED` error.
726
+
727
+ ## Sorting
728
+
729
+ The `sort` option of `query`, the `sort` argument of `single` and `export`, and the `sort` property of the `POST /query`
730
+ and `POST /export` bodies accept either a comma-separated field list, where a `-` prefix sorts descending, or an
731
+ object of `asc` and `desc` field directions. Both sort by a field of an included to-one relation and by the record
732
+ count of a to-many relation:
733
+
734
+ ```ts
735
+ await injectService('Post').query({ sort: '-author.createdAt,tagsCount,id' });
736
+ await injectService('Post').query({
737
+ sort: { author: { createdAt: 'desc' }, tagsCount: 'asc', id: 'asc' }
738
+ });
739
+ ```
740
+
741
+ A hidden, virtual, or array scalar field, a field of a to-many relation, or a relation the action does not include is
742
+ rejected with a `RESOURCE_INVALID_SORT` error (400). Sort inputs are typed by `QuerySort<T>` from `@appweaver/common`,
743
+ with a `<Model>Sort`
744
+ alias emitted per model and validated over HTTP against a generated `<Model>QuerySort` JSON schema. The default is
745
+ `-createdAt`, and every sort is terminated with the primary key so paging stays deterministic.
746
+
747
+ ## Optimistic concurrency
748
+
749
+ The single-record responses carry an `ETag` (the quoted `updatedAt`); sending it, or the `updatedAt` read, as
750
+ `If-Match` on `PATCH`, `PUT` or `DELETE /:id` (`update(id, data, { ifMatch })` in code) fails a write of a record
751
+ changed since with `412 RESOURCE_PRECONDITION_FAILED`. See
752
+ [resources.md](./resources.md#optimistic-concurrency-if-match).
753
+
754
+ ## Aggregating
755
+
756
+ `aggregate` takes a single options object, the same shape as the `POST /aggregate` body: `select`, `filter`,
757
+ `dateField` (default `createdAt`), `from` (inclusive), `to` (exclusive), and `interval`. Without `from` and `to` the
758
+ whole filter is aggregated; without `interval` only the `total`, `items` being empty. An `interval` is an amount and a
759
+ unit of `s`, `m`, `h`, `d`, `w`, `mo` or `y` (`'1d'`), its periods starting at `from` or at the earliest record
760
+ (truncated to the unit), at most `resource.aggregateMaxPeriods` (1000). The required `select` holds the operators
761
+ to apply per field. Only the numeric fields (`count`, `sum`, `avg`, `min`, `max`, `first`, `last`), the date fields (all
762
+ but `sum` and `avg`), and the numeric `id` and audit fields of the model can be aggregated:
763
+
764
+ ```ts
765
+ await injectService('Post').aggregate({
766
+ select: {
767
+ counter: { count: true, sum: true, avg: true, first: true, last: true },
768
+ publishedAt: { min: true, max: true }
769
+ },
770
+ dateField: 'createdAt',
771
+ from: '2026-01-01T00:00:00.000Z',
772
+ to: '2026-01-08T00:00:00.000Z',
773
+ interval: '1d'
774
+ });
775
+ ```
776
+
777
+ The aggregate runs in one SQL statement grouping the records by period. A filter it cannot express in SQL (a relation,
778
+ JSON or list filter) runs one Prisma aggregation per period instead, in a transaction. `first` and `last` take the
779
+ value held by the earliest and the latest record of a period, ordered by the aggregated `dateField` (ties broken by
780
+ `id`).
781
+
782
+ Any other field (string, boolean, enum, JSON, array, hidden, virtual, or a relation), an operator its type does not
783
+ support, an empty selection, or a `dateField` that is not a date field is rejected with a `RESOURCE_INVALID_AGGREGATE`
784
+ error (400). Selections are
785
+ typed by `AggregateSelect<T>` from `@appweaver/common`, with a `<Model>Aggregate` alias emitted per model, and validated
786
+ over HTTP against a generated `<Model>AggregateSelect` JSON schema.
787
+
788
+ The response type is inferred from the selection, so a selection given as an object literal (or declared with
789
+ `satisfies <Model>Aggregate`) narrows it to the selected fields, while one annotated as `<Model>Aggregate` keeps every
790
+ aggregatable field of the model:
791
+
792
+ ```ts
793
+ const stats = await injectService('Post').aggregate({
794
+ select: { counter: { sum: true } }
795
+ });
796
+ stats.total.counter?.sum; // typed
797
+ stats.total.publishedAt; // compile error, the field was not selected
798
+ ```
799
+
800
+ ## Registering a custom route
801
+
802
+ Use `registerRoute` to register a custom [Fastify route](https://fastify.dev/docs/latest/Reference/Routes/) handler. The
803
+ handler is a Fastify plugin function that defines one or more routes. An optional config object controls authentication,
804
+ caching, and the bot checks (`recaptcha`/`recaptchaAction` for reCAPTCHA, `turnstile`/`turnstileAction` for Cloudflare
805
+ Turnstile). When a custom route's 2xx response schema references resource output models (`<Name>`, `<Name>Single` or
806
+ `<Name>Multiple` — directly or nested inside custom schemas), virtual field values (e.g. `File.url`) are projected onto
807
+ the response payload automatically before serialization.
808
+
809
+ Route and model schemas are written with [TypeBox](https://github.com/sinclairzx81/typebox) 1.x (`typebox`), a
810
+ dependency of every scaffolded project at the version the framework uses, which `weaver upgrade` keeps in step.
811
+ TypeBox 1.x has no `Type.Composite`: merge object schemas with `Composite` of `@appweaver/common`. Its types declare
812
+ no JSON Schema keyword, so read one through `schemaNode(schema).$id` (`SchemaNode`). It ships ES modules only: the
813
+ Jest preset of `@appweaver/tooling` compiles them, and a project's own Jest config transforms `.mjs` and keeps `typebox`
814
+ out of `transformIgnorePatterns`.
815
+
816
+ Request validation is strict: a `body`, `querystring` or `params` property the route schema does not declare is
817
+ rejected with `VALIDATION_FAILED` (`rule: "additionalProperties"`, `message: "is not allowed"`), never silently dropped.
818
+ Every object schema declaring `properties` is closed, unless it sets `additionalProperties` itself, so an object meant
819
+ to accept arbitrary keys sets `additionalProperties: true`. The members of a `Type.Intersect` (an `allOf` of several
820
+ schemas) stay open, and `headers` are never closed.
821
+
822
+ ```ts
823
+ // src/plugins/custom-route.ts
824
+ import { registerRoute, Router } from '@appweaver/web';
825
+ import { Type } from 'typebox';
826
+
827
+ registerRoute(
828
+ async function (router: Router) {
829
+ router.get('/search-result', {
830
+ schema: {
831
+ summary: 'Sample search result response route',
832
+ response: {
833
+ 200: Type.Ref('SearchResult')
834
+ }
835
+ },
836
+ handler: async () => {
837
+ return { message: 'Hello, world!' };
838
+ }
839
+ });
840
+ },
841
+ { public: true, cache: { ttl: 15000 } }
842
+ );
843
+ ```
844
+
845
+ ## Rendering templates and translating
846
+
847
+ The `templates/` files render emails, HTML pages, XML documents or any text, and the `locales/<locale>.json` files
848
+ translate keys anywhere in the application. The two are independent: templates render without translation files, and
849
+ translations work without the template engine. The application always gives the locale (a request parameter, a user
850
+ field,
851
+ ...), falling back to `LOCALE_DEFAULT`. A template named `exports/orders.xml` is the file
852
+ `templates/exports/orders.xml.hbs`, and `templates/exports/orders.de.xml.hbs` is its `de` variant.
853
+ See [templates.md](./templates.md).
854
+
855
+ ```ts
856
+ import { TemplateEngine, templateContentType } from '@appweaver/common';
857
+ import { EmailService, inject, LocaleService } from '@appweaver/core';
858
+
859
+ // Any format, i.e. an XML document returned by a custom route
860
+ const xml = await inject(TemplateEngine).render(
861
+ 'exports/orders.xml',
862
+ { orders },
863
+ { locale }
864
+ );
865
+ reply.type(templateContentType('exports/orders.xml')).send(xml);
866
+
867
+ // An email of the emails/order-shipped.{html,subject}.hbs templates, its text derived from the HTML
868
+ await inject(EmailService).sendEmail({
869
+ to,
870
+ template: 'emails/order-shipped',
871
+ data: { order },
872
+ locale
873
+ });
874
+
875
+ // A translated string, i.e. in a service hook
876
+ inject(LocaleService).translate('inbox.unread', 'de', { msg_cnt: 3 });
877
+ ```
878
+
879
+ A translation is an ICU MessageFormat message in a JSON file of nested objects, translated by its dotted key
880
+ (`inbox.unread`), with plural forms by the CLDR categories of the locale: `{ "inbox": { "unread": "You have {msg_cnt,
881
+ plural, =0 {no unread messages} one {# unread message} other {# unread messages}}" } }`.
882
+
883
+ Inside the templates, `{{t "key" name=value}}` translates into the rendered locale, layouts and components are partials
884
+ (`{{#> layouts/page.html}}...{{/layouts/page.html}}`), and `formatDate`, `formatNumber`, `formatCurrency` format in the
885
+ locale. The account emails (verification, password reset, 2FA) render the `emails/*` templates of the application,
886
+ scaffolded by `@appweaver/create`, or without them are sent as plain text of the `emails.*` translations.
887
+
888
+ An email's `from` overrides the sender of the `mailer` config, see [the sender](./mailer.md#the-sender).
889
+
890
+ To check a template while editing it, enable `template.preview.enabled` in the `dev` environment: `GET
891
+ /templates/emails/order-shipped.html?_locale=de&order.number=WS-1` renders it with the query parameters as its data
892
+ (dotted names nest, `_data` takes a JSON object). It is open without authentication unless `template.preview.auth` is
893
+ `true`. See [templates.md](./templates.md#previewing-templates).
894
+
895
+ ## Handling errors
896
+
897
+ Services, policies, hooks, jobs and workers throw an `AppweaverError` subclass carrying a stable `code` (the `ErrorCode`
898
+ enum of `@appweaver/common`) and typed `details`, never an HTTP status. Only the API layer maps the code to a status and
899
+ responds with RFC 9457 problem details (`application/problem+json`), i.e.
900
+ `{ type, title, status, code, detail, instance, requestId, errors, details }`. A schema validation failure responds with
901
+ `VALIDATION_FAILED` and its invalid `errors`, and a database constraint violation with a `DATABASE_*` code naming the
902
+ violated fields, i.e. `DATABASE_UNIQUE_VIOLATION` (409) for a taken email, so there is no need to look a value up
903
+ before creating a record.
904
+
905
+ ```ts
906
+ import { ApplicationError, ErrorCode } from '@appweaver/common';
907
+ import { defineErrors, ResourceError } from '@appweaver/common';
908
+ import { errorResponses } from '@appweaver/web';
909
+
910
+ // A module of its own, imported where the codes are used
911
+ export const ShopErrors = defineErrors({
912
+ OutOfStock: { status: 409, title: 'Product out of stock' }
913
+ });
914
+
915
+ throw new ResourceError(ErrorCode.ResourceNotFound, 'Order not found', {
916
+ model: 'Order',
917
+ id
918
+ });
919
+ throw new ApplicationError(ShopErrors.OutOfStock, 'Only 2 left', { productId });
920
+
921
+ // The documented errors of a custom route, see the response schema of registerRoute
922
+ const response = {
923
+ 200: Type.Ref('OrderSingle'),
924
+ ...errorResponses(ShopErrors.OutOfStock)
925
+ };
926
+ ```
927
+
928
+ Use the framework class that fits (`ResourceError`, `RequestError` for invalid input, `AuthError`, `FileError`, ...),
929
+ and an `ApplicationError` with a code registered by `defineErrors` for a business rule of the application. Never throw a
930
+ plain `Error` for an expected failure, it responds with `INTERNAL_ERROR` (500). Translate the errors of a direct Prisma
931
+ call with `toDatabaseError(e, 'Model')`.
932
+
933
+ ## Logging
934
+
935
+ Log with a named logger, `createLogger('billing')` of `@appweaver/common`, so `log.levels.billing` can set its level
936
+ apart from `log.level`. A module lists the names of its loggers in the `loggers` of its manifest, so
937
+ `appweaver.schema.json` suggests them in `log.levels`. The application chooses its own levels: `info` for the behavior
938
+ worth seeing in the
939
+ production logs (a scheduled job's result, an order placed), `debug` for the details of how it got there. See
940
+ [logging.md](./logging.md) for the levels the framework logs at, its loggers and the config.
941
+
942
+ ## Telemetry
943
+
944
+ The framework records OpenTelemetry traces and metrics on its own: the HTTP requests, the database operations, the
945
+ queue jobs (in the trace of their sender), the scheduled jobs, the emails, the text messages and the tasks. They are
946
+ exported once the `telemetry` module is added (`weaver module add telemetry`, `@appweaver/opentelemetry`), over OTLP
947
+ to the `telemetry.endpoint`, and every log record carries the `trace_id` of its span. Add spans and metrics of the
948
+ application with the helpers of `@appweaver/common`, never with a vendor SDK:
949
+
950
+ ```ts
951
+ import { currentSpan, telemetryCounter, withSpan } from '@appweaver/common';
952
+
953
+ const invoices = telemetryCounter('billing.invoices');
954
+
955
+ currentSpan()?.setAttribute('order.id', orderId); // the span of the request or the job
956
+ const pdf = await withSpan(
957
+ 'invoice render',
958
+ { attributes: { 'order.id': orderId } },
959
+ () => render(orderId)
960
+ );
961
+ invoices().add(1);
962
+ ```
963
+
964
+ See [telemetry.md](./telemetry.md) for what is recorded, the config, the backends (`configureTelemetry`) and
965
+ `recordTelemetry` of `@appweaver/testing`.
966
+
967
+ ## Audit log
968
+
969
+ `audit.enabled` records every request (the user, the client address, the status, the error code) in the `AuditLog`
970
+ table and the changed fields of every record the resource services write in `AuditChange`, the passwords and secrets
971
+ redacted, both kept for `audit.retention`. The `auth`, `read`, `write`, `changes` and `custom` categories are switched
972
+ and kept on their own, the reads off by default. Leave out paths, models and actions with `audit.excludePaths`,
973
+ `audit.excludeModels` and `audit.excludeActions`, or a route with `audit: false`, and keep a field's values out with
974
+ `redact: true`. Code writing through Prisma directly records its changes with `AuditService.recordChange`. See
975
+ [audit.md](./audit.md).
976
+
977
+ ## Realtime events
978
+
979
+ With the `realtime` module (`@appweaver/realtime`), clients subscribe over WebSocket or SSE to the channels of the
980
+ application and the resource events of the models exposing them, and call custom actions. Nothing is exposed unless
981
+ declared, every event is checked against the access of the user, and `public: true` opens a part to anonymous clients
982
+ once `realtime.anonymousEnabled` is set:
983
+
984
+ ```ts
985
+ export const orderShipped = createChannel({
986
+ name: 'order.shipped',
987
+ payload: Type.Object({ orderId: Type.Integer(), customerId: Type.Integer() }),
988
+ deliver: (user, payload) => payload.customerId === user?.id
989
+ });
990
+ await orderShipped.publish({ orderId: 7, customerId: 1 });
991
+
992
+ createRoutes({
993
+ modelName: 'order',
994
+ events: { actions: ['create', { action: 'update', public: true }] }
995
+ });
996
+ createPolicy({
997
+ modelName: 'order',
998
+ events: (user, { current }) => current.customerId === user?.id
999
+ });
1000
+ createRealtimeAction({
1001
+ name: 'chat.typing',
1002
+ payload: Type.Object({ roomId: Type.Integer() }),
1003
+ handler: ({ roomId }, { user }) =>
1004
+ typing.publish({ roomId, userId: user!.id })
1005
+ });
1006
+ ```
1007
+
1008
+ To stream chunks rather than events (the tokens of an LLM answer, bytes), use a **streaming action** for the caller
1009
+ alone, or `createStream` for the subscribers of a key. A subscriber is checked once, never per chunk, and a chunk
1010
+ reaches another instance only while one of them has a subscriber:
1011
+
1012
+ ```ts
1013
+ createRealtimeAction({
1014
+ name: 'assistant.prompt',
1015
+ payload: Type.Object({ prompt: Type.String() }),
1016
+ stream: { codec: 'text', coalesce: 16 },
1017
+ async *handler({ prompt }, { signal }) {
1018
+ for await (const token of llm.stream(prompt, { signal })) yield token; // signal: cancelled or client gone
1019
+ }
1020
+ });
1021
+
1022
+ export const roomAnswer = createStream({
1023
+ name: 'room.answer',
1024
+ subscribe: (user, _, key) => isMember(user, key)
1025
+ });
1026
+ const writer = roomAnswer.open(roomId);
1027
+ writer.write('Hello');
1028
+ writer.end();
1029
+ ```
1030
+
1031
+ An action with `input` receives the chunks a client streams over the WebSocket (`context.input`, paced by credits),
1032
+ i.e. the audio of a microphone. A stream with `resource: { model }` lets subscribe only the users able to `find` the
1033
+ record of the key, so the policy of the model decides. A logout, a disabling or a lost role ends the calls of a user at
1034
+ once (their `signal` aborts), over HTTP too.
1035
+
1036
+ On a rolling update an instance drains: it moves its clients to the other instances (`1012`), relays the streaming
1037
+ actions they resume there until they end, and waits for its calls at most `realtime.shutdownGracePeriod`.
1038
+
1039
+ The generated client calls `client.realtime.subscribe`, `on`, `send`, `emit`, `call` (a streaming action, an async
1040
+ iterable of its chunks, with `call.input` or `{ input }` for an input) and `stream`. See
1041
+ [realtime.md](./realtime.md).
1042
+
1043
+ ## AI models
1044
+
1045
+ With the `ai` module (`@appweaver/ai` and `@appweaver/openai`), `AiService` calls the models of the endpoints of the
1046
+ `ai` config: any OpenAI-compatible server (Ollama, LM Studio, OpenRouter, OpenAI, ...), all usable at once. A model is a
1047
+ reference `<endpoint>:<model>` (`local:qwen3:8b`) or an alias of `ai.aliases` (`fast`, any name), so each environment
1048
+ picks its models (the built-in `mock` endpoint in tests):
1049
+
1050
+ ```ts
1051
+ const ai = inject(AiService);
1052
+ const { text } = await ai.generate({
1053
+ model: 'fast',
1054
+ system: 'Be brief.',
1055
+ prompt: question
1056
+ });
1057
+ for await (const delta of ai.stream({
1058
+ prompt: { template: 'prompts/answer', data }
1059
+ }))
1060
+ send(delta);
1061
+ const { object } = await ai.generateObject({
1062
+ prompt: ticket.body,
1063
+ schema: TicketTriage
1064
+ });
1065
+ const label = await ai.classify(ticket.body, ['bug', 'billing']);
1066
+ await ai.generate({ prompt: 'Where is order 42?', tools: [getOrder] }); // createAiTool, run as the user
1067
+ await ai.generateQueued({ prompt: 'Summarize ...' }); // through the `ai` queue, on any instance
1068
+ ```
1069
+
1070
+ A stream is an async iterable of text: a streaming realtime action returns it, `pipeAiStream` writes it into a
1071
+ `createStream` writer, `aiEventStream` into an SSE response. See [ai.md](./ai.md).
1072
+
1073
+ ## MCP server
1074
+
1075
+ With the `mcp` module (`@appweaver/mcp`), AI agents call the application over the Model Context Protocol at
1076
+ `POST /mcp`, authenticated like the API (JWT, API keys) and running as that user, so the policies apply. Nothing is
1077
+ exposed unless declared: resource actions with the `mcp` key of `createRoutes`, custom tools with `createMcpTool`.
1078
+ `update`, `delete` and tools marked `destructive` also need `mcp.destructiveEnabled`:
1079
+
1080
+ ```ts
1081
+ createRoutes({
1082
+ modelName: 'post',
1083
+ mcp: { actions: ['find', 'query', 'create'], exclude: ['note'] }
1084
+ }); // the access of the API routes
1085
+ createMcpTool({
1086
+ name: 'refundOrder',
1087
+ input: Type.Object({ orderId: Type.Integer() }),
1088
+ roles: ['support'],
1089
+ destructive: true,
1090
+ handler: ({ orderId }) => refunds.refund(orderId)
1091
+ });
1092
+ ```
1093
+
1094
+ `mcp.cache.enabled` caches the read-only tool results per user, `mcp.rateLimit.enabled` limits the tool calls per
1095
+ user, and `mcp.oauth2.enabled` lets the MCP clients sign their users in by themselves (OAuth discovery, dynamic
1096
+ client registration, PKCE) through the OAuth2 providers of `security.oauth2`. See [mcp.md](./mcp.md).
1097
+
1098
+ ## Registering a custom model
1099
+
1100
+ Use `registerModel` to register a custom [TypeBox](https://github.com/sinclairzx81/typebox) schema as a named model.
1101
+ Registered models are added to the schema registry and can be referenced by `$ref` in route schemas.
1102
+
1103
+ ```ts
1104
+ // src/plugins/custom-model.ts
1105
+ import { registerModel } from '@appweaver/web';
1106
+ import { Type } from 'typebox';
1107
+
1108
+ registerModel(
1109
+ Type.Object(
1110
+ {
1111
+ id: Type.Number(),
1112
+ title: Type.String(),
1113
+ score: Type.Number({ minimum: 0, maximum: 1 })
1114
+ },
1115
+ { $id: 'SearchResult' }
1116
+ )
1117
+ );
1118
+ ```
1119
+
1120
+ ## Registering plugin
1121
+
1122
+ Use `registerPlugin` to register a custom [Fastify plugin](https://fastify.dev/docs/latest/Reference/Plugins/). Plugins
1123
+ are registered with `fastify-plugin` so their decorators and hooks are scoped to the entire server. You can declare
1124
+ optional dependencies on other named plugins.
1125
+
1126
+ ```ts
1127
+ // src/plugins/audit-log.ts
1128
+ import { registerPlugin } from '@appweaver/web';
1129
+
1130
+ registerPlugin('audit-log', async (server) => {
1131
+ server.addHook('onResponse', async (request, reply) => {
1132
+ console.log(`${request.method} ${request.url} → ${reply.statusCode}`);
1133
+ });
1134
+ });
1135
+ ```
1136
+
1137
+ ## Dependency injection
1138
+
1139
+ Use `define` to register a value or class in the app context, and `inject` to retrieve it. Class constructors are lazily
1140
+ instantiated as singletons on the first injection.
1141
+
1142
+ ```ts
1143
+ import { Cache } from '@appweaver/common';
1144
+ import { define, inject } from '@appweaver/core';
1145
+
1146
+ define(MyCacheService, Cache); // register class under abstract token
1147
+ define('https://api.example.com', 'ApiBaseUrl'); // register plain value
1148
+
1149
+ const cache = inject(Cache); // resolves singleton instance
1150
+ const url = inject<string>('ApiBaseUrl'); // resolves by string token
1151
+ ```
1152
+
1153
+ The infrastructure providers (`Storage`, `Mailer`, `Queue`, ...) are defined by the modules from the `provider` keys,
1154
+ so `main.ts` never wires them. Inject an optional one with a fallback, or check it first:
1155
+
1156
+ ```ts
1157
+ import { Mailer } from '@appweaver/common';
1158
+ import { inject, isDefined } from '@appweaver/core';
1159
+
1160
+ const mailer: Mailer | undefined = inject(Mailer, false); // undefined with MAILER_PROVIDER=none
1161
+ if (isDefined(Mailer)) {
1162
+ /* ... */
1163
+ }
1164
+ ```
1165
+
1166
+ A registered class setting the static `[LIFECYCLE] = true` tag has its hooks of `@appweaver/common` called:
1167
+ `onInit()` when the application starts, `onReady()` once every service is initialized, `onShutdown()`
1168
+ first on stop, and `onDestroy()` last;
1169
+ see [dependency-injection.md](./dependency-injection.md#lifecycle-hooks).
1170
+
1171
+ ## Writing a seeder
1172
+
1173
+ A seeder is a TypeScript file that must export at least one asynchronous function responsible for executing database
1174
+ seeding logic. Seeder files follow the same conventions as migration files: they can only be executed once, and their
1175
+ execution status is recorded in the database table `_seeders`. Seeders are executed in alphabetical order; therefore,
1176
+ the recommended naming convention is to prefix the filename with an ordinal number (e.g., `001-create-admin-user.ts`).
1177
+
1178
+ During execution of seeder functions, the full application context is available, which means it is possible to inject
1179
+ any service or model previously defined in the main application logic or exported from other NPM packages.
1180
+
1181
+ ```ts
1182
+ // database/seeders/001-create-admin-user.ts
1183
+
1184
+ import { hashPassword, systemConfig } from '@appweaver/data';
1185
+ import { randomString } from '@appweaver/common';
1186
+ import { db } from '@db/client';
1187
+
1188
+ export async function createAdminUser(): Promise<void> {
1189
+ const password =
1190
+ systemConfig.ADMIN_INITIAL_PASSWORD || randomString(16, { extra: false });
1191
+
1192
+ await db.user.create({
1193
+ data: {
1194
+ firstName: 'Admin',
1195
+ lastName: 'Admin',
1196
+ email: systemConfig.ADMIN_INITIAL_EMAIL,
1197
+ passwordHash: await hashPassword(password),
1198
+ roles: {
1199
+ connectOrCreate: [
1200
+ {
1201
+ where: { name: 'Admin' },
1202
+ create: {
1203
+ name: 'Admin',
1204
+ permissions: {
1205
+ connectOrCreate: [
1206
+ { where: { name: 'manage' }, create: { name: 'manage' } },
1207
+ { where: { name: 'view' }, create: { name: 'view' } }
1208
+ ]
1209
+ }
1210
+ }
1211
+ }
1212
+ ]
1213
+ }
1214
+ }
1215
+ });
1216
+ }
1217
+ ```