notifkit 0.1.10 → 0.1.12

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.
Files changed (81) hide show
  1. package/README.md +37 -1
  2. package/dashboard/dist/assets/{index-7mvXb4bS.js → index-Bsrmo9LE.js} +1 -1
  3. package/dashboard/dist/assets/index-s-SXGIwv.css +1 -0
  4. package/dashboard/dist/index.html +2 -2
  5. package/dist/bootstrap-omGPIBny.mjs +89 -0
  6. package/dist/bulk-C4hTcnLu.mjs +77 -0
  7. package/dist/index.d.mts +1160 -8886
  8. package/dist/index.mjs +2 -38
  9. package/dist/{main-C9s-2ArH.mjs → main-B-AZ-xoN.mjs} +49 -75
  10. package/dist/main-B5BwjIMu.mjs +811 -0
  11. package/dist/{main-B3iQrl3t.mjs → main-BU27VjDC.mjs} +149 -134
  12. package/dist/main-Bes11Ad3.mjs +312 -0
  13. package/dist/{main-BiFiOX9D.mjs → main-BtnGmyaT.mjs} +119 -112
  14. package/dist/{main-39DtKrX4.mjs → main-BxAeC_k6.mjs} +395 -184
  15. package/dist/{main-Dz2sUh3c.mjs → main-DAXO-MiH.mjs} +57 -54
  16. package/dist/{main-BgmT1MPe.mjs → main-DYGCl7Ja.mjs} +135 -79
  17. package/dist/{src-QiTu5e_a.mjs → src-CIPTzq9i.mjs} +1351 -661
  18. package/drizzle/0006_message_logs_redundant_indexes.sql +7 -0
  19. package/drizzle/0007_workflow_status_canceled.sql +3 -0
  20. package/drizzle/meta/_journal.json +14 -0
  21. package/package.json +21 -18
  22. package/scripts/create-admin.mjs +8 -1
  23. package/scripts/migrate.mjs +43 -0
  24. package/src/client.ts +15 -5
  25. package/src/config/index.ts +37 -3
  26. package/src/contracts/events/notification-ai-pending.ts +12 -0
  27. package/src/contracts/events/notification-delivered.ts +7 -0
  28. package/src/contracts/events/notification-dispatched.ts +21 -2
  29. package/src/contracts/events/notification-enriched.ts +16 -0
  30. package/src/contracts/events/notification-failed.ts +2 -0
  31. package/src/contracts/events/notification-requested.ts +2 -0
  32. package/src/contracts/registry.ts +2 -2
  33. package/src/contracts/sdk.ts +77 -29
  34. package/src/db/bulk.ts +132 -0
  35. package/src/db/index.ts +174 -7
  36. package/src/db/schema.ts +3 -50
  37. package/src/idempotency/index.ts +60 -6
  38. package/src/logger/index.ts +0 -12
  39. package/src/queue/index.ts +255 -76
  40. package/src/rate-limiter/index.ts +217 -16
  41. package/src/redis/index.ts +265 -0
  42. package/src/repositories/index.ts +171 -82
  43. package/src/server.ts +64 -41
  44. package/src/services/ai/main.ts +83 -70
  45. package/src/services/api/admin-static.ts +41 -12
  46. package/src/services/api/handlers.ts +357 -159
  47. package/src/services/api/http.ts +34 -7
  48. package/src/services/api/main.ts +104 -67
  49. package/src/services/api/router.ts +18 -5
  50. package/src/services/delivery/main.ts +495 -230
  51. package/src/services/delivery/throttle.ts +42 -59
  52. package/src/services/engine/main.ts +206 -152
  53. package/src/services/enricher/main.ts +155 -107
  54. package/src/services/events/main.ts +100 -55
  55. package/src/services/scheduler/main.ts +151 -79
  56. package/src/services/scheduler/send-gate.ts +117 -0
  57. package/src/services/workflow/main.ts +220 -100
  58. package/src/shared/batch-processor.ts +65 -34
  59. package/src/shared/dataloader.ts +58 -22
  60. package/src/shared/events.ts +3 -0
  61. package/src/shared/index.ts +0 -1
  62. package/src/shared/utils.ts +2 -47
  63. package/src/templates/index.ts +0 -67
  64. package/src/transport/index.ts +6 -0
  65. package/src/workers/bootstrap.ts +124 -0
  66. package/src/workers/index.ts +99 -24
  67. package/src/workflows/sdk.ts +2 -0
  68. package/dashboard/dist/assets/index-o7L-f3-c.css +0 -1
  69. package/dist/index.d.mts.map +0 -1
  70. package/dist/index.mjs.map +0 -1
  71. package/dist/main-39DtKrX4.mjs.map +0 -1
  72. package/dist/main-B3iQrl3t.mjs.map +0 -1
  73. package/dist/main-BM8DH3v3.mjs +0 -632
  74. package/dist/main-BM8DH3v3.mjs.map +0 -1
  75. package/dist/main-BgmT1MPe.mjs.map +0 -1
  76. package/dist/main-BiFiOX9D.mjs.map +0 -1
  77. package/dist/main-C9s-2ArH.mjs.map +0 -1
  78. package/dist/main-Cqo3rSb5.mjs +0 -224
  79. package/dist/main-Cqo3rSb5.mjs.map +0 -1
  80. package/dist/main-Dz2sUh3c.mjs.map +0 -1
  81. package/dist/src-QiTu5e_a.mjs.map +0 -1
