@venturekit/notify 0.0.0-dev.20260507015349

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 (75) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +304 -0
  3. package/dist/admin/index.d.ts +88 -0
  4. package/dist/admin/index.d.ts.map +1 -0
  5. package/dist/admin/index.js +105 -0
  6. package/dist/admin/index.js.map +1 -0
  7. package/dist/bounce-handler.d.ts +65 -0
  8. package/dist/bounce-handler.d.ts.map +1 -0
  9. package/dist/bounce-handler.js +171 -0
  10. package/dist/bounce-handler.js.map +1 -0
  11. package/dist/client.d.ts +113 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +213 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/dispatcher.d.ts +95 -0
  16. package/dist/dispatcher.d.ts.map +1 -0
  17. package/dist/dispatcher.js +251 -0
  18. package/dist/dispatcher.js.map +1 -0
  19. package/dist/index.d.ts +60 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +66 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/providers/email-noop.d.ts +30 -0
  24. package/dist/providers/email-noop.d.ts.map +1 -0
  25. package/dist/providers/email-noop.js +39 -0
  26. package/dist/providers/email-noop.js.map +1 -0
  27. package/dist/providers/email-ses.d.ts +39 -0
  28. package/dist/providers/email-ses.d.ts.map +1 -0
  29. package/dist/providers/email-ses.js +114 -0
  30. package/dist/providers/email-ses.js.map +1 -0
  31. package/dist/providers/index.d.ts +20 -0
  32. package/dist/providers/index.d.ts.map +1 -0
  33. package/dist/providers/index.js +20 -0
  34. package/dist/providers/index.js.map +1 -0
  35. package/dist/providers/push-noop.d.ts +12 -0
  36. package/dist/providers/push-noop.d.ts.map +1 -0
  37. package/dist/providers/push-noop.js +30 -0
  38. package/dist/providers/push-noop.js.map +1 -0
  39. package/dist/providers/sms-noop.d.ts +21 -0
  40. package/dist/providers/sms-noop.d.ts.map +1 -0
  41. package/dist/providers/sms-noop.js +42 -0
  42. package/dist/providers/sms-noop.js.map +1 -0
  43. package/dist/providers/types.d.ts +95 -0
  44. package/dist/providers/types.d.ts.map +1 -0
  45. package/dist/providers/types.js +40 -0
  46. package/dist/providers/types.js.map +1 -0
  47. package/dist/providers/whatsapp-meta.d.ts +63 -0
  48. package/dist/providers/whatsapp-meta.d.ts.map +1 -0
  49. package/dist/providers/whatsapp-meta.js +160 -0
  50. package/dist/providers/whatsapp-meta.js.map +1 -0
  51. package/dist/store/index.d.ts +6 -0
  52. package/dist/store/index.d.ts.map +1 -0
  53. package/dist/store/index.js +5 -0
  54. package/dist/store/index.js.map +1 -0
  55. package/dist/store/postgres.d.ts +36 -0
  56. package/dist/store/postgres.d.ts.map +1 -0
  57. package/dist/store/postgres.js +354 -0
  58. package/dist/store/postgres.js.map +1 -0
  59. package/dist/store/types.d.ts +139 -0
  60. package/dist/store/types.d.ts.map +1 -0
  61. package/dist/store/types.js +14 -0
  62. package/dist/store/types.js.map +1 -0
  63. package/dist/templates/registry.d.ts +55 -0
  64. package/dist/templates/registry.d.ts.map +1 -0
  65. package/dist/templates/registry.js +94 -0
  66. package/dist/templates/registry.js.map +1 -0
  67. package/dist/types.d.ts +214 -0
  68. package/dist/types.d.ts.map +1 -0
  69. package/dist/types.js +12 -0
  70. package/dist/types.js.map +1 -0
  71. package/migrations/vk_notify_001_init.sql +109 -0
  72. package/package.json +109 -0
  73. package/runtime/bounce-handler-stub.ts +35 -0
  74. package/runtime/dispatcher-stub.ts +63 -0
  75. package/runtime/tsconfig.json +19 -0
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @venturekit/notify — WhatsApp Cloud API provider (Meta direct)
3
+ *
4
+ * Targets the Graph API at `graph.facebook.com/{apiVersion}/{phoneNumberId}/messages`.
5
+ * Two message shapes are supported in Phase 1:
6
+ *
7
+ * - **Template message** — required for messages outside the 24-hour
8
+ * customer-service window. Driven by `RenderedMessage.whatsapp.metaTemplateName`
9
+ * + `whatsapp.languageCode` + `whatsapp.components`. The template
10
+ * itself is configured in Meta Business Manager and pre-approved by
11
+ * Meta — there is no way to send arbitrary content cold.
12
+ * - **Text message** — only valid inside the 24h session window
13
+ * (recipient messaged the business in the last 24h). Driven by the
14
+ * shared `RenderedMessage.text`. Useful for 2-way replies; Phase 1
15
+ * does not enforce session-window detection — the caller decides
16
+ * based on conversation context, the provider just forwards.
17
+ *
18
+ * The Meta access token is stored in Secrets Manager. The dispatcher
19
+ * fetches it once per cold start and caches it across sends.
20
+ */
21
+ import { type NotifyProvider } from './types.js';
22
+ /** Construction options for {@link createMetaWhatsAppProvider}. */
23
+ export interface MetaWhatsAppProviderConfig {
24
+ /** Meta Phone Number ID (assigned in Meta Business Suite). */
25
+ phoneNumberId: string;
26
+ /** Graph API version, default `'v21.0'`. */
27
+ apiVersion?: string;
28
+ /**
29
+ * Token resolver. Called once per cold start. Common implementations:
30
+ * - `() => process.env.META_WA_TOKEN!` — token injected as env var
31
+ * (development only — env vars are visible in CloudFormation).
32
+ * - `createSecretsTokenResolver(secretArn)` — fetch from Secrets
33
+ * Manager (default in production; see `secrets-token-resolver.ts`).
34
+ */
35
+ tokenResolver: () => Promise<string>;
36
+ /**
37
+ * Optional `fetch` override — useful for tests. Defaults to the
38
+ * global `fetch` available in Node 18+.
39
+ */
40
+ fetch?: typeof fetch;
41
+ }
42
+ /**
43
+ * Create the Meta WhatsApp Cloud API provider.
44
+ */
45
+ export declare function createMetaWhatsAppProvider(config: MetaWhatsAppProviderConfig): NotifyProvider;
46
+ /**
47
+ * Build a token resolver that reads from AWS Secrets Manager.
48
+ * Memoizes the secret value per cold start.
49
+ *
50
+ * Lazy-imports `@aws-sdk/client-secrets-manager` so projects that don't
51
+ * use WhatsApp don't pay the SDK cost at cold start.
52
+ */
53
+ export declare function createSecretsTokenResolver(opts: {
54
+ /** Secret ARN (`arn:aws:secretsmanager:…`). */
55
+ secretArn: string;
56
+ /** Secret JSON key (default: `'token'`). The secret value is parsed
57
+ * as JSON and the named field returned; pass `undefined` to use the
58
+ * raw secret string. */
59
+ jsonKey?: string;
60
+ /** AWS region (default: `process.env.AWS_REGION ?? 'us-east-1'`). */
61
+ region?: string;
62
+ }): () => Promise<string>;
63
+ //# sourceMappingURL=whatsapp-meta.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whatsapp-meta.d.ts","sourceRoot":"","sources":["../../src/providers/whatsapp-meta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAGL,KAAK,cAAc,EAGpB,MAAM,YAAY,CAAC;AAEpB,mEAAmE;AACnE,MAAM,WAAW,0BAA0B;IACzC,8DAA8D;IAC9D,aAAa,EAAE,MAAM,CAAC;IACtB,4CAA4C;IAC5C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;OAMG;IACH,aAAa,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IACrC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,0BAA0B,GACjC,cAAc,CAoHhB;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE;IAC/C,+CAA+C;IAC/C,SAAS,EAAE,MAAM,CAAC;IAClB;;6BAEyB;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qEAAqE;IACrE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,CA2CxB"}
@@ -0,0 +1,160 @@
1
+ /**
2
+ * @venturekit/notify — WhatsApp Cloud API provider (Meta direct)
3
+ *
4
+ * Targets the Graph API at `graph.facebook.com/{apiVersion}/{phoneNumberId}/messages`.
5
+ * Two message shapes are supported in Phase 1:
6
+ *
7
+ * - **Template message** — required for messages outside the 24-hour
8
+ * customer-service window. Driven by `RenderedMessage.whatsapp.metaTemplateName`
9
+ * + `whatsapp.languageCode` + `whatsapp.components`. The template
10
+ * itself is configured in Meta Business Manager and pre-approved by
11
+ * Meta — there is no way to send arbitrary content cold.
12
+ * - **Text message** — only valid inside the 24h session window
13
+ * (recipient messaged the business in the last 24h). Driven by the
14
+ * shared `RenderedMessage.text`. Useful for 2-way replies; Phase 1
15
+ * does not enforce session-window detection — the caller decides
16
+ * based on conversation context, the provider just forwards.
17
+ *
18
+ * The Meta access token is stored in Secrets Manager. The dispatcher
19
+ * fetches it once per cold start and caches it across sends.
20
+ */
21
+ import { ProviderHardError, ProviderSendError, } from './types.js';
22
+ /**
23
+ * Create the Meta WhatsApp Cloud API provider.
24
+ */
25
+ export function createMetaWhatsAppProvider(config) {
26
+ const apiVersion = config.apiVersion ?? 'v21.0';
27
+ const fetchImpl = config.fetch ?? fetch;
28
+ let cachedToken = null;
29
+ async function getToken() {
30
+ if (cachedToken)
31
+ return cachedToken;
32
+ cachedToken = await config.tokenResolver();
33
+ if (!cachedToken) {
34
+ throw new ProviderHardError('Meta WhatsApp provider: token resolver returned empty string');
35
+ }
36
+ return cachedToken;
37
+ }
38
+ return {
39
+ channel: 'whatsapp',
40
+ name: 'meta-cloud',
41
+ async send(request) {
42
+ const { to, message, notificationId } = request;
43
+ // Address must be E.164 minus the leading `+` for the Graph API.
44
+ // We accept either format on input and normalize here so callers
45
+ // don't have to remember the difference between the SMS-style
46
+ // address (with `+`) and the Graph-API-style address (without).
47
+ const normalizedTo = to.startsWith('+') ? to.slice(1) : to;
48
+ const wa = message.whatsapp;
49
+ const isTemplate = !!wa?.metaTemplateName && !!wa.languageCode;
50
+ const body = isTemplate
51
+ ? {
52
+ messaging_product: 'whatsapp',
53
+ to: normalizedTo,
54
+ type: 'template',
55
+ template: {
56
+ name: wa.metaTemplateName,
57
+ language: { code: wa.languageCode },
58
+ components: wa.components ?? [],
59
+ },
60
+ biz_opaque_callback_data: notificationId,
61
+ }
62
+ : {
63
+ messaging_product: 'whatsapp',
64
+ to: normalizedTo,
65
+ type: 'text',
66
+ text: { body: message.text, preview_url: false },
67
+ biz_opaque_callback_data: notificationId,
68
+ };
69
+ const url = `https://graph.facebook.com/${apiVersion}/${config.phoneNumberId}/messages`;
70
+ let response;
71
+ try {
72
+ response = await fetchImpl(url, {
73
+ method: 'POST',
74
+ headers: {
75
+ Authorization: `Bearer ${await getToken()}`,
76
+ 'Content-Type': 'application/json',
77
+ },
78
+ body: JSON.stringify(body),
79
+ });
80
+ }
81
+ catch (err) {
82
+ // Network-level failure (DNS, connection reset, …) — transient.
83
+ throw new ProviderSendError(`Meta WhatsApp send failed (network error)`, err);
84
+ }
85
+ if (!response.ok) {
86
+ const text = await response.text().catch(() => '');
87
+ // Graph API returns structured errors:
88
+ // { error: { code, message, type, error_subcode } }
89
+ // Hard-fail on:
90
+ // - 400 with subcode 131_xxx (template not approved, recipient
91
+ // not on WA, etc.)
92
+ // - 401 / 403 (auth / permission)
93
+ // - 404 (bad phone number id)
94
+ // Retry on 429 + 5xx.
95
+ const hard = response.status === 400 ||
96
+ response.status === 401 ||
97
+ response.status === 403 ||
98
+ response.status === 404;
99
+ const message = `Meta WhatsApp send failed (${response.status}): ${text.slice(0, 500)}`;
100
+ if (hard) {
101
+ throw new ProviderHardError(message);
102
+ }
103
+ throw new ProviderSendError(message);
104
+ }
105
+ const json = (await response.json().catch(() => ({})));
106
+ const wamid = json.messages?.[0]?.id;
107
+ if (!wamid) {
108
+ // Treat missing wamid as transient — Meta has occasionally
109
+ // shipped responses without the field during outages, and a
110
+ // retry is harmless because the request was idempotent on
111
+ // `biz_opaque_callback_data`.
112
+ throw new ProviderSendError('Meta WhatsApp send: response missing messages[0].id');
113
+ }
114
+ return {
115
+ providerMessageId: wamid,
116
+ acceptedAtMs: Date.now(),
117
+ channel: 'whatsapp',
118
+ };
119
+ },
120
+ };
121
+ }
122
+ /**
123
+ * Build a token resolver that reads from AWS Secrets Manager.
124
+ * Memoizes the secret value per cold start.
125
+ *
126
+ * Lazy-imports `@aws-sdk/client-secrets-manager` so projects that don't
127
+ * use WhatsApp don't pay the SDK cost at cold start.
128
+ */
129
+ export function createSecretsTokenResolver(opts) {
130
+ let cached = null;
131
+ return async () => {
132
+ if (cached)
133
+ return cached;
134
+ const region = opts.region ?? process.env.AWS_REGION ?? 'us-east-1';
135
+ const sdk = (await import('@aws-sdk/client-secrets-manager'));
136
+ const client = new sdk.SecretsManagerClient({ region });
137
+ const result = await client.send(new sdk.GetSecretValueCommand({ SecretId: opts.secretArn }));
138
+ if (!result.SecretString) {
139
+ throw new ProviderHardError(`Secret ${opts.secretArn} has no SecretString value`);
140
+ }
141
+ if (opts.jsonKey === undefined) {
142
+ cached = result.SecretString;
143
+ return cached;
144
+ }
145
+ let parsed;
146
+ try {
147
+ parsed = JSON.parse(result.SecretString);
148
+ }
149
+ catch (err) {
150
+ throw new ProviderHardError(`Secret ${opts.secretArn} is not valid JSON`, err);
151
+ }
152
+ const value = parsed[opts.jsonKey];
153
+ if (!value) {
154
+ throw new ProviderHardError(`Secret ${opts.secretArn} has no key '${opts.jsonKey}'`);
155
+ }
156
+ cached = value;
157
+ return cached;
158
+ };
159
+ }
160
+ //# sourceMappingURL=whatsapp-meta.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whatsapp-meta.js","sourceRoot":"","sources":["../../src/providers/whatsapp-meta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EACL,iBAAiB,EACjB,iBAAiB,GAIlB,MAAM,YAAY,CAAC;AAuBpB;;GAEG;AACH,MAAM,UAAU,0BAA0B,CACxC,MAAkC;IAElC,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,IAAI,OAAO,CAAC;IAChD,MAAM,SAAS,GAAG,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC;IACxC,IAAI,WAAW,GAAkB,IAAI,CAAC;IAEtC,KAAK,UAAU,QAAQ;QACrB,IAAI,WAAW;YAAE,OAAO,WAAW,CAAC;QACpC,WAAW,GAAG,MA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U,IAAI,CAAC,SAAS,4BAA4B,CACrD,CAAC;QACJ,CAAC;QACD,IAAI,IAAI,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YAC/B,MAAM,GAAG,MAAM,CAAC,YAAY,CAAC;YAC7B,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,IAAI,MAA8B,CAAC;QACnC,IAAI,CAAC;YACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,CAA2B,CAAC;QACrE,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,iBAAiB,CACzB,UAAU,IAAI,CAAC,SAAS,oBAAoB,EAC5C,GAAG,CACJ,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,iBAAiB,CACzB,UAAU,IAAI,CAAC,SAAS,gBAAgB,IAAI,CAAC,OAAO,GAAG,CACxD,CAAC;QACJ,CAAC;QACD,MAAM,GAAG,KAAK,CAAC;QACf,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @venturekit/notify — store barrel.
3
+ */
4
+ export { createPostgresNotifyStore, type CreatePostgresNotifyStoreOptions, } from './postgres.js';
5
+ export type { NotifyStore, CreateNotificationInput, UpdateNotificationStatusInput, ListForUserOptions, AdminListOptions, } from './types.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACL,yBAAyB,EACzB,KAAK,gCAAgC,GACtC,MAAM,eAAe,CAAC;AAEvB,YAAY,EACV,WAAW,EACX,uBAAuB,EACvB,6BAA6B,EAC7B,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,YAAY,CAAC"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @venturekit/notify — store barrel.
3
+ */
4
+ export { createPostgresNotifyStore, } from './postgres.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACL,yBAAyB,GAE1B,MAAM,eAAe,CAAC"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @venturekit/notify — Postgres outbox adapter
3
+ *
4
+ * Talks to the project's primary Postgres database via `@venturekit/data`'s
5
+ * `query()` (or any `Querier` — useful when the caller already holds a
6
+ * transaction). The schema is shipped under `migrations/` and applied
7
+ * by the in-VPC migration runner that `@venturekit/infra` provisions.
8
+ *
9
+ * All public functions return rows with ISO-8601 timestamp strings
10
+ * matching {@link NotificationRow}. The adapter intentionally does its
11
+ * own date conversion rather than delegating to a global mapper so the
12
+ * package is usable without `@venturekit/data`'s mapper config.
13
+ */
14
+ import type { Querier } from '@venturekit/data';
15
+ import type { NotifyStore } from './types.js';
16
+ export interface CreatePostgresNotifyStoreOptions {
17
+ /**
18
+ * Querier to use. Defaults to `query` from `@venturekit/data` (the
19
+ * pool-backed function). Pass a transaction's `query` method to
20
+ * scope all calls within a single transaction.
21
+ */
22
+ querier?: Querier;
23
+ /**
24
+ * Override the id generator — useful for tests that want predictable
25
+ * ids or for callers that already have a project-wide id factory.
26
+ */
27
+ generateNotificationId?: () => string;
28
+ generateEventId?: () => string;
29
+ }
30
+ /**
31
+ * Create the Postgres-backed {@link NotifyStore}. The returned object
32
+ * is stateless aside from the captured querier, so it's safe to share
33
+ * across handlers.
34
+ */
35
+ export declare function createPostgresNotifyStore(options?: CreatePostgresNotifyStoreOptions): NotifyStore;
36
+ //# sourceMappingURL=postgres.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../../src/store/postgres.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,EAIV,WAAW,EAEZ,MAAM,YAAY,CAAC;AAiIpB,MAAM,WAAW,gCAAgC;IAC/C;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,MAAM,CAAC;IACtC,eAAe,CAAC,EAAE,MAAM,MAAM,CAAC;CAChC;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,gCAAqC,GAC7C,WAAW,CA6Sb"}
@@ -0,0 +1,354 @@
1
+ /**
2
+ * @venturekit/notify — Postgres outbox adapter
3
+ *
4
+ * Talks to the project's primary Postgres database via `@venturekit/data`'s
5
+ * `query()` (or any `Querier` — useful when the caller already holds a
6
+ * transaction). The schema is shipped under `migrations/` and applied
7
+ * by the in-VPC migration runner that `@venturekit/infra` provisions.
8
+ *
9
+ * All public functions return rows with ISO-8601 timestamp strings
10
+ * matching {@link NotificationRow}. The adapter intentionally does its
11
+ * own date conversion rather than delegating to a global mapper so the
12
+ * package is usable without `@venturekit/data`'s mapper config.
13
+ */
14
+ // ── Id generation ─────────────────────────────────────────────────────
15
+ /**
16
+ * Generate a stable URL-safe id. Format: `notif_<22 base32 chars>` —
17
+ * roughly 110 bits of entropy, indistinguishable from a UUIDv4 in
18
+ * collision risk but with a friendlier prefix that's easier to spot in
19
+ * logs (`notif_…` vs `e7…-..-..`). Uses `crypto.randomUUID` then strips
20
+ * the hyphens and converts to lowercase base32 for 22 chars.
21
+ */
22
+ function makeNotificationId() {
23
+ const uuid = globalThis
24
+ .crypto?.randomUUID?.()
25
+ ?? fallbackUuid();
26
+ return `notif_${uuid.replace(/-/g, '').slice(0, 22)}`;
27
+ }
28
+ function makeEventId() {
29
+ const uuid = globalThis
30
+ .crypto?.randomUUID?.()
31
+ ?? fallbackUuid();
32
+ return `nevt_${uuid.replace(/-/g, '').slice(0, 22)}`;
33
+ }
34
+ /** Used only when `crypto.randomUUID` is unavailable (very old Node). */
35
+ function fallbackUuid() {
36
+ const r = () => Math.random().toString(16).slice(2, 10);
37
+ return `${r()}${r()}-${r().slice(0, 4)}-${r().slice(0, 4)}-${r().slice(0, 4)}-${r()}${r().slice(0, 4)}`;
38
+ }
39
+ // ── Row mapping ───────────────────────────────────────────────────────
40
+ /**
41
+ * Cast a Postgres row (snake_case + Date) to a {@link NotificationRow}
42
+ * (camelCase + ISO strings). Centralized so the SELECT lists below all
43
+ * round-trip through the same shape.
44
+ */
45
+ function rowToNotification(r) {
46
+ return {
47
+ id: r.id,
48
+ recipientUserId: r.recipient_user_id ?? null,
49
+ address: r.address ?? null,
50
+ channel: r.channel,
51
+ templateKey: r.template_key,
52
+ payload: r.payload ?? {},
53
+ status: r.status,
54
+ scheduledForISO: dateToIso(r.scheduled_for),
55
+ sentAtISO: dateToIso(r.sent_at),
56
+ relatedKind: r.related_kind ?? null,
57
+ relatedId: r.related_id ?? null,
58
+ providerMessageId: r.provider_message_id ?? null,
59
+ error: r.error ?? null,
60
+ attempts: Number(r.attempts ?? 0),
61
+ createdAtISO: dateToIso(r.created_at) ?? new Date(0).toISOString(),
62
+ };
63
+ }
64
+ function rowToPreference(r) {
65
+ return {
66
+ userId: r.user_id,
67
+ channel: r.channel,
68
+ category: r.category,
69
+ optedIn: Boolean(r.opted_in),
70
+ updatedAtISO: dateToIso(r.updated_at) ?? new Date(0).toISOString(),
71
+ };
72
+ }
73
+ function rowToEvent(r) {
74
+ return {
75
+ id: r.id,
76
+ channel: r.channel,
77
+ address: r.address,
78
+ eventType: r.event_type,
79
+ providerMessageId: r.provider_message_id ?? null,
80
+ suppress: Boolean(r.suppress),
81
+ raw: r.raw ?? {},
82
+ receivedAtISO: dateToIso(r.received_at) ?? new Date(0).toISOString(),
83
+ };
84
+ }
85
+ function dateToIso(value) {
86
+ if (value === null || value === undefined)
87
+ return null;
88
+ if (value instanceof Date)
89
+ return value.toISOString();
90
+ if (typeof value === 'string')
91
+ return value;
92
+ return null;
93
+ }
94
+ // Shared SELECT lists — kept verbatim across reads so a column-name
95
+ // typo can only sneak through one statement at a time.
96
+ const NOTIFICATION_COLUMNS = `
97
+ id,
98
+ recipient_user_id,
99
+ address,
100
+ channel,
101
+ template_key,
102
+ payload,
103
+ status,
104
+ scheduled_for,
105
+ sent_at,
106
+ related_kind,
107
+ related_id,
108
+ provider_message_id,
109
+ error,
110
+ attempts,
111
+ created_at
112
+ `;
113
+ const EVENT_COLUMNS = `
114
+ id, channel, address, event_type, provider_message_id, suppress,
115
+ raw, received_at
116
+ `;
117
+ const PREFERENCE_COLUMNS = `
118
+ user_id, channel, category, opted_in, updated_at
119
+ `;
120
+ /**
121
+ * Create the Postgres-backed {@link NotifyStore}. The returned object
122
+ * is stateless aside from the captured querier, so it's safe to share
123
+ * across handlers.
124
+ */
125
+ export function createPostgresNotifyStore(options = {}) {
126
+ const generateId = options.generateNotificationId ?? makeNotificationId;
127
+ const generateEvtId = options.generateEventId ?? makeEventId;
128
+ // Lazy resolve the default querier so the package can be imported
129
+ // in environments that don't have `@venturekit/data` installed
130
+ // (the runtime client supports passing a custom store).
131
+ let resolveQuerier = async () => {
132
+ if (options.querier)
133
+ return options.querier;
134
+ const data = (await import('@venturekit/data'));
135
+ resolveQuerier = async () => data.query;
136
+ return data.query;
137
+ };
138
+ return {
139
+ // ── Outbox CRUD ───────────────────────────────────────────────
140
+ async createNotification(input) {
141
+ const q = await resolveQuerier();
142
+ const id = generateId();
143
+ const rows = await q(`INSERT INTO notifications (
144
+ id, recipient_user_id, address, channel, template_key, payload,
145
+ scheduled_for, related_kind, related_id
146
+ )
147
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
148
+ RETURNING ${NOTIFICATION_COLUMNS}`, [
149
+ id,
150
+ input.recipientUserId,
151
+ input.address,
152
+ input.channel,
153
+ input.templateKey,
154
+ JSON.stringify(input.payload ?? {}),
155
+ input.scheduledForISO ?? null,
156
+ input.relatedKind ?? null,
157
+ input.relatedId ?? null,
158
+ ]);
159
+ return rowToNotification(rows[0]);
160
+ },
161
+ async claimPending(limit) {
162
+ // Two-stage lock pattern:
163
+ // 1. Inner SELECT … FOR UPDATE SKIP LOCKED selects up-to-`limit`
164
+ // rows that are in 'pending' state and either unscheduled or
165
+ // due now. SKIP LOCKED guarantees concurrent dispatcher
166
+ // replicas never see the same row.
167
+ // 2. Outer UPDATE flips `scheduled_for` to NOW() so the same
168
+ // worker doesn't re-claim them inside its current tick — the
169
+ // effective lease is one cron interval.
170
+ // The status stays 'pending' during dispatch; a follow-up
171
+ // `updateStatus` call commits the final state. We deliberately do
172
+ // NOT introduce a 'leased' state here in Phase 1 — the next-tick
173
+ // re-pickup window is short enough (1 min default) that crash
174
+ // recovery just retries the row, and the outbox runs at low
175
+ // enough volume that the duplicate-send risk is acceptable.
176
+ const q = await resolveQuerier();
177
+ const rows = await q(`UPDATE notifications
178
+ SET scheduled_for = COALESCE(scheduled_for, NOW()),
179
+ attempts = attempts + 1
180
+ WHERE id IN (
181
+ SELECT id FROM notifications
182
+ WHERE status = 'pending'
183
+ AND (scheduled_for IS NULL OR scheduled_for <= NOW())
184
+ ORDER BY created_at ASC
185
+ LIMIT $1
186
+ FOR UPDATE SKIP LOCKED
187
+ )
188
+ RETURNING ${NOTIFICATION_COLUMNS}`, [limit]);
189
+ return rows.map(rowToNotification);
190
+ },
191
+ async updateStatus(input) {
192
+ const q = await resolveQuerier();
193
+ const rows = await q(`UPDATE notifications
194
+ SET status = $1,
195
+ provider_message_id = COALESCE($2, provider_message_id),
196
+ error = $3,
197
+ sent_at = CASE WHEN $1 = 'sent' THEN NOW() ELSE sent_at END,
198
+ attempts = CASE WHEN $4 THEN attempts + 1 ELSE attempts END
199
+ WHERE id = $5
200
+ RETURNING ${NOTIFICATION_COLUMNS}`, [
201
+ input.status,
202
+ input.providerMessageId ?? null,
203
+ input.error ?? null,
204
+ input.incrementAttempts ?? false,
205
+ input.id,
206
+ ]);
207
+ return rows[0] ? rowToNotification(rows[0]) : null;
208
+ },
209
+ async findById(id) {
210
+ const q = await resolveQuerier();
211
+ const rows = await q(`SELECT ${NOTIFICATION_COLUMNS} FROM notifications WHERE id = $1 LIMIT 1`, [id]);
212
+ return rows[0] ? rowToNotification(rows[0]) : null;
213
+ },
214
+ async listForUser(userId, opts = {}) {
215
+ const q = await resolveQuerier();
216
+ const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
217
+ const conds = ['recipient_user_id = $1'];
218
+ const params = [userId];
219
+ if (opts.channel) {
220
+ params.push(opts.channel);
221
+ conds.push(`channel = $${params.length}`);
222
+ }
223
+ if (opts.status) {
224
+ params.push(opts.status);
225
+ conds.push(`status = $${params.length}`);
226
+ }
227
+ params.push(limit);
228
+ const rows = await q(`SELECT ${NOTIFICATION_COLUMNS}
229
+ FROM notifications
230
+ WHERE ${conds.join(' AND ')}
231
+ ORDER BY created_at DESC
232
+ LIMIT $${params.length}`, params);
233
+ return rows.map(rowToNotification);
234
+ },
235
+ async adminList(opts = {}) {
236
+ const q = await resolveQuerier();
237
+ const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
238
+ const offset = Math.max(opts.offset ?? 0, 0);
239
+ const conds = [];
240
+ const params = [];
241
+ if (opts.status) {
242
+ params.push(opts.status);
243
+ conds.push(`status = $${params.length}`);
244
+ }
245
+ if (opts.channel) {
246
+ params.push(opts.channel);
247
+ conds.push(`channel = $${params.length}`);
248
+ }
249
+ if (opts.templateKey) {
250
+ params.push(opts.templateKey);
251
+ conds.push(`template_key = $${params.length}`);
252
+ }
253
+ if (opts.search) {
254
+ params.push(`%${opts.search}%`);
255
+ const idx = params.length;
256
+ conds.push(`(recipient_user_id ILIKE $${idx} OR address ILIKE $${idx})`);
257
+ }
258
+ const where = conds.length ? `WHERE ${conds.join(' AND ')}` : '';
259
+ // Two queries — count + page. The count is unindexed but at admin
260
+ // volumes (low thousands) this is fine; switch to keyset pagination
261
+ // before `notifications` exceeds ~1M rows.
262
+ const totalRows = await q(`SELECT COUNT(*)::text AS count FROM notifications ${where}`, params);
263
+ const total = Number(totalRows[0]?.count ?? 0);
264
+ params.push(limit);
265
+ params.push(offset);
266
+ const rows = await q(`SELECT ${NOTIFICATION_COLUMNS}
267
+ FROM notifications
268
+ ${where}
269
+ ORDER BY created_at DESC
270
+ LIMIT $${params.length - 1} OFFSET $${params.length}`, params);
271
+ return { rows: rows.map(rowToNotification), total };
272
+ },
273
+ async retry(id) {
274
+ const q = await resolveQuerier();
275
+ const rows = await q(`UPDATE notifications
276
+ SET status = 'pending',
277
+ error = NULL,
278
+ scheduled_for = NULL
279
+ WHERE id = $1 AND status IN ('failed', 'bounced')
280
+ RETURNING ${NOTIFICATION_COLUMNS}`, [id]);
281
+ return rows[0] ? rowToNotification(rows[0]) : null;
282
+ },
283
+ async cancel(id) {
284
+ const q = await resolveQuerier();
285
+ const rows = await q(`UPDATE notifications
286
+ SET status = 'cancelled'
287
+ WHERE id = $1 AND status = 'pending'
288
+ RETURNING ${NOTIFICATION_COLUMNS}`, [id]);
289
+ return rows[0] ? rowToNotification(rows[0]) : null;
290
+ },
291
+ // ── Preferences ───────────────────────────────────────────────
292
+ async listPreferences(userId) {
293
+ const q = await resolveQuerier();
294
+ const rows = await q(`SELECT ${PREFERENCE_COLUMNS}
295
+ FROM notification_preferences
296
+ WHERE user_id = $1
297
+ ORDER BY channel, category`, [userId]);
298
+ return rows.map(rowToPreference);
299
+ },
300
+ async upsertPreference(input) {
301
+ const q = await resolveQuerier();
302
+ const rows = await q(`INSERT INTO notification_preferences (user_id, channel, category, opted_in, updated_at)
303
+ VALUES ($1, $2, $3, $4, NOW())
304
+ ON CONFLICT (user_id, channel, category)
305
+ DO UPDATE SET opted_in = EXCLUDED.opted_in, updated_at = NOW()
306
+ RETURNING ${PREFERENCE_COLUMNS}`, [input.userId, input.channel, input.category, input.optedIn]);
307
+ return rowToPreference(rows[0]);
308
+ },
309
+ async isOptedIn(userId, channel, category) {
310
+ const q = await resolveQuerier();
311
+ const rows = await q(`SELECT opted_in FROM notification_preferences
312
+ WHERE user_id = $1 AND channel = $2 AND category = $3
313
+ LIMIT 1`, [userId, channel, category]);
314
+ // No row => default opt-in.
315
+ if (rows.length === 0)
316
+ return true;
317
+ return Boolean(rows[0].opted_in);
318
+ },
319
+ // ── Bounce / suppression ──────────────────────────────────────
320
+ async recordEvent(input) {
321
+ const q = await resolveQuerier();
322
+ const id = generateEvtId();
323
+ const rows = await q(`INSERT INTO notification_event_log (
324
+ id, channel, address, event_type, provider_message_id, suppress, raw, received_at
325
+ )
326
+ VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())
327
+ RETURNING ${EVENT_COLUMNS}`, [
328
+ id,
329
+ input.channel,
330
+ input.address,
331
+ input.eventType,
332
+ input.providerMessageId ?? null,
333
+ input.suppress,
334
+ JSON.stringify(input.raw ?? {}),
335
+ ]);
336
+ return rowToEvent(rows[0]);
337
+ },
338
+ async isAddressSuppressed(channel, address) {
339
+ const q = await resolveQuerier();
340
+ const rows = await q(`SELECT EXISTS(
341
+ SELECT 1 FROM notification_event_log
342
+ WHERE channel = $1 AND address = $2 AND suppress = TRUE
343
+ ) AS exists`, [channel, address]);
344
+ return Boolean(rows[0]?.exists);
345
+ },
346
+ async clearSuppression(channel, address) {
347
+ const q = await resolveQuerier();
348
+ await q(`UPDATE notification_event_log
349
+ SET suppress = FALSE
350
+ WHERE channel = $1 AND address = $2 AND suppress = TRUE`, [channel, address]);
351
+ },
352
+ };
353
+ }
354
+ //# sourceMappingURL=postgres.js.map