@vite-hub/webhooks 0.6.1 → 0.7.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/README.md CHANGED
@@ -23,6 +23,31 @@ export default defineWebhook({
23
23
  | `debounce` | Optional. Waits this long after the last send, then delivers once. A duration such as `"30 minutes"` or `"10s"`, at most 24 hours, the longest delay of Cloudflare Queues. |
24
24
  | `events` | Optional. Events that ViteHub sends by itself: `"invocation.failed"`, `"workflow.failed"`, and `"schedule.failed"`. See [Failure alerts](#failure-alerts). |
25
25
 
26
+ The build declares each variable in Server Env as `env.server.webhooks.<name>.url` and `.secret`, optional and secret, so the Console Env section, `inspectServerEnv()` and `vitehub env push` list them. The group key is the file name without its extension, including any dashes. The build reads the names only when they are string literals in the default webhook definition.
27
+
28
+ To change a description or make a variable required, override only that field in `env.server`. Other fields stay in Server Env. For `feedback.ts`, this `env.server` config makes the signing secret required. Use the same variable name as `defineWebhook()` because the override replaces the whole field, not the name that delivery reads.
29
+
30
+ ```ts [vite.config.ts]
31
+ import { env, hubEnv } from "@vite-hub/env/vite"
32
+ import { defineConfig } from "vite"
33
+
34
+ export default defineConfig({
35
+ plugins: [hubEnv({
36
+ server: {
37
+ webhooks: {
38
+ feedback: {
39
+ secret: env({
40
+ secret: true,
41
+ source: env.source("FEEDBACK_WEBHOOK_SECRET", { canonical: false }),
42
+ description: "Signs feedback sent to the receiver.",
43
+ }),
44
+ },
45
+ },
46
+ },
47
+ })],
48
+ })
49
+ ```
50
+
26
51
  The file name is the webhook name: lowercase letters, digits, and dashes. The app needs `queue` and `database` in `vitehub()`, with a SQLite Default Database such as libSQL or D1. Without them, the build fails with `WEBHOOKS_QUEUE_OFF` or `WEBHOOKS_DATABASE_OFF`. Run `vitehub database generate` and `vitehub database migrate` to add the table.
27
52
 
28
53
  ## Send events
@@ -68,7 +93,7 @@ export default defineWebhook({
68
93
  })
69
94
  ```
70
95
 
71
- Agent, Workflow, and Schedule send the event when a run fails with no retry left. The body has the `event`, the Agent, Workflow, or Schedule name, the run or Invocation id, `error: { message, code? }`, `failedAt`, and `text`, one line that a Slack incoming webhook shows as the message. With `debounce`, failures of the same Agent, Workflow, or Schedule collapse into one delivery. The run must execute in a process that loads the app's Webhooks. Standalone cron entries, including Vercel and Netlify cron functions, and Vercel Workflow DevKit (`native`) runs do not send these events.
96
+ Agent, Workflow, and Schedule send the event when a run fails with no retry left. The body has the `event`, the Agent, Workflow, or Schedule name, the run or Invocation id, `error: { message, code? }`, `failedAt`, and `text`, one line that a Slack incoming webhook shows as the message. With `debounce`, failures of the same Agent, Workflow, or Schedule collapse into one delivery. The run must execute in a process that loads the app's Webhooks. Standalone cron entries, such as `Deno.cron` and `providerOutput: 'standalone'` output, and Vercel Workflow DevKit (`native`) runs do not send these events.
72
97
 
73
98
  ## How a delivery works
74
99
 
@@ -79,6 +104,8 @@ Agent, Workflow, and Schedule send the event when a run fails with no retry left
79
104
 
80
105
  Errors and stored fields never hold the URL, its query, or the secret. A delivery is one of `pending`, `sending`, `sent`, `dead`, or `cancelled`.
81
106
 
107
+ Webhooks prunes finished deliveries after a time: `sent`, `cancelled`, and inbox deliveries after 7 days, `dead` ones after 30 days. Change it with `vitehub({ webhooks: { retention: { sent: '7 days', dead: '30 days' } } })`, where `false` keeps that kind. Each wake and each member send prunes up to 100 old deliveries. Pending and sending deliveries always stay. For a successful member send with a key, pruning removes the payload and hides the delivery from history but keeps its result and key for Comments Send and deduplication.
108
+
82
109
  ## Member endpoints
83
110
 
84
111
  A member endpoint is a receiver that belongs to one member of the app, such as their T3 Code thread. A feature that sends to members turns them on, such as Send in Comments, or a Vite plugin with `vitehub.webhooks: { memberEndpoints: true, reason }`. They need `database`, not `queue`.
@@ -97,7 +124,7 @@ export async function connectAndSend(userId: string, url: string, secret: string
97
124
  | Function | Does |
98
125
  | --- | --- |
99
126
  | `createMemberEndpoint({ owner, ownerName?, ownerEmail?, name, kind, url?, secret?, agent?, address?, hosts? })` | Stores a member's receiver. `kind` is `"url"` or `"inbox"`. The URL must pass `checkWebhookUrl()` with `hosts`, which defaults to `relay.t3.codes`. `address` says where the agent can be reached, such as its T3 thread URL: a member has one endpoint per address, and a new one replaces the one with the same address. |
100
- | `sendToMemberEndpoint(owner, body, { event, key, address?, endpointId? })` | Posts to the member's endpoint with `address`, else to their newest. Pass `endpointId` to send only to that endpoint with no fallback. Posts in the request with a 10 second timeout and the usual signature. The same `key` posts once per endpoint. Returns `[error, { id, status }]`, where `status` is `"sent"`, `"inbox"`, `"pending"` (the Queue retries), or `"failed"`. |
127
+ | `sendToMemberEndpoint(owner, body, { event, key, address?, endpointId? })` | Posts to the member's endpoint with `address`, else to their newest. Pass `endpointId` to send only to that endpoint with no fallback. Posts in the request with a 10 second timeout and the usual signature. The same `key` posts once per endpoint, and takes over a delivery that a stopped server left in `sending` for more than 70 seconds. With Queue, each send also gets a wake that recovers it. Returns `[error, { id, status }]`, where `status` is `"sent"`, `"inbox"`, `"pending"` (the Queue retries), or `"failed"`. |
101
128
  | `listMemberDeliveries(owner, { address?, endpointId?, limit?, before? })` | The selected endpoint and its deliveries, newest first, or `null`. Inbox agents should pass the `endpointId` from pairing so their reads never switch to another endpoint. An empty `address` prefers the unaddressed endpoint. |
102
129
  | `getMemberDelivery(id)` | The `state` of a member delivery and `inbox`, true when it waits in an inbox, or `undefined`. It never returns the body. `inbox` stays true after the member removes the endpoint. |
103
130
  | `startMemberPairing(owner)`, `pairMemberEndpoint(input, { hosts? })`, `allowMemberPairing(owner, code, { name, ownerName?, ownerEmail?, hosts? })` | Pair a member's agent with a one-use code that works for 10 minutes. Give the agent the `code` and `secret` that start returns. A route passes its post, `{ code, url, thread? }` or `{ code, inbox }`, to `pairMemberEndpoint`, and the member's Allow creates the endpoint, with the agent's T3 thread link as its address. `getMemberPairing`, `cancelMemberPairing`, and `refuseMemberPairing` poll, close, and use up a code. Comments Send pairs this way. |
@@ -1407,7 +1407,9 @@ interface WebhookDeliveryStore {
1407
1407
  recordOnce: (send: WebhookSendRecord & {
1408
1408
  key: string;
1409
1409
  }) => Promise<WebhookRecordOnceResult>;
1410
- get: (id: string) => Promise<WebhookDelivery | undefined>;
1410
+ get: (id: string, options?: {
1411
+ includeExpired?: boolean;
1412
+ }) => Promise<WebhookDelivery | undefined>;
1411
1413
  list: (options?: ListWebhookDeliveriesOptions) => Promise<WebhookDelivery[]>;
1412
1414
  /** Pending deliveries, the soonest due first. */
1413
1415
  pending: (options?: {
@@ -1419,6 +1421,8 @@ interface WebhookDeliveryStore {
1419
1421
  * at `revision` with a claim older than `staleBefore`, which a stopped server left.
1420
1422
  */
1421
1423
  claim: (id: string, revision: number, now: number, staleBefore: number) => Promise<WebhookDelivery | undefined>;
1424
+ /** Takes over only a `sending` delivery with an expired claim at `revision`. */
1425
+ claimExpired?: (id: string, revision: number, now: number, staleBefore: number) => Promise<WebhookDelivery | undefined>;
1422
1426
  /** Marks the claimed delivery `sent`. */
1423
1427
  sent: (claim: WebhookDelivery, result: WebhookAttemptResult, now: number) => Promise<void>;
1424
1428
  /**
@@ -1430,6 +1434,16 @@ interface WebhookDeliveryStore {
1430
1434
  due: (id: string, now: number) => Promise<WebhookDelivery | undefined>;
1431
1435
  /** Cancels a pending delivery. */
1432
1436
  cancel: (id: string, now: number) => Promise<WebhookDelivery | undefined>;
1437
+ /**
1438
+ * Prunes up to `limit` finished deliveries. For a sent member delivery with a key, it drops only the payload and hides
1439
+ * the delivery from history. Sent and cancelled deliveries expire at `sentBefore`, dead ones at `deadBefore`, and
1440
+ * `null` keeps that kind. Returns how many deliveries it pruned.
1441
+ */
1442
+ prune: (options: {
1443
+ sentBefore: number | null;
1444
+ deadBefore: number | null;
1445
+ limit: number;
1446
+ }) => Promise<number>;
1433
1447
  /** The newest delivery of each member endpoint, by its `webhook` value `@<endpoint id>`. */
1434
1448
  memberResults: (webhooks: readonly string[]) => Promise<Map<string, MemberLastDelivery>>;
1435
1449
  }
@@ -1,2 +1,2 @@
1
- import { C as webhooksSchema, E as webhooksTableNames, S as webhookPairings, T as webhookEndpointsTableNames, _ as createDrizzleWebhookEndpointStore, a as MemberLastDelivery, b as webhookEndpoints, c as StoredMemberPairing, d as WebhookDeliveryState, f as WebhookDeliveryStore, g as WebhooksDatabase, h as WebhookSendRecord, i as MemberEndpointKind, l as WebhookAttemptResult, m as WebhookRecordOnceResult, n as ListWebhookDeliveriesOptions, o as MemberPairingState, p as WebhookEndpointStore, r as MemberEndpoint, s as StoredMemberEndpoint, t as ListMemberEndpointsOptions, u as WebhookDelivery, v as createDrizzleWebhookStore, w as webhooksTables, x as webhookEndpointsSchema, y as webhookDeliveries } from "./database-C5cwO1an.js";
1
+ import { C as webhooksSchema, E as webhooksTableNames, S as webhookPairings, T as webhookEndpointsTableNames, _ as createDrizzleWebhookEndpointStore, a as MemberLastDelivery, b as webhookEndpoints, c as StoredMemberPairing, d as WebhookDeliveryState, f as WebhookDeliveryStore, g as WebhooksDatabase, h as WebhookSendRecord, i as MemberEndpointKind, l as WebhookAttemptResult, m as WebhookRecordOnceResult, n as ListWebhookDeliveriesOptions, o as MemberPairingState, p as WebhookEndpointStore, r as MemberEndpoint, s as StoredMemberEndpoint, t as ListMemberEndpointsOptions, u as WebhookDelivery, v as createDrizzleWebhookStore, w as webhooksTables, x as webhookEndpointsSchema, y as webhookDeliveries } from "./database-CQ0i7hWU.js";
2
2
  export { ListMemberEndpointsOptions, ListWebhookDeliveriesOptions, MemberEndpoint, MemberEndpointKind, MemberLastDelivery, MemberPairingState, StoredMemberEndpoint, StoredMemberPairing, WebhookAttemptResult, WebhookDelivery, WebhookDeliveryState, WebhookDeliveryStore, WebhookEndpointStore, WebhookRecordOnceResult, WebhookSendRecord, WebhooksDatabase, createDrizzleWebhookEndpointStore, createDrizzleWebhookStore, webhookDeliveries, webhookEndpoints, webhookEndpointsSchema, webhookEndpointsTableNames, webhookPairings, webhooksSchema, webhooksTableNames, webhooksTables };
package/dist/database.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as webhooksErrors } from "./errors-DT8uyCh7.js";
1
+ import { t as webhooksErrors } from "./errors-8u_DGHUd.js";
2
2
  import { n as webhooksTableNames, t as webhookEndpointsTableNames } from "./table-names-DAUip4v2.js";
3
- import { and, asc, desc, eq, gt, gte, inArray, lt, or, sql } from "drizzle-orm";
3
+ import { and, asc, desc, eq, gt, gte, inArray, lt, ne, not, or, sql } from "drizzle-orm";
4
4
  import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
5
5
  /**
6
6
  * One row for each delivery. A debounced webhook keeps one `pending` row for each `(webhook, key)`: each send replaces
@@ -101,11 +101,12 @@ const webhooksTables = [
101
101
  function hasBatch(database) {
102
102
  return "batch" in database && typeof database.batch === "function";
103
103
  }
104
+ const expiredBody = "";
104
105
  function toDelivery(row) {
105
106
  const { owner: _owner, ...delivery } = row;
106
107
  return {
107
108
  ...delivery,
108
- body: JSON.parse(row.body)
109
+ body: row.body === expiredBody ? null : JSON.parse(row.body)
109
110
  };
110
111
  }
111
112
  async function guarded(action, run) {
@@ -126,6 +127,15 @@ async function guarded(action, run) {
126
127
  function createDrizzleWebhookStore(database) {
127
128
  const db = typeof database === "function" ? database : () => database;
128
129
  const t = webhookDeliveries;
130
+ const claimDelivery = (id, revision, now, staleBefore, includePending) => guarded("claim a delivery", async () => {
131
+ const expired = and(eq(t.state, "sending"), lt(t.updatedAt, staleBefore));
132
+ const [row] = await db().update(t).set({
133
+ state: "sending",
134
+ attempts: sql`${t.attempts} + 1`,
135
+ updatedAt: now
136
+ }).where(and(eq(t.id, id), eq(t.revision, revision), includePending ? or(eq(t.state, "pending"), expired) : expired)).returning();
137
+ return row ? toDelivery(row) : void 0;
138
+ });
129
139
  return {
130
140
  record: (send) => guarded("store a delivery", async () => {
131
141
  const insert = db().insert(t).values({
@@ -198,28 +208,22 @@ function createDrizzleWebhookStore(database) {
198
208
  };
199
209
  throw webhooksErrors.WEBHOOKS_STORE_FAILED({ action: "store a delivery" });
200
210
  }),
201
- get: (id) => guarded("read a delivery", async () => {
202
- const [row] = await db().select().from(t).where(eq(t.id, id)).limit(1);
211
+ get: (id, options) => guarded("read a delivery", async () => {
212
+ const [row] = await db().select().from(t).where(and(eq(t.id, id), options?.includeExpired ? void 0 : ne(t.body, expiredBody))).limit(1);
203
213
  return row ? toDelivery(row) : void 0;
204
214
  }),
205
215
  list: (options = {}) => guarded("list deliveries", async () => {
206
216
  const limit = Math.min(Math.max(options.limit ?? 100, 1), 500);
207
217
  const { before } = options;
208
- const where = and(options.webhook ? eq(t.webhook, options.webhook) : void 0, options.owner !== void 0 ? eq(t.owner, options.owner) : void 0, options.state ? eq(t.state, options.state) : void 0, before ? or(lt(t.createdAt, before.createdAt), and(eq(t.createdAt, before.createdAt), lt(t.id, before.id))) : void 0);
218
+ const where = and(ne(t.body, expiredBody), options.webhook ? eq(t.webhook, options.webhook) : void 0, options.owner !== void 0 ? eq(t.owner, options.owner) : void 0, options.state ? eq(t.state, options.state) : void 0, before ? or(lt(t.createdAt, before.createdAt), and(eq(t.createdAt, before.createdAt), lt(t.id, before.id))) : void 0);
209
219
  return (await db().select().from(t).where(where).orderBy(desc(t.createdAt), desc(t.id)).limit(limit)).map(toDelivery);
210
220
  }),
211
221
  pending: (options = {}) => guarded("list pending deliveries", async () => {
212
222
  const limit = Math.min(Math.max(options.limit ?? 100, 1), 500);
213
223
  return (await db().select().from(t).where(and(eq(t.state, "pending"), options.webhook ? eq(t.webhook, options.webhook) : void 0)).orderBy(asc(t.dueAt), asc(t.id)).limit(limit)).map(toDelivery);
214
224
  }),
215
- claim: (id, revision, now, staleBefore) => guarded("claim a delivery", async () => {
216
- const [row] = await db().update(t).set({
217
- state: "sending",
218
- attempts: sql`${t.attempts} + 1`,
219
- updatedAt: now
220
- }).where(and(eq(t.id, id), eq(t.revision, revision), or(eq(t.state, "pending"), and(eq(t.state, "sending"), lt(t.updatedAt, staleBefore))))).returning();
221
- return row ? toDelivery(row) : void 0;
222
- }),
225
+ claim: (id, revision, now, staleBefore) => claimDelivery(id, revision, now, staleBefore, true),
226
+ claimExpired: (id, revision, now, staleBefore) => claimDelivery(id, revision, now, staleBefore, false),
223
227
  sent: (claim, result, now) => guarded("mark a delivery sent", async () => {
224
228
  await db().update(t).set({
225
229
  state: "sent",
@@ -254,6 +258,18 @@ function createDrizzleWebhookStore(database) {
254
258
  }).where(and(eq(t.id, id), eq(t.state, "pending"))).returning();
255
259
  return row ? toDelivery(row) : void 0;
256
260
  }),
261
+ prune: ({ sentBefore, deadBefore, limit }) => guarded("prune old deliveries", async () => {
262
+ const finished = or(sentBefore === null ? void 0 : and(inArray(t.state, ["sent", "cancelled"]), lt(t.updatedAt, sentBefore)), deadBefore === null ? void 0 : and(eq(t.state, "dead"), lt(t.updatedAt, deadBefore)));
263
+ if (!finished) return 0;
264
+ const connection = db();
265
+ const keepResult = sql`${t.state} = 'sent' AND ${t.key} IS NOT NULL AND ${t.webhook} LIKE '@%'`;
266
+ const expired = and(finished, ne(t.body, expiredBody));
267
+ const retained = sentBefore === null ? [] : await connection.update(t).set({ body: expiredBody }).where(inArray(t.id, connection.select({ id: t.id }).from(t).where(and(expired, keepResult)).limit(limit))).returning({ id: t.id });
268
+ if (retained.length === limit) return limit;
269
+ const old = connection.select({ id: t.id }).from(t).where(and(expired, not(keepResult))).limit(limit - retained.length);
270
+ const rows = await connection.delete(t).where(inArray(t.id, old)).returning({ id: t.id });
271
+ return retained.length + rows.length;
272
+ }),
257
273
  memberResults: (webhooks) => guarded("read the member deliveries", async () => {
258
274
  if (!webhooks.length) return /* @__PURE__ */ new Map();
259
275
  const rows = await db().all(sql`
@@ -39,6 +39,10 @@ const webhooksErrors = /*#__PURE__*/ defineErrors({
39
39
  why: ({ files }) => `Webhooks sends each delivery through the Queue, but the app has no Queue. These files define webhooks: ${files}.`,
40
40
  fix: "Turn on `queue` in `vitehub()`, or remove the files of `server/webhooks/`."
41
41
  },
42
+ WEBHOOKS_RETENTION_INVALID: {
43
+ why: ({ problem }) => `\`webhooks.retention\` of \`vitehub()\` is not valid: ${problem}.`,
44
+ fix: "Set `webhooks: { retention: { sent: \"7 days\", dead: \"30 days\" } }`. Each value is a duration, or `false` to keep those deliveries."
45
+ },
42
46
  WEBHOOKS_BODY_INVALID: {
43
47
  why: ({ webhook }) => `The body for the webhook ${webhook} is not JSON data.`,
44
48
  fix: "Pass a plain object, an array, a string, a number, a boolean, or `null`. Convert a `Date` to an ISO string and a `bigint` to a string first."
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { C as WebhookDeliveryErrorCode, S as SendWebhookErrorCode, _ as sendToMemberEndpoint, a as SendToMemberEndpointResult, b as MemberPairingErrorCode, c as enableMemberEndpoint, d as getMemberEndpoint, f as listMemberDeliveries, g as removeMemberEndpoints, h as removeMemberEndpoint, i as SendToMemberEndpointOptions, l as getMemberDelivery, m as memberEndpointHosts, n as MemberDeliveries, o as createMemberEndpoint, p as listMemberEndpoints, r as MemberEndpointWithLastDelivery, s as disableMemberEndpoint, t as CreateMemberEndpointOptions, u as getMemberDeliveryState, v as CreateMemberEndpointErrorCode, x as SendToMemberEndpointErrorCode, y as MemberEndpointErrorCode } from "./members-Cn93y6gO.js";
2
- import { B as WebhookSignature, F as sealWebhooksText, I as unsealWebhooksText, L as WebhookDefinition, R as WebhookEvent, V as defineWebhook, a as SendWebhookResult, s as WebhookEventBody, z as WebhookOptions } from "./runtime-BYILR6Zc.js";
3
- import { a as MemberLastDelivery, i as MemberEndpointKind, o as MemberPairingState, r as MemberEndpoint } from "./database-C5cwO1an.js";
1
+ import { C as WebhookDeliveryErrorCode, S as SendWebhookErrorCode, _ as sendToMemberEndpoint, a as SendToMemberEndpointResult, b as MemberPairingErrorCode, c as enableMemberEndpoint, d as getMemberEndpoint, f as listMemberDeliveries, g as removeMemberEndpoints, h as removeMemberEndpoint, i as SendToMemberEndpointOptions, l as getMemberDelivery, m as memberEndpointHosts, n as MemberDeliveries, o as createMemberEndpoint, p as listMemberEndpoints, r as MemberEndpointWithLastDelivery, s as disableMemberEndpoint, t as CreateMemberEndpointOptions, u as getMemberDeliveryState, v as CreateMemberEndpointErrorCode, x as SendToMemberEndpointErrorCode, y as MemberEndpointErrorCode } from "./members-D5P9ts4J.js";
2
+ import { R as sealWebhooksText, a as SendWebhookResult, s as WebhookEventBody, z as unsealWebhooksText } from "./runtime-2igB0GrL.js";
3
+ import { a as WebhookOptions, c as defineWebhook, i as WebhookEvent, o as WebhookSignature, r as WebhookDefinition, s as WebhooksRetention } from "./queue-name-CWPhsc2U.js";
4
+ import { a as MemberLastDelivery, i as MemberEndpointKind, o as MemberPairingState, r as MemberEndpoint } from "./database-CQ0i7hWU.js";
4
5
  import { Result } from "@vite-hub/runtime";
5
6
  /** How long a pairing code works: 10 minutes. */
6
7
  export declare const memberPairingLifetime: number;
@@ -156,4 +157,4 @@ export interface SendWebhookOptions {
156
157
  * ```
157
158
  */
158
159
  export declare function sendWebhook<TName extends WebhookName>(name: TName, body: unknown, options: SendWebhookOptions): Promise<Result<SendWebhookResult, SendWebhookErrorCode>>;
159
- export { type AllowMemberPairingOptions, type CheckWebhookUrlOptions, type CreateMemberEndpointErrorCode, type CreateMemberEndpointOptions, type MemberAllowResult, type MemberDeliveries, type MemberEndpoint, type MemberEndpointErrorCode, type MemberEndpointKind, type MemberEndpointWithLastDelivery, type MemberLastDelivery, type MemberPairResult, type MemberPairing, type MemberPairingErrorCode, type MemberPairingState, type SendToMemberEndpointErrorCode, type SendToMemberEndpointOptions, type SendToMemberEndpointResult, type SendWebhookErrorCode, type SendWebhookResult, type WebhookDefinition, type WebhookDeliveryErrorCode, type WebhookEvent, type WebhookEventBody, type WebhookOptions, type WebhookSignature, createMemberEndpoint, defineWebhook, disableMemberEndpoint, enableMemberEndpoint, getMemberDelivery, getMemberDeliveryState, getMemberEndpoint, listMemberDeliveries, listMemberEndpoints, memberEndpointHosts, removeMemberEndpoint, removeMemberEndpoints, sealWebhooksText, sendToMemberEndpoint, unsealWebhooksText };
160
+ export { type AllowMemberPairingOptions, type CheckWebhookUrlOptions, type CreateMemberEndpointErrorCode, type CreateMemberEndpointOptions, type MemberAllowResult, type MemberDeliveries, type MemberEndpoint, type MemberEndpointErrorCode, type MemberEndpointKind, type MemberEndpointWithLastDelivery, type MemberLastDelivery, type MemberPairResult, type MemberPairing, type MemberPairingErrorCode, type MemberPairingState, type SendToMemberEndpointErrorCode, type SendToMemberEndpointOptions, type SendToMemberEndpointResult, type SendWebhookErrorCode, type SendWebhookResult, type WebhookDefinition, type WebhookDeliveryErrorCode, type WebhookEvent, type WebhookEventBody, type WebhookOptions, type WebhookSignature, type WebhooksRetention, createMemberEndpoint, defineWebhook, disableMemberEndpoint, enableMemberEndpoint, getMemberDelivery, getMemberDeliveryState, getMemberEndpoint, listMemberDeliveries, listMemberEndpoints, memberEndpointHosts, removeMemberEndpoint, removeMemberEndpoints, sealWebhooksText, sendToMemberEndpoint, unsealWebhooksText };
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import { M as unsealWebhooksText, N as defineWebhook, T as checkWebhookUrl, _ as requireMemberEndpoints, k as sealWebhooksText, y as sendDynamicWebhook } from "./runtime-BFiCJOMB.js";
2
- import { a as getMemberDeliveryState, c as listMemberEndpoints, d as removeMemberEndpoint, f as removeMemberEndpoints, i as getMemberDelivery, l as memberEndpointHosts, n as disableMemberEndpoint, o as getMemberEndpoint, p as sendToMemberEndpoint, r as enableMemberEndpoint, s as listMemberDeliveries, t as createMemberEndpoint } from "./members-DvpsP5Px.js";
3
- import { t as webhooksErrors } from "./errors-DT8uyCh7.js";
1
+ import { F as unsealWebhooksText, M as sealWebhooksText, O as checkWebhookUrl, x as sendDynamicWebhook, y as requireMemberEndpoints } from "./runtime-DhvHbH0D.js";
2
+ import { n as defineWebhook } from "./queue-name-BL96iCCH.js";
3
+ import { a as getMemberDeliveryState, c as listMemberEndpoints, d as removeMemberEndpoint, f as removeMemberEndpoints, i as getMemberDelivery, l as memberEndpointHosts, n as disableMemberEndpoint, o as getMemberEndpoint, p as sendToMemberEndpoint, r as enableMemberEndpoint, s as listMemberDeliveries, t as createMemberEndpoint } from "./members-CD76JOUv.js";
4
+ import { t as webhooksErrors } from "./errors-8u_DGHUd.js";
4
5
  // src/pairing.ts
5
6
  /** How long a pairing code works: 10 minutes. */
6
7
  const memberPairingLifetime = 6e5;
@@ -1,5 +1,5 @@
1
- import { t as webhooksErrors } from "./errors-DT8uyCh7.js";
2
- import { A as sealedMemberBodyPrefix, D as memberBodyLabel, E as outsideHosts, O as sealEndpoint, T as checkWebhookUrl, _ as requireMemberEndpoints, j as unsealEndpoint, k as sealWebhooksText, n as createDeliveryId, r as deliverMemberClaim, s as inspectDelivery } from "./runtime-BFiCJOMB.js";
1
+ import { t as webhooksErrors } from "./errors-8u_DGHUd.js";
2
+ import { A as memberBodyLabel, M as sealWebhooksText, N as sealedMemberBodyPrefix, O as checkWebhookUrl, P as unsealEndpoint, _ as pruneWebhookDeliveries, c as inspectDelivery, i as deliverMemberDelivery, j as sealEndpoint, k as outsideHosts, n as createDeliveryId, y as requireMemberEndpoints } from "./runtime-DhvHbH0D.js";
3
3
  // \0rolldown/runtime.js
4
4
  var __defProp = Object.defineProperty;
5
5
  var __exportAll = (all, no_symbols) => {
@@ -240,6 +240,7 @@ async function sendToMemberEndpoint(owner, body, options) {
240
240
  json = JSON.stringify(`${sealedMemberBodyPrefix}${sealed}`);
241
241
  }
242
242
  const now = Date.now();
243
+ await pruneWebhookDeliveries(installed, now);
243
244
  const recorded = await store.recordOnce({
244
245
  id: options.deliveryId ?? createDeliveryId(),
245
246
  webhook,
@@ -251,16 +252,18 @@ async function sendToMemberEndpoint(owner, body, options) {
251
252
  now
252
253
  });
253
254
  const done = target ? "sent" : "inbox";
254
- if (!recorded.created) return [void 0, {
255
+ if (recorded.state === "sent") return [void 0, {
255
256
  id: recorded.id,
256
- status: recorded.state === "sent" ? done : "pending"
257
+ status: done
257
258
  }];
258
- const claim = await store.claim(recorded.id, recorded.revision, now, 0);
259
- if (!claim) return [void 0, {
259
+ if (!recorded.created && recorded.state !== "sending") return [void 0, {
260
260
  id: recorded.id,
261
261
  status: "pending"
262
262
  }];
263
- return await deliverMemberClaim(installed, claim, target);
263
+ return await deliverMemberDelivery(installed, {
264
+ ...recorded,
265
+ webhook
266
+ }, target, { takeOver: !recorded.created });
264
267
  } catch (error) {
265
268
  return [storeError(error), void 0];
266
269
  }
@@ -310,7 +313,7 @@ async function getMemberDeliveryState(id) {
310
313
  * the member removes the endpoint, so it tells where an old delivery went.
311
314
  */
312
315
  async function getMemberDelivery(id) {
313
- const row = await requireMemberEndpoints().store.get(id);
316
+ const row = await requireMemberEndpoints().store.get(id, { includeExpired: true });
314
317
  if (!row?.webhook.startsWith("@")) return void 0;
315
318
  return {
316
319
  state: row.state,
@@ -1,4 +1,4 @@
1
- import { a as MemberLastDelivery, d as WebhookDeliveryState, n as ListWebhookDeliveriesOptions, r as MemberEndpoint, t as ListMemberEndpointsOptions, u as WebhookDelivery } from "./database-C5cwO1an.js";
1
+ import { a as MemberLastDelivery, d as WebhookDeliveryState, n as ListWebhookDeliveriesOptions, r as MemberEndpoint, t as ListMemberEndpointsOptions, u as WebhookDelivery } from "./database-CQ0i7hWU.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  declare const webhooksErrors: import("@vite-hub/runtime").ErrorCatalog<{
4
4
  readonly WEBHOOKS_CONTRIBUTION_INVALID: {
@@ -51,6 +51,12 @@ declare const webhooksErrors: import("@vite-hub/runtime").ErrorCatalog<{
51
51
  }) => string;
52
52
  readonly fix: "Turn on `queue` in `vitehub()`, or remove the files of `server/webhooks/`.";
53
53
  };
54
+ readonly WEBHOOKS_RETENTION_INVALID: {
55
+ readonly why: ({ problem }: {
56
+ problem: string;
57
+ }) => string;
58
+ readonly fix: "Set `webhooks: { retention: { sent: \"7 days\", dead: \"30 days\" } }`. Each value is a duration, or `false` to keep those deliveries.";
59
+ };
54
60
  readonly WEBHOOKS_BODY_INVALID: {
55
61
  readonly why: ({ webhook }: {
56
62
  webhook: string;
@@ -1,6 +1,6 @@
1
1
  import { t as AnyOperation } from "./operations-8hqTi0DH.js";
2
- import { r as MemberEndpoint } from "./database-C5cwO1an.js";
3
- import { r as MemberEndpointWithLastDelivery } from "./members-Cn93y6gO.js";
2
+ import { r as MemberEndpoint } from "./database-CQ0i7hWU.js";
3
+ import { r as MemberEndpointWithLastDelivery } from "./members-D5P9ts4J.js";
4
4
  /**
5
5
  * One member endpoint, as `webhooks.endpoints` lists it for admins: no URL, no secret, and no email. `mine` is true
6
6
  * when the caller owns it, so the Console shows Redeliver only on the caller's own deliveries.
@@ -1,5 +1,5 @@
1
1
  import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
2
- import { t as webhooksErrors } from "./errors-DT8uyCh7.js";
2
+ import { t as webhooksErrors } from "./errors-8u_DGHUd.js";
3
3
  import { toJsonSchema } from "@valibot/to-json-schema";
4
4
  import * as v from "valibot";
5
5
  // ../../node_modules/.pnpm/nostics@1.4.0/node_modules/nostics/dist/index.mjs
@@ -134,7 +134,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
134
134
  why: ({ message }) => message === void 0 ? "" : String(message)
135
135
  },
136
136
  INTERNAL_R0024: {
137
- fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
137
+ fix: "Start the dev server (`nuxt dev` or `vite dev`), or pass `--url <origin>` of a deployed app and set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to a private key whose public key the app has in VITEHUB_CONSOLE_KEY_<NAME>.",
138
138
  why: ({ message }) => message === void 0 ? "" : String(message)
139
139
  },
140
140
  INTERNAL_R0023: {
@@ -250,7 +250,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
250
250
  fix: "Give a switch column `format: \"switch\"` and `switch: { operation, input }` with a registered operation name, or remove both."
251
251
  },
252
252
  INTERNAL_R0025: {
253
- fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
253
+ fix: "Start the dev server (`nuxt dev` or `vite dev`) in the project that you run the command from, or pass `--url` of that server.",
254
254
  why: ({ message }) => message === void 0 ? "" : String(message)
255
255
  },
256
256
  INTERNAL_R0026: {
@@ -271,7 +271,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
271
271
  },
272
272
  INTERNAL_R0002: {
273
273
  ...dynamicError,
274
- fix: "Stop using the feature that the message names, or set `host` in `vitehub()` to a host that provides it. For Blob, you can also set `blob: { driver: \"s3\" }` with a remote store."
274
+ fix: ({ fix }) => fix ?? "Build for a host that provides this capability, or set the option named in the message to `false`."
275
275
  },
276
276
  INTERNAL_R0004: {
277
277
  ...dynamicError,
@@ -511,7 +511,7 @@ function operationInputJsonSchema(operation) {
511
511
  }
512
512
  // src/operations.ts
513
513
  const runtime = () => import("./runtime.js");
514
- const members = () => import("./members-DvpsP5Px.js").then((n) => n.u);
514
+ const members = () => import("./members-CD76JOUv.js").then((n) => n.u);
515
515
  const statuses = {
516
516
  WEBHOOKS_BODY_INVALID: 400,
517
517
  WEBHOOKS_DATABASE_MISSING: 409,
@@ -0,0 +1,80 @@
1
+ import { t as webhooksErrors } from "./errors-8u_DGHUd.js";
2
+ import { runFailedEventNames } from "@vite-hub/runtime/internal/run-failed";
3
+ import { parseDuration } from "@vite-hub/runtime";
4
+ // src/define.ts
5
+ const definitionBrand = Symbol.for("vitehub.webhooks.definition");
6
+ const variableName = /^[A-Z_][A-Z0-9_]*$/i;
7
+ function isWebhookEvent(value) {
8
+ return runFailedEventNames.some((name) => name === value);
9
+ }
10
+ function invalid(message) {
11
+ return webhooksErrors.WEBHOOKS_DEFINITION_INVALID({ message: `[vitehub] ${message}` });
12
+ }
13
+ /**
14
+ * Defines a webhook: where ViteHub sends events, how it signs them, and how long it waits to collapse them. Default-export
15
+ * it from `server/webhooks/<name>.ts`, then call `sendWebhook("<name>", body)` from server code, or list `events` that
16
+ * ViteHub sends by itself.
17
+ *
18
+ * ```ts [server/webhooks/t3.ts]
19
+ * import { defineWebhook } from "@vite-hub/webhooks"
20
+ *
21
+ * export default defineWebhook({
22
+ * url: "T3_WEBHOOK_URL",
23
+ * secret: "T3_WEBHOOK_SECRET",
24
+ * debounce: "30m",
25
+ * })
26
+ * ```
27
+ */
28
+ function defineWebhook(options) {
29
+ for (const key of ["url", "secret"]) {
30
+ const value = options?.[key];
31
+ if (typeof value !== "string" || !variableName.test(value)) throw invalid(`\`${key}\` must be the name of a server variable, such as ${key === "url" ? "\"T3_WEBHOOK_URL\"" : "\"T3_WEBHOOK_SECRET\""}, not ${JSON.stringify(value)}.`);
32
+ }
33
+ const signature = options.signature ?? "github";
34
+ if (signature !== "github" && signature !== "stripe") throw invalid(`\`signature\` must be "github" or "stripe", not ${JSON.stringify(signature)}.`);
35
+ const debounceMs = options.debounce === void 0 ? 0 : parseDuration(options.debounce, "debounce");
36
+ if (debounceMs > 864e5) throw webhooksErrors.WEBHOOKS_DEBOUNCE_TOO_LONG({ debounce: JSON.stringify(options.debounce) });
37
+ const listed = options.events ?? [];
38
+ if (!Array.isArray(listed)) throw invalid(`\`events\` must be a list such as ["workflow.failed"], not ${JSON.stringify(listed)}.`);
39
+ const items = listed;
40
+ const events = /* @__PURE__ */ new Set();
41
+ for (const event of items) {
42
+ if (!isWebhookEvent(event)) throw invalid(`\`events\` lists ${JSON.stringify(event)}. Use ${runFailedEventNames.map((name) => JSON.stringify(name)).join(", ")}.`);
43
+ events.add(event);
44
+ }
45
+ return Object.defineProperty({
46
+ url: options.url,
47
+ secret: options.secret,
48
+ signature,
49
+ debounceMs,
50
+ events: [...events]
51
+ }, definitionBrand, { value: true });
52
+ }
53
+ function isWebhookDefinition(value) {
54
+ return typeof value === "object" && value !== null && Reflect.get(value, definitionBrand) === true;
55
+ }
56
+ const defaultRetention = {
57
+ sent: "7 days",
58
+ dead: "30 days"
59
+ };
60
+ /** Reads `webhooks.retention` of `vitehub()`. A value of the wrong shape throws `WEBHOOKS_RETENTION_INVALID`. */
61
+ function resolveWebhooksRetention(value = {}) {
62
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw webhooksErrors.WEBHOOKS_RETENTION_INVALID({ problem: `it is ${JSON.stringify(value)}, not an object` });
63
+ const unknown = Object.keys(value).find((key) => key !== "sent" && key !== "dead");
64
+ if (unknown !== void 0) throw webhooksErrors.WEBHOOKS_RETENTION_INVALID({ problem: `it has the key ${JSON.stringify(unknown)}` });
65
+ const read = (key) => {
66
+ const configured = Reflect.get(value, key);
67
+ const duration = configured === void 0 ? defaultRetention[key] : configured;
68
+ if (duration === false) return null;
69
+ if (typeof duration !== "string") throw webhooksErrors.WEBHOOKS_RETENTION_INVALID({ problem: `\`${key}\` is ${JSON.stringify(duration)}` });
70
+ return parseDuration(duration, `webhooks.retention.${key}`);
71
+ };
72
+ return {
73
+ sentMs: read("sent"),
74
+ deadMs: read("dead")
75
+ };
76
+ }
77
+ // src/queue-name.ts
78
+ /** The internal Queue that delivers every webhook. Its own module, so the Vite plugin reads it without the runtime. */
79
+ const webhooksQueueName = "vitehub-webhooks";
80
+ export { resolveWebhooksRetention as i, defineWebhook as n, isWebhookDefinition as r, webhooksQueueName as t };
@@ -0,0 +1,76 @@
1
+ import { RunFailedEventName } from "@vite-hub/runtime/internal/run-failed";
2
+ import { Duration } from "@vite-hub/runtime";
3
+ /** How a delivery is signed. Both use HMAC-SHA256 of the raw body with the secret. */
4
+ type WebhookSignature = "github" | "stripe";
5
+ /**
6
+ * An event that ViteHub sends by itself, with no `sendWebhook()` call: an Agent Invocation, a Workflow run, or a Schedule
7
+ * run that ended in failure with no retry left.
8
+ */
9
+ type WebhookEvent = RunFailedEventName;
10
+ /** What `defineWebhook()` accepts. */
11
+ interface WebhookOptions {
12
+ /**
13
+ * The name of the server variable that holds the receiver URL, such as `"T3_WEBHOOK_URL"`. It is a name, not the URL,
14
+ * because a URL often holds a token.
15
+ */
16
+ url: string;
17
+ /** The name of the server variable that holds the signing secret, such as `"T3_WEBHOOK_SECRET"`. */
18
+ secret: string;
19
+ /**
20
+ * `"github"` (default) sends `x-hub-signature-256: sha256=<hex>`. `"stripe"` sends
21
+ * `stripe-signature: t=<time>,v1=<hex>`. `verifyWebhook()` from `@vite-hub/env` checks both.
22
+ */
23
+ signature?: WebhookSignature;
24
+ /**
25
+ * Wait this long after the last send before one delivery, such as `"30m"`. Each send in the window replaces the body
26
+ * and restarts the wait. Sends with the same `key` collapse, and the key defaults to the webhook name. At most `"1d"`.
27
+ * Without it, each send is delivered at once.
28
+ */
29
+ debounce?: Duration;
30
+ /**
31
+ * Events that ViteHub sends to this webhook by itself: `"invocation.failed"`, `"workflow.failed"`, and
32
+ * `"schedule.failed"`. Each is sent once, when the run ends in failure with no retry left.
33
+ */
34
+ events?: readonly WebhookEvent[];
35
+ }
36
+ /** A webhook of `server/webhooks/<name>.ts`. */
37
+ interface WebhookDefinition {
38
+ readonly url: string;
39
+ readonly secret: string;
40
+ readonly signature: WebhookSignature;
41
+ /** The debounce in milliseconds. `0` delivers each send at once. */
42
+ readonly debounceMs: number;
43
+ /** The events that ViteHub sends to this webhook by itself. */
44
+ readonly events: readonly WebhookEvent[];
45
+ }
46
+ /**
47
+ * Defines a webhook: where ViteHub sends events, how it signs them, and how long it waits to collapse them. Default-export
48
+ * it from `server/webhooks/<name>.ts`, then call `sendWebhook("<name>", body)` from server code, or list `events` that
49
+ * ViteHub sends by itself.
50
+ *
51
+ * ```ts [server/webhooks/t3.ts]
52
+ * import { defineWebhook } from "@vite-hub/webhooks"
53
+ *
54
+ * export default defineWebhook({
55
+ * url: "T3_WEBHOOK_URL",
56
+ * secret: "T3_WEBHOOK_SECRET",
57
+ * debounce: "30m",
58
+ * })
59
+ * ```
60
+ */
61
+ declare function defineWebhook(options: WebhookOptions): WebhookDefinition;
62
+ /** How long Webhooks keeps finished deliveries, from when they finished. `false` keeps them. */
63
+ interface WebhooksRetention {
64
+ /** Sent and cancelled deliveries, inbox deliveries included. Default: `"7 days"`. */
65
+ sent?: Duration | false;
66
+ /** Dead deliveries, which people may still look into. Default: `"30 days"`. */
67
+ dead?: Duration | false;
68
+ }
69
+ /** The retention in milliseconds. `null` keeps the deliveries. */
70
+ interface ResolvedWebhooksRetention {
71
+ sentMs: number | null;
72
+ deadMs: number | null;
73
+ }
74
+ /** The internal Queue that delivers every webhook. Its own module, so the Vite plugin reads it without the runtime. */
75
+ declare const webhooksQueueName = "vitehub-webhooks";
76
+ export { WebhookOptions as a, defineWebhook as c, WebhookEvent as i, ResolvedWebhooksRetention as n, WebhookSignature as o, WebhookDefinition as r, WebhooksRetention as s, webhooksQueueName as t };