@@ -0,0 +1,7 @@
1
+ -- Both indexes are strict prefixes of others on the same table:
2
+ -- message_logs_project_idx (project_id) <- every composite leading with project_id
3
+ -- task_idx (task_id) <- task_channel_attempt_uidx (task_id, ...)
4
+ -- message_logs takes two rows per delivered notification, so each index is
5
+ -- paid for on the hottest insert path in the system.
6
+ DROP INDEX IF EXISTS "message_logs_project_idx";--> statement-breakpoint
7
+ DROP INDEX IF EXISTS "task_idx";
@@ -0,0 +1,3 @@
1
+ -- WorkflowRepository.cancelInstance writes 'canceled', which the enum never
2
+ -- had, so every cancel failed with invalid_text_representation.
3
+ ALTER TYPE "public"."workflow_status" ADD VALUE IF NOT EXISTS 'canceled';
@@ -43,6 +43,20 @@
43
43
  "when": 1788781000000,
44
44
  "tag": "0005_admin_users",
45
45
  "breakpoints": true
46
+ },
47
+ {
48
+ "idx": 6,
49
+ "version": "7",
50
+ "when": 1790600000000,
51
+ "tag": "0006_message_logs_redundant_indexes",
52
+ "breakpoints": true
53
+ },
54
+ {
55
+ "idx": 7,
56
+ "version": "7",
57
+ "when": 1790700000000,
58
+ "tag": "0007_workflow_status_canceled",
59
+ "breakpoints": true
46
60
  }
47
61
  ]
48
62
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notifkit",
3
- "version": "0.1.10",
3
+ "version": "0.1.12",
4
4
  "description": "Self-hosted notification infrastructure. One call delivers to email, SMS, push, and webhook — routed by preference, quiet hours, and consent.",
5
5
  "license": "MIT",
6
6
  "author": "devkitshq",
@@ -51,37 +51,40 @@
51
51
  "dashboard/dist",
52
52
  "scripts/create-project.mjs",
53
53
  "scripts/create-admin.mjs",
54
+ "scripts/migrate.mjs",
54
55
  "README.md",
55
56
  "LICENSE"
56
57
  ],
57
58
  "bin": {
58
59
  "notifkit-create-project": "./scripts/create-project.mjs",
59
- "notifkit-create-admin": "./scripts/create-admin.mjs"
60
+ "notifkit-create-admin": "./scripts/create-admin.mjs",
61
+ "notifkit-migrate": "./scripts/migrate.mjs"
60
62
  },
61
63
  "scripts": {
62
64
  "build": "tsdown",
63
65
  "dev": "tsdown --watch",
64
66
  "create-project": "node scripts/create-project.mjs",
65
67
  "create-admin": "node scripts/create-admin.mjs",
68
+ "migrate": "node scripts/migrate.mjs",
66
69
  "build:dashboard": "npm --prefix dashboard run build",
67
70
  "test": "vitest run --coverage",
68
71
  "test:watch": "vitest",
69
72
  "lint": "eslint . --fix",
70
73
  "typecheck": "tsc --noEmit",
74
+ "typecheck:workspaces": "npm run typecheck --workspaces --if-present",
71
75
  "prepare": "husky",
72
- "prepublishOnly": "npm run typecheck && npm run build && npm run build:dashboard"
76
+ "prepublishOnly": "npm run typecheck && npm run build && npm run typecheck:workspaces && npm run build:dashboard"
73
77
  },
