@roko-app/instant-webhooks 0.0.0-stage → 1.0.67-roko.2
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/.tshy/build.json +8 -0
- package/.tshy/commonjs.json +16 -0
- package/.tshy/esm.json +15 -0
- package/.turbo/turbo-build.log +38 -0
- package/LICENSE +202 -0
- package/README.md +400 -2
- package/__tests__/src/helpers.test.ts +134 -0
- package/__tests__/src/processPayload.test.ts +153 -0
- package/__tests__/src/validate.test.ts +98 -0
- package/dist/commonjs/__types__/typeUtils.d.ts +12 -0
- package/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
- package/dist/commonjs/__types__/typeUtils.js +5 -0
- package/dist/commonjs/__types__/typeUtils.js.map +1 -0
- package/dist/commonjs/__types__/typesTests.d.ts +2 -0
- package/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
- package/dist/commonjs/__types__/typesTests.js +79 -0
- package/dist/commonjs/__types__/typesTests.js.map +1 -0
- package/dist/commonjs/index.d.ts +588 -0
- package/dist/commonjs/index.d.ts.map +1 -0
- package/dist/commonjs/index.js +754 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/package.json +3 -0
- package/dist/esm/__types__/typeUtils.d.ts +12 -0
- package/dist/esm/__types__/typeUtils.d.ts.map +1 -0
- package/dist/esm/__types__/typeUtils.js +4 -0
- package/dist/esm/__types__/typeUtils.js.map +1 -0
- package/dist/esm/__types__/typesTests.d.ts +2 -0
- package/dist/esm/__types__/typesTests.d.ts.map +1 -0
- package/dist/esm/__types__/typesTests.js +77 -0
- package/dist/esm/__types__/typesTests.js.map +1 -0
- package/dist/esm/index.d.ts +588 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +749 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/package.json +38 -3
- package/src/__types__/typeUtils.ts +21 -0
- package/src/__types__/typesTests.ts +188 -0
- package/src/index.ts +1308 -0
- package/tsconfig.dev.json +14 -0
- package/tsconfig.json +11 -0
- package/tsconfig.test.json +5 -0
package/README.md
CHANGED
|
@@ -1,3 +1,401 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://instantdb.com">
|
|
3
|
+
<img alt="Shows the Instant logo" src="https://instantdb.com/img/icon/android-chrome-512x512.png" width="10%">
|
|
4
|
+
</a>
|
|
5
|
+
<h1 align="center">@instantdb/webhooks</h1>
|
|
6
|
+
</p>
|
|
2
7
|
|
|
3
|
-
|
|
8
|
+
<p align="center">
|
|
9
|
+
<a
|
|
10
|
+
href="https://discord.com/invite/VU53p7uQcE" >
|
|
11
|
+
<img height=20 src="https://img.shields.io/discord/1031957483243188235" alt="Discord members" />
|
|
12
|
+
</a>
|
|
13
|
+
<img src="https://img.shields.io/github/stars/instantdb/instant" alt="stars">
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
<p align="center">
|
|
17
|
+
<a href="https://www.instantdb.com/docs/webhooks">Get Started</a> ·
|
|
18
|
+
<a href="https://instantdb.com/examples">Examples</a> ·
|
|
19
|
+
<a href="https://www.instantdb.com/docs/webhooks">Docs</a> ·
|
|
20
|
+
<a href="https://discord.com/invite/VU53p7uQcE">Discord</a>
|
|
21
|
+
</p>
|
|
22
|
+
|
|
23
|
+
Welcome to [Instant's](http://instantdb.com) webhooks library.
|
|
24
|
+
|
|
25
|
+
This package gives you the building blocks for working with Instant webhooks: verifying incoming requests, dispatching records to typed handlers, and managing webhook subscriptions and their delivery history.
|
|
26
|
+
|
|
27
|
+
# Where to use this
|
|
28
|
+
|
|
29
|
+
The `Webhooks` class is re-exported from a few places. Use whichever fits your setup:
|
|
30
|
+
|
|
31
|
+
- **From `@instantdb/admin`** — most apps. `db.webhooks` is wired up for you. An admin token is only required if you also want to manage webhooks (`db.webhooks.manager.*`); the receiving side (`processRequest` / `validate`) works without one.
|
|
32
|
+
- **From `@instantdb/platform`** — building on top of Instant on behalf of other users. `api.webhooks(appId)` returns a `Webhooks` instance, and the platform SDK transparently refreshes the OAuth token for manager calls. Auth is only required if you'll use `manager.*`.
|
|
33
|
+
- **Standalone from `@instantdb/webhooks`** — useful if you don't want to pull in the rest of the admin SDK. Again, no admin token is needed unless you'll call `manager.*`.
|
|
34
|
+
|
|
35
|
+
## From the admin SDK
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { init } from '@instantdb/admin';
|
|
39
|
+
import schema from './instant.schema';
|
|
40
|
+
|
|
41
|
+
// adminToken is optional if you're only using the SDK for the receiving side
|
|
42
|
+
// of webhooks (processRequest / validate / etc.). Include it if you also want
|
|
43
|
+
// to use db.webhooks.manager.* — or any other admin-SDK feature that requires
|
|
44
|
+
// auth, like writes or impersonation.
|
|
45
|
+
const db = init({
|
|
46
|
+
appId: process.env.INSTANT_APP_ID!,
|
|
47
|
+
schema,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// db.webhooks is a Webhooks<typeof schema> instance.
|
|
51
|
+
await db.webhooks.processRequest(handlers, req);
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## From the platform SDK
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { PlatformApi } from '@instantdb/platform';
|
|
58
|
+
import schema from './instant.schema';
|
|
59
|
+
|
|
60
|
+
// Auth is optional if you're only using PlatformApi for the receiving side of
|
|
61
|
+
// webhooks. Include it if you also want to use webhooks.manager.* (or any
|
|
62
|
+
// other platform-SDK feature). When provided, the platform SDK refreshes the
|
|
63
|
+
// OAuth token transparently for manager calls.
|
|
64
|
+
const api = new PlatformApi({ auth: { token: accessToken } });
|
|
65
|
+
|
|
66
|
+
const webhooks = api.webhooks(appId, { schema });
|
|
67
|
+
|
|
68
|
+
await webhooks.processRequest(handlers, req);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Standalone
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { Webhooks } from '@instantdb/webhooks';
|
|
75
|
+
import schema from './instant.schema';
|
|
76
|
+
|
|
77
|
+
// For receiving only (validate / processRequest / processPayload), the
|
|
78
|
+
// adminToken is optional — you just need appId + schema for typed handlers.
|
|
79
|
+
const webhooks = new Webhooks<typeof schema>({
|
|
80
|
+
appId: process.env.INSTANT_APP_ID!,
|
|
81
|
+
schema,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// To also manage webhooks (manager.create, manager.list, …) pass adminToken.
|
|
85
|
+
const webhooksWithManager = new Webhooks<typeof schema>({
|
|
86
|
+
appId: process.env.INSTANT_APP_ID!,
|
|
87
|
+
adminToken: process.env.INSTANT_APP_ADMIN_TOKEN!,
|
|
88
|
+
schema,
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`new Webhooks(config)` accepts:
|
|
93
|
+
|
|
94
|
+
- `appId` — required for `manager.*`; recommended for the receiving side so error messages and helpers are scoped.
|
|
95
|
+
- `adminToken` (or `token`) — required for `manager.*`. Not needed to verify signatures or dispatch handlers.
|
|
96
|
+
- `schema` — optional. Pass your schema to get fully typed `record.before` / `record.after` in handlers and typed `namespaces` on `manager.create` / `manager.update`.
|
|
97
|
+
- `apiURI` — defaults to `https://api.instantdb.com`. Override for self-hosted or local development.
|
|
98
|
+
- `withAuth` — advanced hook used by the platform SDK to inject a fresh OAuth token per request; you generally won't pass this directly.
|
|
99
|
+
|
|
100
|
+
The rest of this README uses `db.webhooks` in examples. The same methods exist on a standalone `Webhooks` instance or on `api.webhooks(appId)`.
|
|
101
|
+
|
|
102
|
+
# Receiving webhooks
|
|
103
|
+
|
|
104
|
+
## `processRequest(handlers, req, opts?)`
|
|
105
|
+
|
|
106
|
+
The one-liner for handling an incoming webhook. It:
|
|
107
|
+
|
|
108
|
+
1. Verifies the `Instant-Signature` header against the raw body.
|
|
109
|
+
2. Fetches the records via the short-lived `payloadUrl` + JWT in the body.
|
|
110
|
+
3. Dispatches each record to the matching handler.
|
|
111
|
+
|
|
112
|
+
Pass it a Web [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) (Next.js App Router, Cloudflare Workers, Deno, Bun, Hono, etc.):
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
// app/api/instant-webhook/route.ts
|
|
116
|
+
import { init } from '@instantdb/admin';
|
|
117
|
+
import schema from '@/instant.schema';
|
|
118
|
+
|
|
119
|
+
const db = init({
|
|
120
|
+
appId: process.env.INSTANT_APP_ID!,
|
|
121
|
+
schema,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const { typedHandlers, combineHandlers } = db.webhooks.helpers();
|
|
125
|
+
|
|
126
|
+
const handlers = combineHandlers(
|
|
127
|
+
typedHandlers('posts', 'create', async (record) => {
|
|
128
|
+
await sendNewPostEmail(record.after);
|
|
129
|
+
}),
|
|
130
|
+
typedHandlers('posts', 'update', (record) => {
|
|
131
|
+
console.log('post %s changed', record.id, record.before, record.after);
|
|
132
|
+
}),
|
|
133
|
+
typedHandlers('$default', (record) => {
|
|
134
|
+
console.log('unhandled record', record);
|
|
135
|
+
}),
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
export async function POST(req: Request) {
|
|
139
|
+
await db.webhooks.processRequest(handlers, req);
|
|
140
|
+
return new Response('ok');
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Options:
|
|
145
|
+
|
|
146
|
+
- `tolerance` — max signature age in seconds (default `300`). Protects against replays; raising this weakens that.
|
|
147
|
+
- `receivedAt` — override the "now" used when checking signature age. Mostly useful in tests.
|
|
148
|
+
|
|
149
|
+
Handler resolution is most-specific-wins: `namespace` + `action` → that namespace's `$default` → top-level `$default`. Records with no matching handler are skipped.
|
|
150
|
+
|
|
151
|
+
Handlers run concurrently. `processRequest` resolves once all of them settle. If any handler rejects, the call rejects — return a non-2xx response so Instant retries the event.
|
|
152
|
+
|
|
153
|
+
## `processNodeRequest(handlers, req, opts?)`
|
|
154
|
+
|
|
155
|
+
Adapter for frameworks that hand you a Node-style `IncomingMessage` instead of a Web `Request` — Next.js Pages Router, Express, Koa, NestJS, Fastify, etc. The raw bytes of the body are required to verify the signature, so **don't put a JSON body parser in front of this route** (`express.json()`, Next's default `bodyParser`, etc.).
|
|
156
|
+
|
|
157
|
+
The adapter picks up the raw body from, in order: `opts.body`, `req.rawBody`, `req.body` (if it's a `Buffer`/`Uint8Array`/string), then the unconsumed request stream.
|
|
158
|
+
|
|
159
|
+
Next.js Pages Router:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
// pages/api/instant-webhook.ts
|
|
163
|
+
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
164
|
+
|
|
165
|
+
export const config = { api: { bodyParser: false } };
|
|
166
|
+
|
|
167
|
+
export default async function handler(
|
|
168
|
+
req: NextApiRequest,
|
|
169
|
+
res: NextApiResponse,
|
|
170
|
+
) {
|
|
171
|
+
try {
|
|
172
|
+
await db.webhooks.processNodeRequest(handlers, req);
|
|
173
|
+
res.status(200).end();
|
|
174
|
+
} catch (e) {
|
|
175
|
+
res.status(400).json({ error: String(e) });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Express (use `express.raw` on the webhook route only):
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
app.post(
|
|
184
|
+
'/webhooks/instant',
|
|
185
|
+
express.raw({ type: 'application/json' }),
|
|
186
|
+
async (req, res) => {
|
|
187
|
+
try {
|
|
188
|
+
await db.webhooks.processNodeRequest(handlers, req);
|
|
189
|
+
res.status(200).end();
|
|
190
|
+
} catch (e) {
|
|
191
|
+
res.status(400).json({ error: String(e) });
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
);
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Koa with `raw-body`:
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
router.post('/webhooks/instant', async (ctx) => {
|
|
201
|
+
await db.webhooks.processNodeRequest(handlers, ctx.req, {
|
|
202
|
+
body: rawBody(ctx.req), // adapter awaits the Promise
|
|
203
|
+
});
|
|
204
|
+
ctx.status = 200;
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
NestJS (Express adapter, with `NestFactory.create(AppModule, { rawBody: true })`):
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
@Controller('webhooks')
|
|
212
|
+
export class WebhooksController {
|
|
213
|
+
@Post('instant')
|
|
214
|
+
@HttpCode(200)
|
|
215
|
+
async handle(@Req() req: Request) {
|
|
216
|
+
await db.webhooks.processNodeRequest(handlers, req);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
If the adapter detects that an upstream parser turned the body into an object, it re-serializes it and tries anyway — but if the bytes don't match what Instant signed, you'll get a targeted error telling you to switch the route off the JSON parser.
|
|
222
|
+
|
|
223
|
+
## `processPayload(handlers, payload)`
|
|
224
|
+
|
|
225
|
+
Dispatches a payload you've already fetched. Useful when you'd rather do signature verification yourself (or when you're replaying an event from `manager.getPayload`).
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
const body = await db.webhooks.validate(signatureHeader, rawBody);
|
|
229
|
+
const payload = await db.webhooks.fetchPayloads(body);
|
|
230
|
+
await db.webhooks.processPayload(handlers, payload);
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Same resolution rules and concurrency model as `processRequest`: handlers run in parallel, and if any of them rejects the call rejects too — return a non-2xx response so Instant retries the event. If you'd rather have a per-handler failure not fail the whole batch, wrap that handler's body in `try`/`catch`.
|
|
234
|
+
|
|
235
|
+
## `validate(signatureHeader, body, opts?)`
|
|
236
|
+
|
|
237
|
+
Parses an `Instant-Signature` header, verifies it against the body, and returns the `{ payloadUrl, token }` you'd use to fetch the records. Throws if the signature doesn't validate, is older than `opts.tolerance` (default 300 seconds), or the body isn't the expected shape.
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
const { payloadUrl, token } = await db.webhooks.validate(
|
|
241
|
+
signatureHeader,
|
|
242
|
+
rawBody,
|
|
243
|
+
{ tolerance: 300 },
|
|
244
|
+
);
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
`body` can be a string or a function returning a `Promise<string>` — pass the function form to defer reading the request stream until after the header has been parsed.
|
|
248
|
+
|
|
249
|
+
## `validateRequest(req, opts?)`
|
|
250
|
+
|
|
251
|
+
Convenience wrapper around `validate`: pulls `instant-signature` and the body off a Web `Request` for you.
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
const { payloadUrl, token } = await db.webhooks.validateRequest(req);
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
## `fetchPayloads({ payloadUrl, token })`
|
|
258
|
+
|
|
259
|
+
Exchanges the `{ payloadUrl, token }` from a validated body for the full payload of records. Returns a `WebhookPayload<Schema>`.
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
const payload = await db.webhooks.fetchPayloads({ payloadUrl, token });
|
|
263
|
+
console.log(payload.idempotencyKey, payload.data.length);
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
## `helpers()` and `Webhooks.helpers<Schema>()`
|
|
267
|
+
|
|
268
|
+
Schema-bound helpers for building typed handler maps:
|
|
269
|
+
|
|
270
|
+
- `typedHandlers(namespace, action, handler)` — typed entry for one `namespace` + `action`. Pass `'$default'` for `action` to handle every action for that namespace.
|
|
271
|
+
- `typedHandlers('$default', handler)` — top-level catch-all.
|
|
272
|
+
- `combineHandlers(...entries)` — merges entries into a single `WebhookHandlers` object suitable for `processRequest` / `processPayload`.
|
|
273
|
+
|
|
274
|
+
Two ways to get them:
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
// Instance form — infers Schema from the instance, no type argument needed.
|
|
278
|
+
const { typedHandlers, combineHandlers } = db.webhooks.helpers();
|
|
279
|
+
|
|
280
|
+
// Static form — useful when you don't have a Webhooks instance handy.
|
|
281
|
+
const { typedHandlers, combineHandlers } = Webhooks.helpers<typeof schema>();
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Inside each handler, `record.before` and `record.after` are typed according to your schema and narrowed on `action` (`create` ⇒ `before: null`, `delete` ⇒ `after: null`).
|
|
285
|
+
|
|
286
|
+
# Managing webhooks
|
|
287
|
+
|
|
288
|
+
`db.webhooks.manager` exposes CRUD on webhooks and access to their delivery history. All `manager.*` methods require an `adminToken` (admin SDK) or platform OAuth token (platform SDK).
|
|
289
|
+
|
|
290
|
+
## `manager.list()`
|
|
291
|
+
|
|
292
|
+
Returns every webhook configured on the app, newest first. Includes both active and disabled webhooks.
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
const webhooks = await db.webhooks.manager.list();
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
## `manager.create({ url, namespaces, actions })`
|
|
299
|
+
|
|
300
|
+
Creates a webhook in the `active` state. It starts receiving matching events immediately.
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
const webhook = await db.webhooks.manager.create({
|
|
304
|
+
url: 'https://example.com/instant',
|
|
305
|
+
namespaces: ['posts', 'comments'],
|
|
306
|
+
actions: ['create', 'update'],
|
|
307
|
+
});
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
The server rejects the request if `url` isn't an HTTPS URL pointing at a public host, if `namespaces` doesn't reference any entity in the app's schema, if `actions` is empty, or if the app has hit its **100 active webhooks** limit.
|
|
311
|
+
|
|
312
|
+
## `manager.update(webhookId, params)`
|
|
313
|
+
|
|
314
|
+
Patches `url`, `namespaces`, and/or `actions`. Omitted fields keep their current value. Does not affect status — use `enable` / `disable` for that.
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
await db.webhooks.manager.update(webhook.id, {
|
|
318
|
+
actions: ['create', 'update'],
|
|
319
|
+
});
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
## `manager.delete(webhookId)`
|
|
323
|
+
|
|
324
|
+
Deletes a webhook. No further events will be queued for it. Returns the webhook as it looked just before deletion.
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
await db.webhooks.manager.delete(webhook.id);
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
## `manager.enable(webhookId)`
|
|
331
|
+
|
|
332
|
+
Re-enables a disabled webhook. Clears `disabledReason` and resumes delivery for new events. Events that occurred while the webhook was disabled are **not** retroactively delivered.
|
|
333
|
+
|
|
334
|
+
```ts
|
|
335
|
+
await db.webhooks.manager.enable(webhook.id);
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
## `manager.disable(webhookId, opts?)`
|
|
339
|
+
|
|
340
|
+
Stops queuing new events for a webhook. In-flight events already being processed will still complete. Optionally attach a human-readable `reason` that shows up in the dashboard.
|
|
341
|
+
|
|
342
|
+
```ts
|
|
343
|
+
await db.webhooks.manager.disable(webhook.id, {
|
|
344
|
+
reason: 'paused for migration',
|
|
345
|
+
});
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
Instant also disables webhooks automatically after repeated delivery failures.
|
|
349
|
+
|
|
350
|
+
## `manager.listEvents(webhookId, opts?)`
|
|
351
|
+
|
|
352
|
+
Returns a page of delivery events for a webhook, newest first. Events are retained for ~60 days.
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
let cursor: string | null = null;
|
|
356
|
+
do {
|
|
357
|
+
const { events, pageInfo } = await db.webhooks.manager.listEvents(
|
|
358
|
+
webhook.id,
|
|
359
|
+
{
|
|
360
|
+
after: cursor,
|
|
361
|
+
},
|
|
362
|
+
);
|
|
363
|
+
for (const event of events) {
|
|
364
|
+
console.log(event.isn, event.status, event.attempts);
|
|
365
|
+
}
|
|
366
|
+
cursor = pageInfo.hasNextPage ? pageInfo.endCursor : null;
|
|
367
|
+
} while (cursor);
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
Each event's `attempts` array records, per attempt: HTTP status, response body (first 256 bytes), duration, and an `errorType` tag (`timeout`, `dns`, `connect`, `tls`, `protocol`, `network`, `unknown`) when delivery failed.
|
|
371
|
+
|
|
372
|
+
## `manager.getEvent(webhookId, isn)`
|
|
373
|
+
|
|
374
|
+
Fetches a single event by its `isn` (Instant Sequence Number).
|
|
375
|
+
|
|
376
|
+
```ts
|
|
377
|
+
const event = await db.webhooks.manager.getEvent(webhook.id, isn);
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
## `manager.getPayload(webhookId, isn)`
|
|
381
|
+
|
|
382
|
+
Returns the full payload (records + `idempotencyKey`) for an event. Useful for replaying delivery locally with `processPayload`.
|
|
383
|
+
|
|
384
|
+
```ts
|
|
385
|
+
const payload = await db.webhooks.manager.getPayload(webhook.id, isn);
|
|
386
|
+
await db.webhooks.processPayload(handlers, payload);
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
## `manager.resendEvent(webhookId, isn)`
|
|
390
|
+
|
|
391
|
+
Re-queues an event for delivery, regardless of its current status. Use this to retry a `failed` event or force a redelivery of a `success` one.
|
|
392
|
+
|
|
393
|
+
```ts
|
|
394
|
+
await db.webhooks.manager.resendEvent(webhook.id, isn);
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
Rate-limited per event — calling it twice in quick succession returns a validation error asking you to wait about a minute.
|
|
398
|
+
|
|
399
|
+
# Questions?
|
|
400
|
+
|
|
401
|
+
If you have any questions, feel free to drop us a line on our [Discord](https://discord.com/invite/VU53p7uQcE)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { describe, test, expect } from 'vitest';
|
|
2
|
+
import { i } from '@instantdb/core';
|
|
3
|
+
import { Webhooks, type WebhookHandlers } from '../../src/index';
|
|
4
|
+
|
|
5
|
+
const schema = i.schema({
|
|
6
|
+
entities: {
|
|
7
|
+
posts: i.entity({ title: i.string() }),
|
|
8
|
+
comments: i.entity({ body: i.string() }),
|
|
9
|
+
},
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
type Schema = typeof schema;
|
|
13
|
+
|
|
14
|
+
const { typedHandlers, combineHandlers } = Webhooks.helpers<Schema>();
|
|
15
|
+
|
|
16
|
+
describe('typedHandlers', () => {
|
|
17
|
+
test('builds a single namespace.action entry', () => {
|
|
18
|
+
const fn = () => {};
|
|
19
|
+
expect(typedHandlers('posts', 'create', fn)).toEqual({
|
|
20
|
+
posts: { create: fn },
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('builds a namespace $default entry', () => {
|
|
25
|
+
const fn = () => {};
|
|
26
|
+
expect(typedHandlers('posts', '$default', fn)).toEqual({
|
|
27
|
+
posts: { $default: fn },
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('builds a top-level $default entry', () => {
|
|
32
|
+
const fn = () => {};
|
|
33
|
+
expect(typedHandlers('$default', fn)).toEqual({ $default: fn });
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
describe('combineHandlers', () => {
|
|
38
|
+
test('merges entries for different namespaces', () => {
|
|
39
|
+
const onPostCreate = () => {};
|
|
40
|
+
const onCommentDelete = () => {};
|
|
41
|
+
|
|
42
|
+
const handlers = combineHandlers(
|
|
43
|
+
typedHandlers('posts', 'create', onPostCreate),
|
|
44
|
+
typedHandlers('comments', 'delete', onCommentDelete),
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
expect(handlers).toEqual({
|
|
48
|
+
posts: { create: onPostCreate },
|
|
49
|
+
comments: { delete: onCommentDelete },
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('merges actions within the same namespace', () => {
|
|
54
|
+
const onCreate = () => {};
|
|
55
|
+
const onUpdate = () => {};
|
|
56
|
+
const onNamespaceDefault = () => {};
|
|
57
|
+
|
|
58
|
+
const handlers = combineHandlers(
|
|
59
|
+
typedHandlers('posts', 'create', onCreate),
|
|
60
|
+
typedHandlers('posts', 'update', onUpdate),
|
|
61
|
+
typedHandlers('posts', '$default', onNamespaceDefault),
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
expect(handlers).toEqual({
|
|
65
|
+
posts: {
|
|
66
|
+
create: onCreate,
|
|
67
|
+
update: onUpdate,
|
|
68
|
+
$default: onNamespaceDefault,
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('later entries override earlier ones for the same namespace.action', () => {
|
|
74
|
+
const first = () => {};
|
|
75
|
+
const second = () => {};
|
|
76
|
+
|
|
77
|
+
const handlers = combineHandlers(
|
|
78
|
+
typedHandlers('posts', 'create', first),
|
|
79
|
+
typedHandlers('posts', 'create', second),
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
expect(handlers.posts!.create).toBe(second);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('later top-level $default replaces earlier one wholesale', () => {
|
|
86
|
+
const firstDefault = () => {};
|
|
87
|
+
const secondDefault = () => {};
|
|
88
|
+
|
|
89
|
+
const handlers = combineHandlers(
|
|
90
|
+
typedHandlers('$default', firstDefault),
|
|
91
|
+
typedHandlers('$default', secondDefault),
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
expect(handlers.$default).toBe(secondDefault);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('top-level $default does not affect per-namespace handlers', () => {
|
|
98
|
+
const onPostCreate = () => {};
|
|
99
|
+
const topDefault = () => {};
|
|
100
|
+
|
|
101
|
+
const handlers = combineHandlers(
|
|
102
|
+
typedHandlers('posts', 'create', onPostCreate),
|
|
103
|
+
typedHandlers('$default', topDefault),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
expect(handlers).toEqual({
|
|
107
|
+
posts: { create: onPostCreate },
|
|
108
|
+
$default: topDefault,
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test('accepts a pre-built WebhookHandlers map', () => {
|
|
113
|
+
const onPostCreate = () => {};
|
|
114
|
+
const onCommentDefault = () => {};
|
|
115
|
+
|
|
116
|
+
const prebuilt: WebhookHandlers<Schema> = {
|
|
117
|
+
posts: { create: onPostCreate },
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const handlers = combineHandlers(
|
|
121
|
+
prebuilt,
|
|
122
|
+
typedHandlers('comments', '$default', onCommentDefault),
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
expect(handlers).toEqual({
|
|
126
|
+
posts: { create: onPostCreate },
|
|
127
|
+
comments: { $default: onCommentDefault },
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('returns an empty object when given no entries', () => {
|
|
132
|
+
expect(combineHandlers()).toEqual({});
|
|
133
|
+
});
|
|
134
|
+
});
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { describe, test, expect, vi } from 'vitest';
|
|
2
|
+
import { i } from '@instantdb/core';
|
|
3
|
+
import { Webhooks, type WebhookPayload } from '../../src/index';
|
|
4
|
+
|
|
5
|
+
const schema = i.schema({
|
|
6
|
+
entities: {
|
|
7
|
+
posts: i.entity({ title: i.string() }),
|
|
8
|
+
comments: i.entity({ body: i.string() }),
|
|
9
|
+
},
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
type Schema = typeof schema;
|
|
13
|
+
|
|
14
|
+
function makeWebhooks() {
|
|
15
|
+
return new Webhooks<Schema>({ appId: 'app', adminToken: 'tok', schema });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function record(
|
|
19
|
+
namespace: 'posts' | 'comments',
|
|
20
|
+
action: 'create' | 'update' | 'delete',
|
|
21
|
+
id = 'r1',
|
|
22
|
+
) {
|
|
23
|
+
return {
|
|
24
|
+
namespace,
|
|
25
|
+
id,
|
|
26
|
+
action,
|
|
27
|
+
before: action === 'create' ? null : { id, title: 'b', body: 'b' },
|
|
28
|
+
after: action === 'delete' ? null : { id, title: 'a', body: 'a' },
|
|
29
|
+
idempotencyKey: `${namespace}-${action}-${id}`,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function payload(records: any[]): WebhookPayload<Schema> {
|
|
34
|
+
return { data: records, idempotencyKey: 'k' };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
describe('processPayload dispatch precedence', () => {
|
|
38
|
+
test('exact namespace+action wins over namespace $default and top-level $default', async () => {
|
|
39
|
+
const wh = makeWebhooks();
|
|
40
|
+
const exact = vi.fn();
|
|
41
|
+
const namespaceDefault = vi.fn();
|
|
42
|
+
const topDefault = vi.fn();
|
|
43
|
+
|
|
44
|
+
await wh.processPayload(
|
|
45
|
+
{
|
|
46
|
+
posts: { create: exact, $default: namespaceDefault },
|
|
47
|
+
$default: topDefault,
|
|
48
|
+
},
|
|
49
|
+
payload([record('posts', 'create')]),
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
expect(exact).toHaveBeenCalledTimes(1);
|
|
53
|
+
expect(namespaceDefault).not.toHaveBeenCalled();
|
|
54
|
+
expect(topDefault).not.toHaveBeenCalled();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('namespace $default wins over top-level $default when no exact handler', async () => {
|
|
58
|
+
const wh = makeWebhooks();
|
|
59
|
+
const namespaceDefault = vi.fn();
|
|
60
|
+
const topDefault = vi.fn();
|
|
61
|
+
|
|
62
|
+
await wh.processPayload(
|
|
63
|
+
{
|
|
64
|
+
posts: { $default: namespaceDefault },
|
|
65
|
+
$default: topDefault,
|
|
66
|
+
},
|
|
67
|
+
payload([record('posts', 'update')]),
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
expect(namespaceDefault).toHaveBeenCalledTimes(1);
|
|
71
|
+
expect(topDefault).not.toHaveBeenCalled();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('top-level $default catches records with no namespace match', async () => {
|
|
75
|
+
const wh = makeWebhooks();
|
|
76
|
+
const topDefault = vi.fn();
|
|
77
|
+
|
|
78
|
+
await wh.processPayload(
|
|
79
|
+
{
|
|
80
|
+
posts: { create: vi.fn() },
|
|
81
|
+
$default: topDefault,
|
|
82
|
+
},
|
|
83
|
+
payload([record('comments', 'delete')]),
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
expect(topDefault).toHaveBeenCalledTimes(1);
|
|
87
|
+
expect(topDefault.mock.calls[0][0].namespace).toBe('comments');
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('records with no matching handler are skipped without error', async () => {
|
|
91
|
+
const wh = makeWebhooks();
|
|
92
|
+
const postsCreate = vi.fn();
|
|
93
|
+
|
|
94
|
+
await expect(
|
|
95
|
+
wh.processPayload(
|
|
96
|
+
{ posts: { create: postsCreate } },
|
|
97
|
+
payload([
|
|
98
|
+
record('posts', 'create', 'a'),
|
|
99
|
+
record('posts', 'update', 'b'),
|
|
100
|
+
record('comments', 'delete', 'c'),
|
|
101
|
+
]),
|
|
102
|
+
),
|
|
103
|
+
).resolves.toBeUndefined();
|
|
104
|
+
|
|
105
|
+
expect(postsCreate).toHaveBeenCalledTimes(1);
|
|
106
|
+
expect(postsCreate.mock.calls[0][0].id).toBe('a');
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('each record routes to its own most-specific handler', async () => {
|
|
110
|
+
const wh = makeWebhooks();
|
|
111
|
+
const postsCreate = vi.fn();
|
|
112
|
+
const postsDefault = vi.fn();
|
|
113
|
+
const topDefault = vi.fn();
|
|
114
|
+
|
|
115
|
+
await wh.processPayload(
|
|
116
|
+
{
|
|
117
|
+
posts: { create: postsCreate, $default: postsDefault },
|
|
118
|
+
$default: topDefault,
|
|
119
|
+
},
|
|
120
|
+
payload([
|
|
121
|
+
record('posts', 'create', 'a'),
|
|
122
|
+
record('posts', 'update', 'b'),
|
|
123
|
+
record('comments', 'delete', 'c'),
|
|
124
|
+
]),
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
expect(postsCreate).toHaveBeenCalledTimes(1);
|
|
128
|
+
expect(postsCreate.mock.calls[0][0].id).toBe('a');
|
|
129
|
+
expect(postsDefault).toHaveBeenCalledTimes(1);
|
|
130
|
+
expect(postsDefault.mock.calls[0][0].id).toBe('b');
|
|
131
|
+
expect(topDefault).toHaveBeenCalledTimes(1);
|
|
132
|
+
expect(topDefault.mock.calls[0][0].id).toBe('c');
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('rejects when any handler rejects', async () => {
|
|
136
|
+
const wh = makeWebhooks();
|
|
137
|
+
const ok = vi.fn().mockResolvedValue(undefined);
|
|
138
|
+
const bad = vi.fn().mockRejectedValue(new Error('boom'));
|
|
139
|
+
|
|
140
|
+
await expect(
|
|
141
|
+
wh.processPayload(
|
|
142
|
+
{ posts: { create: ok, update: bad } },
|
|
143
|
+
payload([
|
|
144
|
+
record('posts', 'create', 'a'),
|
|
145
|
+
record('posts', 'update', 'b'),
|
|
146
|
+
]),
|
|
147
|
+
),
|
|
148
|
+
).rejects.toThrow('boom');
|
|
149
|
+
|
|
150
|
+
expect(ok).toHaveBeenCalledTimes(1);
|
|
151
|
+
expect(bad).toHaveBeenCalledTimes(1);
|
|
152
|
+
});
|
|
153
|
+
});
|