create-wervt 0.1.0 → 0.2.1

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,340 @@
1
+ # Wide Events Guide
2
+
3
+ Wide events are comprehensive log entries that capture all context for a single logical operation (usually a request) in one place.
4
+
5
+ ## Why Wide Events?
6
+
7
+ Traditional logging scatters information across many log lines:
8
+
9
+ ```
10
+ 10:23:45.001 Request received POST /checkout
11
+ 10:23:45.012 User authenticated: user_123
12
+ 10:23:45.045 Cart loaded: 3 items, $99.99
13
+ 10:23:45.089 Payment initiated: Stripe
14
+ 10:23:45.234 Payment failed: card_declined
15
+ 10:23:45.235 Request completed: 500
16
+ ```
17
+
18
+ During an incident, you're grep-ing through thousands of these trying to reconstruct what happened.
19
+
20
+ **Wide events emit once with everything:**
21
+
22
+ Development (pretty format):
23
+
24
+ ```
25
+ 10:23:45.235 ERROR [api] POST /checkout 500 in 234ms
26
+ ├─ user: id=user_123 plan=premium accountAge=847
27
+ ├─ cart: items=3 total=9999
28
+ ├─ payment: provider=stripe method=card
29
+ └─ error: code=card_declined retriable=false
30
+ ```
31
+
32
+ Production (JSON format):
33
+
34
+ ```json
35
+ {
36
+ "timestamp": "2025-01-24T10:23:45.235Z",
37
+ "level": "error",
38
+ "service": "api",
39
+ "method": "POST",
40
+ "path": "/checkout",
41
+ "duration": "234ms",
42
+ "user": { "id": "user_123", "plan": "premium", "accountAge": 847 },
43
+ "cart": { "items": 3, "total": 9999 },
44
+ "payment": { "provider": "stripe", "method": "card" },
45
+ "error": { "code": "card_declined", "retriable": false }
46
+ }
47
+ ```
48
+
49
+ ## When to Use Wide Events
50
+
51
+ | Scenario | Use Wide Event? |
52
+ | ----------------------------- | --------------------------------- |
53
+ | HTTP request handling | Yes - one event per request |
54
+ | Background job execution | Yes - one event per job |
55
+ | Database query | No - use simple log |
56
+ | Cache hit/miss | No - include in parent wide event |
57
+ | User action (login, checkout) | Yes - one event per action |
58
+ | Debug statements | No - remove in production |
59
+
60
+ ## Required Fields
61
+
62
+ Every wide event should include:
63
+
64
+ ### Request Context
65
+
66
+ ```typescript
67
+ log.set({
68
+ method: 'POST',
69
+ path: '/api/checkout',
70
+ requestId: 'req_abc123', // For tracing
71
+ traceId: 'trace_xyz', // Distributed tracing
72
+ })
73
+ ```
74
+
75
+ ### User Context
76
+
77
+ ```typescript
78
+ log.set({
79
+ user: {
80
+ id: 'user_123',
81
+ plan: 'premium', // Business-relevant
82
+ accountAge: 847, // Days since signup
83
+ subscription: 'annual',
84
+ },
85
+ })
86
+ ```
87
+
88
+ ### Business Context
89
+
90
+ Add domain-specific data relevant to the operation:
91
+
92
+ ```typescript
93
+ // E-commerce checkout
94
+ log.set({
95
+ cart: { id: 'cart_xyz', items: 3, total: 9999 },
96
+ payment: { method: 'card', provider: 'stripe' },
97
+ order: { id: 'order_123', status: 'created' },
98
+ })
99
+
100
+ // API rate limiting
101
+ log.set({
102
+ rateLimit: {
103
+ limit: 1000,
104
+ remaining: 42,
105
+ resetAt: '2025-01-24T11:00:00Z',
106
+ },
107
+ })
108
+
109
+ // File upload
110
+ log.set({
111
+ upload: {
112
+ filename: 'document.pdf',
113
+ size: 1024000,
114
+ mimeType: 'application/pdf',
115
+ },
116
+ })
117
+ ```
118
+
119
+ ### Outcome
120
+
121
+ ```typescript
122
+ // Success
123
+ log.set({
124
+ status: 200,
125
+ // duration is added automatically by emit()
126
+ })
127
+
128
+ // Error
129
+ log.error(error, {
130
+ step: 'payment',
131
+ retriable: false,
132
+ })
133
+ ```
134
+
135
+ ## Pattern: Request Logger in API Routes
136
+
137
+ ### Nuxt/Nitro (Recommended)
138
+
139
+ With the evlog module, use `useLogger(event)` - it's auto-created and auto-emitted:
140
+
141
+ ```typescript
142
+ // server/api/checkout.post.ts
143
+ // Nuxt: useLogger is auto-imported, createError is not
144
+ // Nitro v3: import { useLogger } from 'evlog/nitro/v3'
145
+ // Nitro v2: import { useLogger } from 'evlog/nitro'
146
+ import { createError } from 'evlog'
147
+
148
+ export default defineEventHandler(async (event) => {
149
+ const log = useLogger(event) // Auto-created by evlog
150
+
151
+ const user = await requireAuth(event)
152
+ log.set({ user: { id: user.id, plan: user.plan } })
153
+
154
+ const cart = await getCart(user.id)
155
+ log.set({ cart: { items: cart.items.length, total: cart.total } })
156
+
157
+ try {
158
+ const payment = await processPayment(cart, user)
159
+ log.set({ payment: { id: payment.id, method: payment.method } })
160
+ } catch (error) {
161
+ log.error(error, { step: 'payment' })
162
+ throw createError({
163
+ message: 'Payment failed',
164
+ why: error.message,
165
+ fix: 'Try a different payment method',
166
+ })
167
+ }
168
+
169
+ const order = await createOrder(cart, user)
170
+ log.set({ order: { id: order.id, status: order.status } })
171
+
172
+ return order
173
+ // log.emit() is called automatically at request end
174
+ })
175
+ ```
176
+
177
+ ### Standalone TypeScript (Scripts, Workers)
178
+
179
+ Without Nuxt/Nitro, use `createRequestLogger()` and call `emit()` manually:
180
+
181
+ ```typescript
182
+ // scripts/sync-job.ts
183
+ import { initLogger, createRequestLogger } from 'evlog'
184
+
185
+ initLogger({ env: { service: 'sync-worker', environment: 'production' } })
186
+
187
+ async function processJob(job: Job) {
188
+ const log = createRequestLogger({ jobId: job.id, type: 'sync' })
189
+
190
+ try {
191
+ log.set({ source: job.source, target: job.target })
192
+
193
+ const result = await performSync(job)
194
+ log.set({ recordsSynced: result.count })
195
+
196
+ return result
197
+ } catch (error) {
198
+ log.error(error, { step: 'sync' })
199
+ throw error
200
+ } finally {
201
+ log.emit() // Manual emit required
202
+ }
203
+ }
204
+ ```
205
+
206
+ ## Transformation Examples
207
+
208
+ ### Before: Console.log Spam
209
+
210
+ ```typescript
211
+ // server/api/checkout.post.ts
212
+
213
+ export default defineEventHandler(async (event) => {
214
+ console.log('Checkout started')
215
+
216
+ const user = await getUser(event)
217
+ console.log('User loaded:', user.id)
218
+
219
+ const cart = await getCart(user.id)
220
+ console.log('Cart loaded:', cart.items.length, 'items')
221
+
222
+ try {
223
+ const payment = await processPayment(cart)
224
+ console.log('Payment successful:', payment.id)
225
+ return { orderId: payment.orderId }
226
+ } catch (error) {
227
+ console.error('Payment failed:', error.message)
228
+ throw error
229
+ }
230
+ })
231
+ ```
232
+
233
+ ### After: Single Wide Event
234
+
235
+ ```typescript
236
+ // server/api/checkout.post.ts
237
+ // Nuxt: useLogger is auto-imported, createError is not
238
+ // Nitro v3: import { useLogger } from 'evlog/nitro/v3'
239
+ // Nitro v2: import { useLogger } from 'evlog/nitro'
240
+ import { createError } from 'evlog'
241
+
242
+ export default defineEventHandler(async (event) => {
243
+ const log = useLogger(event)
244
+
245
+ const user = await getUser(event)
246
+ log.set({ user: { id: user.id, plan: user.plan } })
247
+
248
+ const cart = await getCart(user.id)
249
+ log.set({ cart: { items: cart.items.length, total: cart.total } })
250
+
251
+ try {
252
+ const payment = await processPayment(cart)
253
+ log.set({ payment: { id: payment.id }, order: { id: payment.orderId } })
254
+
255
+ return { orderId: payment.orderId }
256
+ } catch (error) {
257
+ log.error(error, { step: 'payment' })
258
+ throw createError({
259
+ message: 'Payment failed',
260
+ why: error.message,
261
+ fix: 'Try a different payment method',
262
+ })
263
+ }
264
+ // emit() called automatically
265
+ })
266
+ ```
267
+
268
+ ## Best Practices
269
+
270
+ ### Do
271
+
272
+ - Include business-relevant context (user plan, cart value, etc.)
273
+ - Add enough context to debug without looking elsewhere
274
+ - Use consistent field names across your codebase
275
+ - Let `emit()` calculate duration automatically
276
+
277
+ ### Don't
278
+
279
+ - Log sensitive data (passwords, tokens, full credit card numbers)
280
+ - Create multiple wide events for one logical operation
281
+ - Forget to call `emit()` (or use the Nuxt module for auto-emit)
282
+ - Include debugging logs inside wide events (remove them)
283
+
284
+ ## Security: Preventing Sensitive Data Leakage
285
+
286
+ Always explicitly select which fields to log:
287
+
288
+ ```typescript
289
+ // ❌ DANGEROUS - logs everything including password
290
+ log.set({ user: body })
291
+
292
+ // ✅ SAFE - explicitly select fields
293
+ log.set({
294
+ user: {
295
+ id: body.id,
296
+ email: maskEmail(body.email),
297
+ // password: body.password ← NEVER include
298
+ },
299
+ })
300
+ ```
301
+
302
+ **Never log:** passwords, API keys, tokens, secrets, full card numbers, CVV, SSN, PII, session tokens, JWTs.
303
+
304
+ **Sanitization helpers:**
305
+
306
+ ```typescript
307
+ // server/utils/sanitize.ts
308
+ export function maskEmail(email: string): string {
309
+ const [local, domain] = email.split('@')
310
+ if (!domain) return '***'
311
+ return `${local[0]}***@${domain[0]}***.${domain.split('.')[1]}`
312
+ }
313
+
314
+ export function maskCard(card: string): string {
315
+ return `****${card.slice(-4)}`
316
+ }
317
+ ```
318
+
319
+ See [code-review.md](code-review.md) for the full security review checklist.
320
+
321
+ ## Field Naming Conventions
322
+
323
+ Use consistent, descriptive field names:
324
+
325
+ ```typescript
326
+ // ✅ Good - grouped, descriptive
327
+ log.set({
328
+ user: { id, plan, accountAge },
329
+ cart: { items, total },
330
+ payment: { method, provider },
331
+ })
332
+
333
+ // ❌ Bad - flat, abbreviated
334
+ log.set({
335
+ uid: '123',
336
+ n: 3,
337
+ t: 9999,
338
+ pm: 'card',
339
+ })
340
+ ```
@@ -0,0 +1,77 @@
1
+ ---
2
+ name: wervt-logs
3
+ description: Read this app's production logs on wervt with `wervt logs` to debug errors, failed or slow requests, crashes, releases that don't start and isolates hitting CPU or memory limits. Use when a bug report, an error or "it's broken in production" needs evidence from the running app. Covers LogsQL queries, the fields wervt and evlog log, and how to narrow down from an error to its request.
4
+ ---
5
+
6
+ # Production logs on wervt
7
+
8
+ The app's logs live on wervt for 14 days: every request as one wide event (evlog), console output,
9
+ and what the runtime saw (boots, boot failures, uncaught exceptions, shutdowns). Read them with the
10
+ `wervt` CLI. Never guess at production behavior when the logs can tell.
11
+
12
+ ## Access
13
+
14
+ `wervt logs` uses `WERVT_URL` and `WERVT_TOKEN` (or the saved `wervt login`). The **read token** is
15
+ enough and is what agents should have; it can't deploy or change anything. If the command fails with
16
+ "Not logged in", ask the user for the URL and a read token rather than looking for credentials.
17
+
18
+ ```bash
19
+ pnpm exec wervt logs <app> # last hour, oldest first
20
+ pnpm exec wervt logs <app> 'level:error' --since 1d --json # every field, one JSON object per line
21
+ pnpm exec wervt logs <app> 'status:>=500' --since 6h --limit 50 --json
22
+ pnpm exec wervt logs <app> -f # follow while reproducing
23
+ ```
24
+
25
+ The app name is the `name` in package.json. Prefer `--json` and a narrow query: the output goes into
26
+ your context, so ask for what you need (`--limit`, `--since`, filters) instead of everything.
27
+
28
+ ## Fields
29
+
30
+ | Field | From | |
31
+ | ---------------------------------------------- | ------- | ------------------------------------------------------------- |
32
+ | `_time`, `_msg` | wervt | Time and the line (`GET /api/x 500` for requests) |
33
+ | `level` | wervt | `error`, `warn`, `info`, `debug`. 4xx requests are `warn` |
34
+ | `type` | wervt | `log`, `Boot`, `BootFailure`, `UncaughtException`, `Shutdown` |
35
+ | `release` | wervt | Which deploy wrote it |
36
+ | `execution_id` | wervt | One isolate's lifetime (boot to shutdown) |
37
+ | `reason` | wervt | Shutdowns: `CPUTime`, `Memory` (killed) or idle ones |
38
+ | `method`, `path`, `status` | evlog | The request |
39
+ | `duration`, `requestId` | evlog | Timing and the id to correlate with |
40
+ | `error.message`, `error.stack`, `error.status` | evlog | Why it failed |
41
+ | anything else | the app | Set with `useLogger(event).set({...})`, e.g. `user.id` |
42
+
43
+ ## Queries (LogsQL)
44
+
45
+ | Query | Finds |
46
+ | ------------------------------------------- | ----------------------------------------- |
47
+ | `level:error` | errors, uncaught exceptions, failed boots |
48
+ | `status:>=500` | requests that failed on the server |
49
+ | `path:/api/rooms` | requests to a path; `path:/api/*` prefix |
50
+ | `requestId:=<id>` | everything about one request |
51
+ | `type:=BootFailure` | a release that doesn't start |
52
+ | `type:=Shutdown reason:in(CPUTime, Memory)` | isolates killed by a limit |
53
+ | `duration:>1000ms` or `durationMs:>1000` | slow requests |
54
+ | `release:=<id>` | one deploy only |
55
+ | `timeout` | any entry containing the word |
56
+
57
+ Combine with spaces (AND), `OR`, `-` / `NOT`, and parentheses. Reference:
58
+ https://docs.victoriametrics.com/victorialogs/logsql/
59
+
60
+ ## Debugging flow
61
+
62
+ 1. Start broad and recent: `'level:error' --since 1d --json --limit 20`. Note `release` and
63
+ `_time` of the first occurrence: did it start with a deploy (`pnpm exec wervt releases <app>`)?
64
+ 2. Narrow to the failing route (`path:`), then to one request (`requestId:=`), and read
65
+ `error.stack`. Stack lines point into the built server, so map them back to the source by the
66
+ function names and the route.
67
+ 3. `UncaughtException` or `Shutdown` with `reason` `CPUTime` / `Memory`: work outside a request's
68
+ await chain, an endless loop or a large in-memory result. Look at what that route does.
69
+ 4. `BootFailure`: the release can't start at all, often an import Deno can't resolve. Fixing it needs a
70
+ new deploy; `wervt rollback <app>` gets the previous release back meanwhile (ask first).
71
+ 5. Missing context to explain a failure? Add it to the wide event with `useLogger(event).set()`
72
+ (see the review-logging-patterns skill), deploy, and query again.
73
+
74
+ ## Care
75
+
76
+ Logs can contain user data (ids, paths, messages). Quote only what's needed to explain the bug, and
77
+ never paste tokens or personal data into code, commits or issues.
@@ -110,6 +110,28 @@ const { data: todos, isLive } = await useShape<Todo>('/api/shapes/todos')
110
110
  requests.