74
78
  "dependencies": {
75
- "ai": "^7.0.37",
76
- "dotenv": "^16.4.5",
77
- "drizzle-orm": "^0.45.2",
78
- "drizzle-zod": "^0.8.3",
79
- "ioredis": "^5.4.1",
80
- "pino": "^9.2.0",
81
- "pino-pretty": "^11.0.0",
82
- "postgres": "^3.4.4",
79
+ "ai": "^7.0.118",
80
+ "dotenv": "^18.0.4",
81
+ "drizzle-orm": "^0.45.3",
82
+ "ioredis": "^6.0.0",
83
+ "pino": "^10.3.1",
84
+ "pino-pretty": "^13.1.3",
85
+ "postgres": "^3.4.9",
83
86
  "prom-client": "^15.1.3",
84
- "zod": "^3.23.8"
87
+ "zod": "^4.6.5"
85
88
  },
86
89
  "devDependencies": {
87
90
  "@commitlint/cli": "^19.3.0",
@@ -90,15 +93,15 @@
90
93
  "@testcontainers/redis": "^12.0.4",
91
94
  "@types/node": "^22.0.0",
92
95
  "@types/supertest": "^7.2.1",
93
- "@typescript-eslint/eslint-plugin": "^8.0.0",
94
- "@typescript-eslint/parser": "^8.0.0",
96
+ "@typescript-eslint/eslint-plugin": "^8.70.1",
97
+ "@typescript-eslint/parser": "^8.70.1",
95
98
  "@vitest/coverage-v8": "^2.0.0",
96
- "drizzle-kit": "^0.31.10",
99
+ "drizzle-kit": "^0.31.11",
97
100
  "eslint": "^9.0.0",
98
101
  "husky": "^9.0.11",
99
- "lint-staged": "^15.2.5",
100
- "prettier": "^3.3.0",
101
- "supertest": "^7.2.2",
102
+ "lint-staged": "^15.5.2",
103
+ "prettier": "^3.9.9",
104
+ "supertest": "^7.3.0",
102
105
  "testcontainers": "^12.0.4",
103
106
  "tsdown": "^0.22.14",
104
107
  "typescript": "^5.8.3",
@@ -36,7 +36,14 @@ if (!email || !password) {
36
36
 
37
37
  const databaseUrl =
38
38
  process.env.DATABASE_URL || "postgres://platform:platform@localhost:5432/notifkit";
39
- const sql = postgres(databaseUrl);
39
+ const schema = (process.env.DB_SCHEMA || "public").trim();
40
+ if (!/^[a-z_][a-z0-9_]{0,62}$/.test(schema)) {
41
+ console.error(`Invalid DB_SCHEMA "${schema}": must be a lowercase PostgreSQL identifier.`);
42
+ process.exit(1);
43
+ }
44
+ const sql = postgres(databaseUrl, {
45
+ connection: schema === "public" ? {} : { search_path: `"${schema}"` },
46
+ });
40
47
 
41
48
  try {
42
49
  const passwordHash = await hashPassword(password);
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Apply notifkit's database migrations.
4
+ *
5
+ * Reads DATABASE_URL and DB_SCHEMA (from the environment or .env) and runs the
6
+ * same migrations NotifkitServer runs on start-up with autoMigrate, into the
7
+ * same schema. Safe to run repeatedly: already-applied migrations are skipped.
8
+ * Exits non-zero if anything fails.
9
+ *
10
+ * Usage:
11
+ * DATABASE_URL=postgres://user:pass@host:5432/db npx notifkit-migrate
12
+ * DATABASE_URL=... DB_SCHEMA=notifications npx notifkit-migrate
13
+ * node scripts/migrate.mjs
14
+ */
15
+
16
+ import { config } from "dotenv";
17
+ import { resolve } from "node:path";
18
+
19
+ config({ path: resolve(process.cwd(), ".env") });
20
+
21
+ if (!process.env.DATABASE_URL) {
22
+ console.error("Usage: DATABASE_URL=postgres://... [DB_SCHEMA=schema] npx notifkit-migrate");
23
+ process.exit(1);
24
+ }
25
+
26
+ try {
27
+ // Imported after .env is loaded: the package reads DB_SCHEMA from the environment.
28
+ const { migrateDatabase } = await import("../dist/index.mjs");
29
+ const schema = await migrateDatabase({ url: process.env.DATABASE_URL });
30
+ console.log(`Migrations applied to schema "${schema}".`);
31
+ } catch (err) {
32
+ console.error(`Failed to run migrations: ${describe(err)}`);
33
+ process.exitCode = 1;
34
+ }
35
+
36
+ /** drizzle wraps driver errors as "Failed query: ..."; the cause says what actually went wrong. */
37
+ function describe(err) {
38
+ const parts = [err.message];
39
+ if (err.fields) parts.push(JSON.stringify(err.fields));
40
+ const cause = err.cause;
41
+ if (cause) parts.push(`cause: ${cause.message || cause.code || String(cause)}`);
42
+ return parts.join("\n ");
43
+ }
package/src/client.ts CHANGED
@@ -22,6 +22,7 @@ import type {
22
22
  SuppressionRecord,
23
23
  ProjectRecord,
24
24
  ProjectKeyRecord,
25
+ CreatedProjectKeyRecord,
25
26
  SystemHealthRecord,
26
27
  SystemMetricsRecord,
27
28
  DLQMessageRecord,
@@ -61,10 +62,17 @@ export class NotifkitClient {
61
62
  return undefined as T;
62
63
  }
63
64
 
64
- const data = await res.json();
65
+ const text = await res.text();
66
+ let data: unknown;
67
+ try {
68
+ data = text ? JSON.parse(text) : undefined;
69
+ } catch {
70
+ // Not JSON: an HTML error page, or a proxy in front of the API.
71
+ data = undefined;
72
+ }
65
73
  if (!res.ok) {
66
- const errorMsg =
67
- (data as any).message || (data as any).error || `Request failed with status ${res.status}`;
74
+ const body = data as { message?: string; error?: string } | undefined;
75
+ const errorMsg = body?.message || body?.error || `Request failed with status ${res.status}`;
68
76
  throw new Error(errorMsg);
69
77
  }
70
78
  return data as T;
@@ -285,7 +293,7 @@ export class NotifkitClient {
285
293
  async createProjectKey(
286
294
  id: string,
287
295
  input?: { role?: "admin" | "read_only" },
288
- ): Promise<ProjectKeyRecord> {
296
+ ): Promise<CreatedProjectKeyRecord> {
289
297
  return this.request(`/v1/projects/${encodeURIComponent(id)}/keys`, "POST", input || {});
290
298
  }
291
299
 
@@ -472,7 +480,9 @@ export class NotifkitClient {
472
480
  }
473
481
 
474
482
  /** Replay a dead-letter queue message. */
475
- async replayDLQMessage(id: string): Promise<{ success: boolean; replayedId: string }> {
483
+ async replayDLQMessage(
484
+ id: string,
485
+ ): Promise<{ success: boolean; replayedId: string; stream: string }> {
476
486
  return this.request("/v1/dlq/replay", "POST", { id });
477
487
  }
478
488
 
@@ -3,7 +3,7 @@ import { resolve } from "node:path";
3
3
  import { z, type ZodTypeAny } from "zod";
4
4
  import type { LanguageModel } from "ai";
5
5
 
6
- import { ValidationError } from "@/index.js";
6
+ import { ValidationError } from "@/shared/index.js";
7
7
 
8
8
  export function loadEnv(path?: string): void {
9
9
  const envPath = path ?? resolve(process.cwd(), ".env");
@@ -47,8 +47,39 @@ export const baseConfigSchema = z.object({
47
47
  ADMIN_PASSWORD: z.string().trim().min(6).optional(),
48
48
  ADMIN_USERNAME: z.string().trim().optional(),
49
49
  WORKER_CONCURRENCY: z.coerce.number().int().min(1).default(10),
50
- QUEUE_MAX_LEN: z.coerce.number().int().min(1).default(10000000),
50
+ /** In-flight sends per delivery worker. Defaults to WORKER_CONCURRENCY. */
51
+ DELIVERY_CONCURRENCY: z.coerce.number().int().min(1).optional(),
52
+ /**
53
+ * When enricher, engine and delivery run in the same process, hand
54
+ * single-recipient notifications from stage to stage in memory instead of
55
+ * through the enriched/outbound streams. See `NotifkitOptions.fusedPipeline`.
56
+ */
57
+ PIPELINE_FUSED: z
58
+ .string()
59
+ .optional()
60
+ .transform((v) => v === "true" || v === "1"),
61
+ QUEUE_MAX_LEN: z.coerce.number().int().min(1).default(100000),
62
+ /**
63
+ * How long the pipeline remembers it handled a message, so a redelivery
64
+ * after a crash is not sent twice. It only has to outlast redelivery (about
65
+ * ten minutes) plus however far behind the streams run; a caller's own
66
+ * X-Idempotency-Key is always kept for 24 hours regardless. These markers
67
+ * are most of Redis memory under load, so the cost of a longer window is
68
+ * real: a few hundred bytes per message for as long as it lasts.
69
+ */
70
+ IDEMPOTENCY_TTL_SECONDS: z.coerce.number().int().min(60).default(3600),
51
71
  DB_MAX_CONNECTIONS: z.coerce.number().int().min(1).default(2),
72
+ /**
73
+ * PostgreSQL schema that holds notifkit's tables and enum types. Defaults to
74
+ * `public`. Any other value makes migrations create every object in that
75
+ * schema and sets `search_path` on every connection, so notifkit can share a
76
+ * database with an application that owns `public`.
77
+ */
78
+ DB_SCHEMA: z
79
+ .string()
80
+ .trim()
81
+ .regex(/^[a-z_][a-z0-9_]{0,62}$/, "must be a lowercase PostgreSQL identifier")
82
+ .default("public"),
52
83
  LOG_FLUSH_INTERVAL_MS: z.coerce.number().int().min(50).default(500),
53
84
  LOG_BUFFER_MAX_SIZE: z.coerce.number().int().min(100).default(5000),
54
85
  SEGMENT_MAX_USERS: z.coerce.number().int().min(1).default(10000),
@@ -69,7 +100,10 @@ export const baseConfigSchema = z.object({
69
100
  * When true, trusts X-Forwarded-For headers from reverse proxies for client IP resolution.
70
101
  * Defaults to false to prevent client-spoofed headers from bypassing rate limits.
71
102
  */
72
- TRUST_PROXY: z.coerce.boolean().default(false),
103
+ TRUST_PROXY: z
104
+ .string()
105
+ .optional()
106
+ .transform((v) => v === "true" || v === "1"),
73
107
  /**
74
108
  * Comma-separated list of allowed origins for CORS on session-authenticated admin routes.
75
109
  */
@@ -14,5 +14,17 @@ export const NotificationAiPendingPayloadSchema = z.object({
14
14
  aiPrompts: z.record(z.string(), z.string()),
15
15
  scheduledAt: z.string().datetime().optional(),
16
16
  fallbackChain: z.array(NotificationChannelSchema).optional(),
17
+ /**
18
+ * The task id the engine assigned. Stable across replays, so a re-run of
19
+ * this event dispatches the same task — which delivery's lease then sends
20
+ * once — rather than a fresh one.
21
+ */
22
+ taskId: z.string().min(1).optional(),
23
+ /** The contact address the engine resolved and cleared against suppressions. */
24
+ destination: z.string().min(1).optional(),
25
+ /** Headers for the provider, e.g. one-click unsubscribe. */
26
+ deliveryHeaders: z.record(z.string(), z.string()).optional(),
27
+ campaignId: z.string().min(1).max(128).optional(),
28
+ workflowInstanceId: z.string().uuid().optional(),
17
29
  });
18
30
  export type NotificationAiPendingPayload = z.infer<typeof NotificationAiPendingPayloadSchema>;
@@ -13,5 +13,12 @@ export const NotificationDeliveredPayloadSchema = z.object({
13
13
  workflowInstanceId: z.string().uuid().optional(),
14
14
  /** Campaign this message belongs to, carried from the originating request. */
15
15
  campaignId: z.string().min(1).max(128).optional(),
16
+ attempt: z.number().int().positive().optional(),
17
+ /**
18
+ * Set when this event also stands in for the attempt's
19
+ * `notification.dispatched` log entry (see DeliveryWorker): the send finished
20
+ * quickly enough that both were published as one stream entry.
21
+ */
22
+ dispatchedAt: z.string().datetime().optional(),
16
23
  });
17
24
  export type NotificationDeliveredPayload = z.infer<typeof NotificationDeliveredPayloadSchema>;
@@ -34,12 +34,31 @@ export const NotificationDispatchedPayloadSchema = z.object({
34
34
  templateVariables: z.record(z.string(), z.unknown()).default({}),
35
35
  aiPrompts: z.record(z.string(), z.string()).optional(),
36
36
  recipient: RecipientProfileSchema.optional(),
37
- renderedContent: RenderedContentSchema,
37
+ /**
38
+ * Absent on tasks the engine dispatches: delivery renders `templateId` with
39
+ * `templateVariables` just before sending, so the rendered body never rides
40
+ * through the outbound stream or sits in a scheduled payload. The AI worker
41
+ * still sends it pre-rendered, since its variables are generated.
42
+ */
43
+ renderedContent: RenderedContentSchema.optional(),
38
44
  destination: z.string().min(1).optional(),
39
45
  deliveryOptions: DeliveryOptionsSchema,
40
46
  fallbackChain: z.array(NotificationChannelSchema).optional(),
41
47
  throttleAttemptCount: z.number().int().nonnegative().optional(),
48
+ /**
49
+ * Provider attempts that already failed. Delivery re-queues a failed send
50
+ * through the scheduler until this reaches `deliveryOptions.maxAttempts`.
51
+ */
52
+ deliveryAttemptCount: z.number().int().nonnegative().optional(),
42
53
  /** Campaign this message belongs to, carried from the originating request. */
43
54
  campaignId: z.string().min(1).max(128).optional(),
55
+ /** Workflow instance whose step sent this, recorded on the delivery log. */
56
+ workflowInstanceId: z.string().uuid().optional(),
44
57
  });
45
- export type NotificationDispatchedPayload = z.infer<typeof NotificationDispatchedPayloadSchema>;
58
+ /** A `notification.dispatched` task as it travels on the outbound stream. */
59
+ export type DispatchedTaskPayload = z.infer<typeof NotificationDispatchedPayloadSchema>;
60
+
61
+ /** A task as a transport receives it: always rendered. */
62
+ export type NotificationDispatchedPayload = DispatchedTaskPayload & {
63
+ renderedContent: RenderedContent;
64
+ };
@@ -40,7 +40,23 @@ export const NotificationEnrichedPayloadSchema = z.object({
40
40
  aiPrompts: z.record(z.string(), z.string()).optional(),
41
41
  scheduledAt: z.string().datetime().optional(),
42
42
  fallbackChain: z.array(NotificationChannelSchema).optional(),
43
+ /**
44
+ * The contact the enricher resolved this message to, and its address. When
45
+ * present the engine sends to exactly this contact instead of re-reading the
46
+ * user's contacts. Absent on events from delivery's channel fallback and the
47
+ * AI worker, which carry a recipient but no resolved contact.
48
+ */
49
+ contactId: z.string().min(1).optional(),
50
+ destination: z.string().min(1).optional(),
43
51
  /** Campaign this message belongs to, carried from the originating request. */
44
52
  campaignId: z.string().min(1).max(128).optional(),
53
+ /** Workflow instance whose step sent this, carried to the delivery log. */
54
+ workflowInstanceId: z.string().uuid().optional(),
55
+ /**
56
+ * Set on delivery's channel fallback. The notification was counted against
57
+ * the user's throttle when it was first sent; counting it again per channel
58
+ * it falls back through would drop the very send meant to reach them.
59
+ */
60
+ throttleCounted: z.boolean().optional(),
45
61
  });
46
62
  export type NotificationEnrichedPayload = z.infer<typeof NotificationEnrichedPayloadSchema>;
@@ -15,5 +15,7 @@ export const NotificationFailedPayloadSchema = z.object({
15
15
  workflowInstanceId: z.string().uuid().optional(),
16
16
  /** Campaign this message belongs to, carried from the originating request. */
17
17
  campaignId: z.string().min(1).max(128).optional(),
18
+ /** See NotificationDeliveredPayload.dispatchedAt. */
19
+ dispatchedAt: z.string().datetime().optional(),
18
20
  });
19
21
  export type NotificationFailedPayload = z.infer<typeof NotificationFailedPayloadSchema>;
@@ -32,5 +32,7 @@ export const NotificationRequestedPayloadSchema = z.object({
32
32
  * reported on afterwards. Carried unchanged to the delivery log.
33
33
  */
34
34
  campaignId: z.string().min(1).max(128).optional(),
35
+ /** Set by the workflow worker on a step's notify, carried to the delivery log. */
36
+ workflowInstanceId: z.string().uuid().optional(),
35
37
  });
36
38
  export type NotificationRequestedPayload = z.infer<typeof NotificationRequestedPayloadSchema>;
@@ -3,7 +3,7 @@ import type { NotificationRequestedPayload } from "./events/notification-request
3
3
  import type { NotificationCreatedPayload } from "./events/notification-created.js";
4
4
  import type { NotificationEnrichedPayload } from "./events/notification-enriched.js";
5
5
  import type { NotificationScheduledPayload } from "./events/notification-scheduled.js";
6
- import type { NotificationDispatchedPayload } from "./events/notification-dispatched.js";
6
+ import type { DispatchedTaskPayload } from "./events/notification-dispatched.js";
7
7
  import type { NotificationDeliveredPayload } from "./events/notification-delivered.js";
8
8
  import type { NotificationFailedPayload } from "./events/notification-failed.js";
9
9
  import type { NotificationSkippedPayload } from "./events/notification-skipped.js";
@@ -26,7 +26,7 @@ export interface EventPayloadMap {
26
26
  "notification.created": NotificationCreatedPayload;
27
27
  "notification.enriched": NotificationEnrichedPayload;
28
28
  "notification.scheduled": NotificationScheduledPayload;
29
- "notification.dispatched": NotificationDispatchedPayload;
29
+ "notification.dispatched": DispatchedTaskPayload;
30
30
  "notification.delivered": NotificationDeliveredPayload;
31
31
  "notification.failed": NotificationFailedPayload;
32
32
  "notification.skipped": NotificationSkippedPayload;
@@ -110,12 +110,12 @@ export const TemplateSchema = z.object({
110
110
  content: z.record(z.string(), z.unknown()),
111
111
  aiPrompts: z.record(z.string(), z.string()).optional(),
112
112
  });
113
- export type TemplateInput = z.infer<typeof TemplateSchema>;
113
+ export type TemplateInput = z.input<typeof TemplateSchema>;
114
114
 
115
115
  export const SyncTemplatesSchema = z.object({
116
116
  templates: z.array(TemplateSchema).min(1),
117
117
  });
118
- export type SyncTemplatesInput = z.infer<typeof SyncTemplatesSchema>;
118
+ export type SyncTemplatesInput = z.input<typeof SyncTemplatesSchema>;
119
119
 
120
120
  // ─── notify() ─────────────────────────────────────────────────────────────────
121
121
 
@@ -216,7 +216,7 @@ export const TriggerWorkflowSchema = z.object({
216
216
  input: z.record(z.string(), z.unknown()).optional(),
217
217
  user: z.union([z.string().min(1), InlineUserSchema]).optional(),
218
218
  });
219
- export type TriggerWorkflowInput = z.infer<typeof TriggerWorkflowSchema>;
219
+ export type TriggerWorkflowInput = z.input<typeof TriggerWorkflowSchema>;
220
220
 
221
221
  // ─── Events ───────────────────────────────────────────────────────────────────
222
222
 
@@ -241,6 +241,12 @@ export const WorkflowStepSchema = z.discriminatedUnion("action", [
241
241
  options: z
242
242
  .object({
243
243
  timeout: z.string().optional(), // e.g. "24h"
244
+ /**
245
+ * Fields the event must carry to wake this instance, e.g.
246
+ * `{ userId: "u1" }`. Without it any event of that name in the project
247
+ * wakes every instance waiting on it.
248
+ */
249
+ match: z.record(z.string(), z.unknown()).optional(),
244
250
  })
245
251
  .optional(),
246
252
  }),
@@ -251,7 +257,7 @@ export const CreateWorkflowSchema = z.object({
251
257
  name: z.string().min(1),
252
258
  steps: z.array(WorkflowStepSchema).min(1),
253
259
  });
254
- export type CreateWorkflowInput = z.infer<typeof CreateWorkflowSchema>;
260
+ export type CreateWorkflowInput = z.input<typeof CreateWorkflowSchema>;
255
261
 
256
262
  // ─── Projects ─────────────────────────────────────────────────────────────────
257
263
 
@@ -291,7 +297,8 @@ export interface UserResponse extends UserProfileResponse {
291
297
 
292
298
  export interface UserDetailResponse extends UserResponse {
293
299
  contacts: UserContactResponse[];
294
- recentLogs?: unknown[];
300
+ /** The 50 most recent delivery-log rows for this user's addresses. */
301
+ logs: NotificationLogRecord[];
295
302
  }
296
303
 
297
304
  export interface WorkflowDefinitionRecord {
@@ -302,30 +309,53 @@ export interface WorkflowDefinitionRecord {
302
309
  updatedAt?: string;
303
310
  }
304
311
 
312
+ export interface WorkflowStepRecord {
313
+ id: string;
314
+ instanceId: string;
315
+ stepIndex: string;
316
+ action: "notify" | "wait" | "waitForEvent" | "run" | string;
317
+ output: unknown;
318
+ error: string | null;
319
+ createdAt: string;
320
+ }
321
+
322
+ export interface WorkflowWaiterRecord {
323
+ id: string;
324
+ instanceId: string;
325
+ eventName: string;
326
+ matchCriteria: Record<string, unknown>;
327
+ expiresAt: string;
328
+ createdAt: string;
329
+ }
330
+
305
331
  export interface WorkflowInstanceRecord {
306
332
  id: string;
333
+ projectId: string;
307
334
  name: string;
308
- status: string;
309
- currentStepIndex: number;
310
- input?: Record<string, unknown>;
311
- output?: Record<string, unknown>;
335
+ status: "pending" | "running" | "completed" | "failed" | "canceled";
336
+ input?: Record<string, unknown> | null;
312
337
  createdAt: string;
313
338
  updatedAt: string;
339
+ steps: WorkflowStepRecord[];
340
+ waiters: WorkflowWaiterRecord[];
314
341
  }
315
342
 
343
+ /** One row of the delivery log, as the API returns it. */
316
344
  export interface NotificationLogRecord {
317
345
  id: string;
318
- notificationId: string;
319
- taskId?: string;
346
+ projectId: string;
347
+ taskId: string;
348
+ providerMessageId: string | null;
349
+ templateId: string | null;
350
+ workflowInstanceId: string | null;
320
351
  channel: string;
321
- target?: string;
352
+ attempt: number;
353
+ /** `dispatched`, `attempt`, or an engagement event such as `opened`. */
354
+ kind: string;
322
355
  status: string;
323
- templateId?: string;
324
- campaign?: string;
325
- createdAt: string;
326
- dispatchedAt?: string;
327
- error?: string;
328
- metadata?: Record<string, unknown>;
356
+ campaignId: string | null;
357
+ metadata: Record<string, unknown> | null;
358
+ timestamp: string;
329
359
  }
330
360
 
331
361
  export interface TemplateRecordResponse {
@@ -338,9 +368,12 @@ export interface TemplateRecordResponse {
338
368
 
339
369
  export interface SuppressionRecord {
340
370
  id: string;
371
+ projectId: string;
341
372
  channel: string;
342
373
  target: string;
343
374
  reason: string;
375
+ source: string | null;
376
+ taskId: string | null;
344
377
  createdAt: string;
345
378
  }
346
379
 
@@ -353,30 +386,45 @@ export interface ProjectRecord {
353
386
  createdAt: string;
354
387
  }
355
388
 
389
+ /** A key as listed: the secret itself is only ever returned once, on creation. */
356
390
  export interface ProjectKeyRecord {
357
391
  id: string;
358
- apiKey: string;
359
- role: string;
392
+ role: "admin" | "read_only";
360
393
  createdAt: string;
361
394
  }
362
395
 
396
+ export interface CreatedProjectKeyRecord {
397
+ id: string;
398
+ apiKey: string;
399
+ role: "admin" | "read_only";
400
+ }
401
+
363
402
  export interface SystemHealthRecord {
364
- status: string;
365
- timestamp: string;
366
- redis?: { status: string };
367
- db?: { status: string };
368
- workers?: Record<string, unknown>;
403
+ status: "healthy" | "degraded";
404
+ redis: { ok: boolean; latencyMs: number };
405
+ db: { ok: boolean; latencyMs: number };
406
+ /** Each worker's last heartbeat, or `{ status: "unknown" }` when none arrived. */
407
+ workers: Record<string, Record<string, unknown>>;
369
408
  }
370
409
 
371
410
  export interface SystemMetricsRecord {
372
- queues: Record<string, number>;
373
- throughput?: Record<string, unknown>;
411
+ /** Unconsumed backlog per stream. Empty for project-scoped callers. */
412
+ streams: Record<string, number>;
413
+ deliveryStats: {
414
+ total: number;
415
+ delivered: number;
416
+ failed: number;
417
+ successRate: number;
418
+ };
374
419
  }
375
420
 
376
421
  export interface DLQMessageRecord {
377
422
  id: string;
378
- stream: string;
423
+ eventType: string;
379
424
  payload: Record<string, unknown>;
380
- error?: string;
425
+ /** Why the message was dead-lettered. */
426
+ error: string;
381
427
  timestamp: string;
428
+ /** The stream it failed on, where a replay puts it back. */
429
+ originalStream?: string;
382
430
  }