@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.
- package/LICENSE +21 -0
- package/README.md +29 -2
- package/index.d.ts +39 -0
- package/index.js +105 -0
- package/package.json +41 -3
- package/skill/GUIDELINES.md +383 -0
- package/skill/SKILL.md +121 -0
- package/skill/references/ai.md +231 -0
- package/skill/references/audit.md +220 -0
- package/skill/references/cache.md +233 -0
- package/skill/references/cli.md +760 -0
- package/skill/references/client.md +982 -0
- package/skill/references/configuration.md +1224 -0
- package/skill/references/database.md +349 -0
- package/skill/references/dependency-injection.md +301 -0
- package/skill/references/errors.md +486 -0
- package/skill/references/events.md +203 -0
- package/skill/references/logging.md +157 -0
- package/skill/references/mailer.md +393 -0
- package/skill/references/mcp.md +245 -0
- package/skill/references/modules.md +509 -0
- package/skill/references/patterns.md +1217 -0
- package/skill/references/payments.md +795 -0
- package/skill/references/queue.md +281 -0
- package/skill/references/realtime.md +572 -0
- package/skill/references/resources.md +2238 -0
- package/skill/references/scheduler.md +228 -0
- package/skill/references/security.md +1185 -0
- package/skill/references/sms.md +143 -0
- package/skill/references/spatial.md +197 -0
- package/skill/references/storage.md +500 -0
- package/skill/references/telemetry.md +207 -0
- package/skill/references/templates.md +488 -0
- package/skill/references/timeseries.md +312 -0
- package/skill/references/workflow.md +224 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# Events
|
|
2
|
+
|
|
3
|
+
The events module provides a resource-scoped publish/subscribe system built on top of Node.js `EventEmitter`. It is used
|
|
4
|
+
internally by the framework to broadcast resource lifecycle changes (`create`, `update`, `delete`, `find`, `query`) and
|
|
5
|
+
can be used directly to react to those events anywhere in the application.
|
|
6
|
+
|
|
7
|
+
## Injecting Events
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { inject } from '@appweaver/core';
|
|
11
|
+
import { Events } from '@appweaver/common';
|
|
12
|
+
|
|
13
|
+
const events = inject(Events);
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
#### `events.onResourceEvent(resourceName, event, listener)`
|
|
19
|
+
|
|
20
|
+
Registers a listener for a specific resource and action. Returns a listener ID that can be used to unsubscribe.
|
|
21
|
+
|
|
22
|
+
| Parameter | Type | Description |
|
|
23
|
+
| -------------- | ------------------ | ------------------------------------------------------- |
|
|
24
|
+
| `resourceName` | `string` | The name of the resource model (e.g. `'Product'`) |
|
|
25
|
+
| `event` | `ActionType` | `'create'`, `'update'`, `'delete'`, `'find'`, `'query'` |
|
|
26
|
+
| `listener` | `EventListener<T>` | Callback receiving `EventData<T>` |
|
|
27
|
+
|
|
28
|
+
Once the types are generated (`weaver generate`), the records are typed by the model name, like `injectService`:
|
|
29
|
+
`current` and `previous` are `ResourceRecord<'Product'>`, the model type with its foreign keys and relation counts,
|
|
30
|
+
and `current` is an array of them for a `query`. Give the type yourself for a model name known only at runtime,
|
|
31
|
+
`events.onResourceEvent<AuthUser>(modelName, 'update', listener)`.
|
|
32
|
+
|
|
33
|
+
`EventData<T>` shape:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
type EventData<T> = {
|
|
37
|
+
previous?: T; // present on 'update'
|
|
38
|
+
current: T; // an array of resources on 'query'
|
|
39
|
+
};
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The resources are the ones the service returns, the same objects: their virtual fields set (computed once, so a
|
|
43
|
+
non-deterministic one has the same value in the event and in the API response), their relation counts set (`postsCount`
|
|
44
|
+
instead of `_count`), and their soft deleted relations hidden. They still hold the hidden fields (i.e. `passwordHash`),
|
|
45
|
+
which only the response serialization leaves out. A change of a listener would reach the response, so the listener
|
|
46
|
+
receives them readonly at every depth (`DeepReadonly` of `@appweaver/common`): `current.status = 'x'` or
|
|
47
|
+
`current.items.push(item)` fails to compile. A function taking a record of an event takes it as
|
|
48
|
+
`DeepReadonly<Product>`, or the `Pick` of the fields it reads; to change one, copy it (`{ ...current, status: 'x' }`).
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
const listenerId = events.onResourceEvent(
|
|
52
|
+
'Product',
|
|
53
|
+
'create',
|
|
54
|
+
({ current }) => {
|
|
55
|
+
logger.info('New product created:', current.name);
|
|
56
|
+
}
|
|
57
|
+
);
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
**Listening to updates** (access both previous and current state):
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
events.onResourceEvent('User', 'update', ({ previous, current }) => {
|
|
64
|
+
if (previous?.email !== current.email) {
|
|
65
|
+
sendEmailChangeNotification(current);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
#### `events.emitResourceEvent<T>(resourceName, event, data)`
|
|
73
|
+
|
|
74
|
+
Emits an event for a resource. The framework calls this automatically after every resource mutation of a resource
|
|
75
|
+
service ([resources.md](./resources.md#createservice)); use it directly only when you need to emit custom events from
|
|
76
|
+
your own service logic.
|
|
77
|
+
|
|
78
|
+
| Parameter | Type | Description |
|
|
79
|
+
| -------------- | -------------- | ----------------------------------------------- |
|
|
80
|
+
| `resourceName` | `string` | Resource model name |
|
|
81
|
+
| `event` | `ActionType` | Action type |
|
|
82
|
+
| `data` | `EventData<T>` | Object with `current` (and optional `previous`) |
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
events.emitResourceEvent<Order>('Order', 'create', { current: newOrder });
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
#### `events.removeResourceEvent(listenerId)`
|
|
91
|
+
|
|
92
|
+
Unregisters a listener by the ID returned from `onResourceEvent`. Returns `true` if the listener was found and removed.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const listenerId = events.onResourceEvent('Product', 'delete', handler);
|
|
96
|
+
// ... later:
|
|
97
|
+
events.removeResourceEvent(listenerId);
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## Realtime
|
|
103
|
+
|
|
104
|
+
The resource events stay in the process: the listeners of `onResourceEvent` run once, on the instance of the change. To
|
|
105
|
+
push them to the clients, expose them on the routes of the model with `createRoutes({ events: { actions } })` and the
|
|
106
|
+
`@appweaver/realtime` module, which publishes them through the `PubSub` contract (`memory` or `redis`) to the
|
|
107
|
+
realtime connections of every instance, each event checked against the access of the subscribed user. The `find` and
|
|
108
|
+
`query` events are never exposed. See [realtime.md](./realtime.md).
|
|
109
|
+
|
|
110
|
+
## Broadcasting between instances
|
|
111
|
+
|
|
112
|
+
`Events` stay in the process. To tell every instance something, use the `PubSub` contract: with `@appweaver/redis`
|
|
113
|
+
every subscribed instance receives a message (Redis pub/sub), otherwise only the process itself.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
import { PubSub } from '@appweaver/common';
|
|
117
|
+
import { inject } from '@appweaver/core';
|
|
118
|
+
|
|
119
|
+
const pubsub = inject(PubSub);
|
|
120
|
+
|
|
121
|
+
await pubsub.subscribe<{ key: string }>('cache.cleared', ({ key }) =>
|
|
122
|
+
localCache.delete(key)
|
|
123
|
+
);
|
|
124
|
+
await pubsub.publish('cache.cleared', { key: 'products' });
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
A message is JSON (dates arrive as strings), reaches the publisher too, and is delivered at most once: an instance
|
|
128
|
+
down or reconnecting misses it. Use it for what every instance should know now (a local cache, a flag, an ops
|
|
129
|
+
signal), and the `Queue` for work that must run once and survive a failure (an email, a payment). The `realtime:`
|
|
130
|
+
channels belong to `@appweaver/realtime`.
|
|
131
|
+
|
|
132
|
+
## Configuration
|
|
133
|
+
|
|
134
|
+
| Key | Type | Default | Description |
|
|
135
|
+
| ---------------------- | -------- | -------- | ------------------------------------- |
|
|
136
|
+
| `EVENTS_MAX_LISTENERS` | `int` | `20` | Max listeners per event (Node.js cap) |
|
|
137
|
+
| `EVENTS_PROVIDER` | `string` | `'auto'` | `auto`/`node`, or a module path |
|
|
138
|
+
|
|
139
|
+
## Real-world example
|
|
140
|
+
|
|
141
|
+
Register listeners at startup, then let the framework drive the emit side:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// src/features/notifications/notification-listener.ts
|
|
145
|
+
import { inject } from '@appweaver/core';
|
|
146
|
+
import { createLogger, Events, Mailer } from '@appweaver/common';
|
|
147
|
+
|
|
148
|
+
const logger = createLogger('notifications');
|
|
149
|
+
|
|
150
|
+
export function registerNotificationListeners() {
|
|
151
|
+
const events = inject(Events);
|
|
152
|
+
const mailer = inject(Mailer, false);
|
|
153
|
+
|
|
154
|
+
events.onResourceEvent('Order', 'create', async ({ current }) => {
|
|
155
|
+
if (!mailer) return;
|
|
156
|
+
await mailer.sendEmail({
|
|
157
|
+
to: current.customerEmail,
|
|
158
|
+
subject: 'Order received',
|
|
159
|
+
text: `Your order #${current.id} has been placed.`
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
events.onResourceEvent('User', 'delete', ({ current }) => {
|
|
164
|
+
logger.info(`User ${current.id} was deleted — cleaning up sessions`);
|
|
165
|
+
cleanupSessions(current.id);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Call `registerNotificationListeners()` during application startup, after the providers are loaded. A listener runs in
|
|
171
|
+
the process that made the change, so move slow or retried work to a queue ([queue.md](./queue.md)).
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## Using Node.js EventEmitter directly
|
|
176
|
+
|
|
177
|
+
Since `Events` extends Node.js `EventEmitter`, you can use the standard `.on()` / `.emit()` API for custom application
|
|
178
|
+
events alongside the resource event helpers.
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
import { inject } from '@appweaver/core';
|
|
182
|
+
import { Events } from '@appweaver/common';
|
|
183
|
+
|
|
184
|
+
const events = inject(Events);
|
|
185
|
+
|
|
186
|
+
// Listen for a custom event
|
|
187
|
+
events.on('user-registered', (user: User) => {
|
|
188
|
+
logger.info(`Welcome email queued for ${user.email}`);
|
|
189
|
+
mailer.sendWelcomeEmail(user);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
// Emit the event from your service
|
|
193
|
+
events.emit('user-registered', newUser);
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
You can use any string as the event name. The listener receives whatever arguments you pass to `emit`. Use
|
|
197
|
+
`events.once()` if you only need to handle the event one time:
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
events.once('user-registered', (user: User) => {
|
|
201
|
+
logger.info(`First registration ever: ${user.email}`);
|
|
202
|
+
});
|
|
203
|
+
```
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# Logging
|
|
2
|
+
|
|
3
|
+
Appweaver logs with [pino](https://getpino.io), as JSON records on the standard output, and in a rotated file with
|
|
4
|
+
`LOG_PATH`. The config keys are listed in [configuration.md](./configuration.md#logging-log_).
|
|
5
|
+
|
|
6
|
+
## Loggers
|
|
7
|
+
|
|
8
|
+
`@appweaver/common` exports two kinds of logger:
|
|
9
|
+
|
|
10
|
+
- `logger` — the default logger, logging at `LOG_LEVEL` (`log.level`)
|
|
11
|
+
- `createLogger(name)` — a named logger, logging at its level of `LOG_LEVELS` (`log.levels.<name>`), otherwise at
|
|
12
|
+
`LOG_LEVEL`. Its records carry the name in their `module` field. The same name returns the same logger.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { createLogger, logger } from '@appweaver/common';
|
|
16
|
+
|
|
17
|
+
// Named after the module or feature logging with it, in camelCase
|
|
18
|
+
const log = createLogger('billing');
|
|
19
|
+
|
|
20
|
+
log.debug({ invoiceId }, 'Invoice sent');
|
|
21
|
+
log.error(err, 'Invoice failed');
|
|
22
|
+
logger.info('Logged at LOG_LEVEL, without a name');
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Prefer a named logger in a module, a service or a job, so its level can be set apart from the rest. A module package
|
|
26
|
+
logs under its short name (`@acme/appweaver-gcs` → `gcs`), and a local module under the camelCase of its name
|
|
27
|
+
(`audit-log` → `auditLog`), as the files scaffolded by `weaver module new` and `npm create @appweaver module` do.
|
|
28
|
+
|
|
29
|
+
## Trace correlation and export
|
|
30
|
+
|
|
31
|
+
With [telemetry](./telemetry.md) enabled, every record written inside an OpenTelemetry span carries its `trace_id`,
|
|
32
|
+
`span_id` and `trace_flags` (`telemetry.logCorrelation`), so the logs of a request or a job are found by its trace. The
|
|
33
|
+
`@appweaver/opentelemetry` module can also export the records over OTLP (`telemetry.logs.enabled`). Both are
|
|
34
|
+
configured in the `telemetry` section, the `log` section stays as it is.
|
|
35
|
+
|
|
36
|
+
## Levels
|
|
37
|
+
|
|
38
|
+
The framework logs at these levels:
|
|
39
|
+
|
|
40
|
+
| Level | Logged |
|
|
41
|
+
| ------- | ------------------------------------------------------------------------------------------------------- |
|
|
42
|
+
| `fatal` | The process cannot go on, i.e. an uncaught exception |
|
|
43
|
+
| `error` | A failure needing attention: a 5xx response, a failed job, a lost connection |
|
|
44
|
+
| `warn` | A degraded or unexpected state the application recovers from: a job retried, a slow query, a check down |
|
|
45
|
+
| `info` | One-time, system-wide facts only: the application started and stopped, a connection made or restored |
|
|
46
|
+
| `debug` | The internal behavior: every operation, i.e. a resource written, a job run, a login rejected, a 4xx |
|
|
47
|
+
| `trace` | Not used by the framework |
|
|
48
|
+
|
|
49
|
+
The framework never logs a request, a login or another operation at `info`. The requests are audited by the request
|
|
50
|
+
logs of the `server` logger (`SERVER_REQUEST_LOGGING_ENABLED`), and the operations are seen at `debug`.
|
|
51
|
+
|
|
52
|
+
The application is not bound by the levels of the framework and picks the level of its own logs: `info` for the core
|
|
53
|
+
behavior worth seeing in the production logs (a scheduled job publishing posts, an order paid, a worker done), `debug`
|
|
54
|
+
for the details only useful while investigating. A logger too noisy at `info` can still be quietened with its own level
|
|
55
|
+
in `LOG_LEVELS`.
|
|
56
|
+
|
|
57
|
+
## Log levels per module
|
|
58
|
+
|
|
59
|
+
`LOG_LEVELS` sets the level of a name, any other logger logs at `LOG_LEVEL`, and `silent` turns a logger off. A named
|
|
60
|
+
level overrides the default either way, so `LOG_LEVEL=silent` with `database: debug` prints the database logs only.
|
|
61
|
+
|
|
62
|
+
```jsonc
|
|
63
|
+
// appweaver.json
|
|
64
|
+
"log": {
|
|
65
|
+
"level": "info",
|
|
66
|
+
"levels": { "database": "trace", "cache": "error", "scheduler": "silent" }
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
# Each entry is its own variable, or a name:level pair of the LOG_LEVELS list
|
|
72
|
+
LOG_LEVELS_DATABASE=trace
|
|
73
|
+
LOG_LEVELS=database:trace,cache:error
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
- An entry of the environment overrides the same entry of the JSON files, and keeps the other ones.
|
|
77
|
+
- A name of `LOG_LEVELS` no logger uses (a typo, or a disabled module) is reported with a warning when the application
|
|
78
|
+
is created.
|
|
79
|
+
- The `appweaver.schema.json` of `weaver generate` suggests the logger names the enabled modules list in the
|
|
80
|
+
`loggers` of their manifests (the framework loggers below, and those of the module packages and local modules),
|
|
81
|
+
and still accepts any other name, i.e. a logger of the application.
|
|
82
|
+
- The levels are read when the loggers are created, at startup, so a change needs a restart.
|
|
83
|
+
- The `weaver` CLI commands log nothing, whatever the levels.
|
|
84
|
+
|
|
85
|
+
### Framework loggers
|
|
86
|
+
|
|
87
|
+
| Name | Logs of |
|
|
88
|
+
| ----------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
|
89
|
+
| `app` | The started application and its duration (info), the enabled modules, providers, app files and lifecycle hook durations |
|
|
90
|
+
| `database` | The connection (info), slow queries (warn), Prisma events, transaction retries and rollbacks |
|
|
91
|
+
| `resource` | Resources created, updated and deleted, bulk operations, denied policies, the loaded models, services and routes, CSV export |
|
|
92
|
+
| `server` | Fastify and its request logs, 5xx (error) and 4xx (debug) responses, rate limit hits, plugins, routes and shutdown |
|
|
93
|
+
| `security` | Logins and their rejection reason, rejected API keys, password, email, phone and 2FA flows, OAuth2, reCAPTCHA and Turnstile |
|
|
94
|
+
| `cache` | Cache hits and misses, writes, invalidation, eviction, and the cache going away and coming back |
|
|
95
|
+
| `memory` | The Redis connections: established and restored (info), lost (error) |
|
|
96
|
+
| `events` | The listeners added and the events emitted, or deferred to the commit of a transaction |
|
|
97
|
+
| `queue` | Jobs added and completed with their duration, retried (warn), failed (error) and stalled (warn) |
|
|
98
|
+
| `scheduler` | Jobs added with their next run, started, stopped and removed, each run with its duration |
|
|
99
|
+
| `mailer` | E-mails queued and sent, the SMTP message id, and the e-mails of the `json` mailer |
|
|
100
|
+
| `sms` | Text messages sent, the message id of Twilio, and the messages of the `json` SMS sender |
|
|
101
|
+
| `payments` | Gateways connected, plans read, payment emails queued, payments and webhook events that failed or were not reconciled |
|
|
102
|
+
| `template` | The loaded templates and the template preview route |
|
|
103
|
+
| `locale` | The loaded translations and the missing keys |
|
|
104
|
+
| `storage` | `FileService`, the `local` storage driver and the processed images |
|
|
105
|
+
| `health` | Each check going down (warn) and up again (info), once per change, and the health listener |
|
|
106
|
+
| `audit` | Audit log entries failing to be written (error), dropped while the buffer is full (warn), and the expired ones deleted |
|
|
107
|
+
|
|
108
|
+
### Database queries
|
|
109
|
+
|
|
110
|
+
`DATABASE_LOG_EVENTS` selects the events Prisma emits, so the queries need both the event and the level:
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
DATABASE_LOG_EVENTS=query,warn,error
|
|
114
|
+
LOG_LEVELS_DATABASE=debug
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`DATABASE_SLOW_QUERY_THRESHOLD` logs every query taking at least that many milliseconds as a warning, with its SQL but
|
|
118
|
+
without its parameters, whatever `DATABASE_LOG_EVENTS` holds. It is `0` by default, which disables it:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
DATABASE_SLOW_QUERY_THRESHOLD=3000
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Request logs
|
|
125
|
+
|
|
126
|
+
The request logs of Fastify are written by the `server` logger when `SERVER_REQUEST_LOGGING_ENABLED` is `true`, so
|
|
127
|
+
`LOG_LEVELS_SERVER=warn` keeps the errors of the server without them.
|
|
128
|
+
|
|
129
|
+
## Redacted values
|
|
130
|
+
|
|
131
|
+
The values of the keys `password`, `passwordHash`, `token`, `accessToken`, `refreshToken`, `apiKey` and `secret`, at the
|
|
132
|
+
top of a record or one level down, and the `authorization`, `cookie` and `x-api-key` headers of a request, are written
|
|
133
|
+
as `[Redacted]`. Still never log a credential under another key.
|
|
134
|
+
|
|
135
|
+
## Output
|
|
136
|
+
|
|
137
|
+
| Key | Effect |
|
|
138
|
+
| -------------- | ----------------------------------------------------------------------------------------- |
|
|
139
|
+
| `LOG_PRETTY` | Colored, human-readable lines (`[database] Prisma query`), for development |
|
|
140
|
+
| `LOG_STREAM` | `stderr` writes the console logs there instead of stdout (`weaver run` does for a task) |
|
|
141
|
+
| `LOG_PATH` | Also writes to `<LOG_PATH>/<app name>.log` (`APP_NAME` in snake case), rotated by default |
|
|
142
|
+
| `LOG_ROTATE_*` | The rotation of the file: its size, interval, total size, number of files and compression |
|
|
143
|
+
| `LOG_SYNC` | Writes each record before the next statement runs, so none is lost or reordered (tests) |
|
|
144
|
+
|
|
145
|
+
The samples and the scaffolded projects pretty-print at `debug` in the `dev` environment, and log nothing in `test`.
|
|
146
|
+
|
|
147
|
+
## Testing
|
|
148
|
+
|
|
149
|
+
Spy on the logger the code under test logs with, the named one when it uses `createLogger`:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
import { createLogger } from '@appweaver/common';
|
|
153
|
+
|
|
154
|
+
const error = jest.spyOn(createLogger('billing'), 'error').mockImplementation();
|
|
155
|
+
// ...
|
|
156
|
+
expect(error).toHaveBeenCalledWith(expect.any(Error), 'Invoice failed');
|
|
157
|
+
```
|