111
111
  - No secrets in client code. Server env vars come from wervt; don't hardcode credentials.
112
112
 
113
+ ## Logs
114
+
115
+ Every request logs one wide event (evlog). Add context to it rather than logging separate lines:
116
+ `useLogger(event).set({ user: { id }, room: { id } })`, with `useLogger` and `log` imported from
117
+ `@wervt/nuxt/server`. Use `log.info(tag, msg)` outside requests. Never log secrets or request
118
+ bodies.
119
+
120
+ evlog is already set up by `@wervt/nuxt` and wervt collects its output. Don't add `evlog/nuxt` to
121
+ `modules`, don't run `evlog init` and don't configure drains (Axiom, OTLP, files, …), even when the
122
+ review-logging-patterns skill suggests it. Its patterns for wide events and errors apply as is.
123
+ Skills: `review-logging-patterns` (writing logging code), `wervt-logs` (reading production logs).
124
+
125
+ Production logs, to debug a bug report (`WERVT_TOKEN` can be the read token):
126
+
127
+ ```bash
128
+ pnpm exec wervt logs <app> 'level:error' --since 1d --json
129
+ pnpm exec wervt logs <app> 'status:>=500 path:/api/*' --json
130
+ pnpm exec wervt logs <app> 'type:=BootFailure' # a release that didn't start
131
+ ```
132
+
133
+ Queries are LogsQL. Logs may contain user data: quote only what's needed.
134
+
113
135
  ## Commands
114
136
 
115
137
  - `pnpm dev`: dev server against the local wervt stack (`docker compose up -d` in the wervt repo).
@@ -9,7 +9,7 @@
9
9
  "postinstall": "nuxt prepare"
10
10
  },
11
11
  "dependencies": {
12
- "@wervt/nuxt": "^0.1.0",
12
+ "@wervt/nuxt": "^0.2.1",
13
13
  "drizzle-orm": "1.0.0-rc.4",
14
14
  "nuxt": "npm:nuxt-nightly@5x",
15
15
  "valibot": "^1.5.0"