@frigear-nu/notify 0.2.5 → 0.2.6

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
@@ -29,9 +29,14 @@ export default defineNuxtConfig({
29
29
  driver: '~/server/utils/twilio-sms-driver',
30
30
  },
31
31
  simple: {
32
- // Same idea, matching the `SimpleDriver` signature, for generic push notifications.
32
+ // Same idea, matching the `SimpleDriver` signature, for generic notifications.
33
33
  driver: 'log',
34
34
  },
35
+ push: {
36
+ // Same idea, matching the `PushDriver` signature, for `dispatchPushNotification`.
37
+ // Leave it unset with `@frigear-nu/push` installed: push sets itself here, and a value set here wins.
38
+ // driver: '~/server/utils/my-push-driver',
39
+ },
35
40
  },
36
41
  })
37
42
  ```
@@ -79,6 +84,13 @@ await dispatchSimpleNotification({
79
84
  })
80
85
  ```
81
86
 
87
+ ### notifyUser
88
+
89
+ `notifyUser(userId, { topic, email?, sms?, push? })` sends one user a message on the channels they chose for a topic.
90
+ Modules declare their topics with `extendNotificationTopics(nuxt, topics)` from `@frigear-nu/notify/utils`. The
91
+ contacts come from the recipient store `@frigear-nu/users` registers, the choices from the choices store
92
+ `@frigear-nu/preferences` registers. See https://docs.frigear.dev/modules/communication/notify#notifying-a-user.
93
+
82
94
  ## Built-in email drivers: `resend`, `ses`, `cloudflare`
83
95
 
84
96
  Zero dependencies and zero config beyond environment variables - each driver talks to its provider with plain `fetch`
package/dist/module.d.mts CHANGED
@@ -4,8 +4,8 @@ type NotificationMeta<AdditionalMeta = Record<string, unknown>> = {
4
4
  driver?: string;
5
5
  } & AdditionalMeta;
6
6
  /**
7
- * Generic, transport-agnostic push notification. Concrete notifications (e.g. a password reset)
8
- * build one of these and hand it to `dispatchPushNotification`, similar in spirit to how Laravel
7
+ * Generic, transport-agnostic notification. Concrete notifications (e.g. a password reset)
8
+ * build one of these and hand it to `dispatchSimpleNotification`, similar in spirit to how Laravel
9
9
  * notifications render themselves to a `toMail()` payload before a channel sends it.
10
10
  */
11
11
  interface SimpleNotification<M = Record<string, unknown>> {
@@ -15,6 +15,37 @@ interface SimpleNotification<M = Record<string, unknown>> {
15
15
  url?: string;
16
16
  meta?: M;
17
17
  }
18
+ /** Text, or one text per locale (`{ da: '...', en: '...' }`), for a driver that picks by the recipient's locale. */
19
+ type PushText = string | Record<string, string>;
20
+ /**
21
+ * A push notification to the devices of one or more users. Concrete notifications build one of these and hand it to
22
+ * `dispatchPushNotification`; the driver (`notify.push.driver`) finds the users' devices and delivers it.
23
+ * `@frigear-nu/push` is that driver when it is installed (FCM and APNs to the devices it stores).
24
+ */
25
+ interface PushNotification<M = NotificationMeta> {
26
+ /** The users to reach, on every device the driver knows for them. */
27
+ userIds: number[];
28
+ /** Text, or one text per locale: a driver that knows each device's locale picks it (else `en`). */
29
+ title: PushText;
30
+ body: PushText;
31
+ /** Where the app goes when the notification is opened (a path in the app or a URL). */
32
+ url?: string;
33
+ /** Extra string data delivered with the notification. */
34
+ data?: Record<string, string>;
35
+ meta?: M;
36
+ }
37
+ /**
38
+ * What a push driver may answer: how many devices took the notification. A driver that cannot tell (the `log` driver)
39
+ * answers nothing, so `dispatchPushNotification` resolves to `undefined`.
40
+ */
41
+ type PushDispatchResult = {
42
+ /** Devices the provider accepted. */
43
+ sent: number;
44
+ /** Devices that failed. */
45
+ failed: number;
46
+ /** Devices whose token turned out dead and were dropped, when the driver tracks it. */
47
+ revoked?: number;
48
+ };
18
49
  /**
19
50
  * Generic, transport-agnostic SMS notification. Concrete notifications (e.g. a password reset)
20
51
  * build one of these and hand it to `dispatchSMSNotification`, similar in spirit to how Laravel
@@ -39,6 +70,11 @@ interface EmailNotification<M = NotificationMeta> {
39
70
  text?: string;
40
71
  /** Address replies should go to (the `Reply-To` header). */
41
72
  replyTo?: string;
73
+ /**
74
+ * `Cc` recipients. Optional and additive: every built-in driver (`resend`, `ses`, `cloudflare`, `log`) passes them
75
+ * on. A custom driver whose transport has no cc may ignore them, and should say so where it is documented.
76
+ */
77
+ cc?: string | string[];
42
78
  /**
43
79
  * Template to render this email from instead of `subject`/`body`/`text`, when a renderer is
44
80
  * installed (`@frigear-nu/email-templates` listens on the `notify:email` hook). Without one,
@@ -81,6 +117,115 @@ type NotifyEmailContext = {
81
117
  type SimpleDriver = (notification: SimpleNotification) => Promise<void> | void;
82
118
  type SMSDriver = (notification: SMSNotification) => Promise<void> | void;
83
119
  type EmailDriver = (notification: EmailNotification) => Promise<void> | void;
120
+ type PushDriver = (notification: PushNotification) => Promise<PushDispatchResult | void> | PushDispatchResult | void;
121
+ /** The channels `notifyUser` can reach a user on. */
122
+ type NotificationChannel = 'email' | 'sms' | 'push';
123
+ /** A text in one language, or per locale code (`{ da, en }`). */
124
+ type Translated = string | Record<string, string>;
125
+ /** What a module declares with `extendNotificationTopics`: one kind of message a user can choose channels for. */
126
+ type NotificationTopic = {
127
+ /** Stable id (`shifts.reminder`); the key the user's choices are stored under. */
128
+ id: string;
129
+ /** The label the account page shows. */
130
+ label?: Translated;
131
+ /** An i18n key (`shifts.topics.reminder`) tried before `label`. */
132
+ labelKey?: string;
133
+ description?: Translated;
134
+ descriptionKey?: string;
135
+ /** What applies until the user chooses. A channel the topic does not offer is off whatever this says. */
136
+ defaults: Record<NotificationChannel, boolean>;
137
+ /** The channels the topic can use. Defaults to all three. */
138
+ channels?: NotificationChannel[];
139
+ };
140
+ /** Which channels are on, for one topic. */
141
+ type ChannelSettings = Record<NotificationChannel, boolean>;
142
+ /** What a user chose, per topic id. A topic (or a channel) left out uses the topic's defaults. */
143
+ type NotificationChoices = Record<string, Partial<ChannelSettings>>;
144
+ /** How `notifyUser` reaches a user: what the registered recipient store answers. */
145
+ type NotifyRecipient = {
146
+ /** Where email goes; without it the email channel is `unavailable`. */
147
+ email?: string | null;
148
+ /** Where SMS goes; without it the SMS channel is `unavailable`. */
149
+ phone?: string | null;
150
+ /** The user's language (`da`, `en-GB`): picks the SMS text and the email template's locale when they have none. */
151
+ locale?: string | null;
152
+ };
153
+ /**
154
+ * Resolves user ids to the contacts `notifyUser` sends to. `@frigear-nu/users` registers one (`setNotifyRecipientStore`).
155
+ * Without one, `notifyUser` sends nothing and logs a warning.
156
+ */
157
+ interface NotifyRecipientStore {
158
+ /** The contacts of a user, or `null` when there is no such user. */
159
+ findRecipient(userId: number): Promise<NotifyRecipient | null>;
160
+ }
161
+ /**
162
+ * Reads and writes each user's channel choices per topic. `@frigear-nu/preferences` registers one
163
+ * (`setNotifyChoicesStore`). Without one, every user gets the topics' defaults and nothing can be changed.
164
+ */
165
+ interface NotifyChoicesStore {
166
+ /** What the user chose, per topic id. */
167
+ readChoices(userId: number): Promise<NotificationChoices>;
168
+ /**
169
+ * Merges the channels given into what is stored for each topic, per channel and against a fresh read of the stored
170
+ * choices (not one the caller made earlier), so concurrent changes to other channels or topics are kept. Channels and
171
+ * topics left out keep what they had.
172
+ */
173
+ writeChoices(userId: number, choices: NotificationChoices): Promise<void>;
174
+ }
175
+ /** A topic as the account page shows it. */
176
+ type NotificationTopicDto = {
177
+ id: string;
178
+ label: Translated;
179
+ labelKey?: string;
180
+ description?: Translated;
181
+ descriptionKey?: string;
182
+ channels: NotificationChannel[];
183
+ };
184
+ type NotificationChannelsRow = NotificationTopicDto & {
185
+ /** What the user has chosen, or the topic's defaults. */
186
+ settings: ChannelSettings;
187
+ /** Whether the user chose it (`false`: the defaults apply). */
188
+ custom: boolean;
189
+ };
190
+ /** Every registered topic with what applies to one user (`readNotificationChannels`). */
191
+ type NotificationChannelsDto = {
192
+ /** `true` when the user has a phone number, so SMS can work. */
193
+ hasPhone: boolean;
194
+ topics: NotificationChannelsRow[];
195
+ };
196
+ type NotifyUserInput = {
197
+ /** A topic registered with `extendNotificationTopics`; an unknown one throws. */
198
+ topic: string;
199
+ /**
200
+ * The email to send, to the recipient's address. `template` and `meta` are handed to `dispatchEmailNotification` as
201
+ * they are (`subject` and `body` stay the fallback when no renderer is installed).
202
+ */
203
+ email?: {
204
+ subject: string;
205
+ body: string;
206
+ text?: string;
207
+ replyTo?: string;
208
+ template?: EmailTemplateRef;
209
+ meta?: Record<string, unknown>;
210
+ };
211
+ /** The text of an SMS, or one per locale (the recipient's locale picks it). */
212
+ sms?: {
213
+ body: Translated;
214
+ };
215
+ /** The push notification, through notify's push driver (`dispatchPushNotification`). */
216
+ push?: {
217
+ title: Translated;
218
+ body: Translated;
219
+ url?: string;
220
+ data?: Record<string, string>;
221
+ };
222
+ };
223
+ type NotifyUserResult = {
224
+ /** The channels that went out. */
225
+ channels: NotificationChannel[];
226
+ /** Channels the user's choices (or a missing address, phone or device) skipped, with why. */
227
+ skipped: Partial<Record<NotificationChannel, 'disabled' | 'unavailable' | 'no_content' | 'failed'>>;
228
+ };
84
229
  type ModuleOptions = {
85
230
  email?: {
86
231
  driver?: 'log' | 'resend' | 'ses' | 'cloudflare' | (string & {});
@@ -92,7 +237,7 @@ type ModuleOptions = {
92
237
  driver?: string | 'log';
93
238
  };
94
239
  push?: {
95
- driver?: string;
240
+ driver?: string | 'log';
96
241
  };
97
242
  };
98
243
  /** Private runtime config (`runtimeConfig.notify`), overridable through `NUXT_NOTIFY_*` env vars. */
@@ -139,4 +284,4 @@ declare module '@nuxt/schema' {
139
284
  declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
140
285
 
141
286
  export { _default as default };
142
- export type { EmailDriver, EmailNotification, EmailTemplateRef, EmailTemplateSource, ModuleOptions, NotifyEmailContext, SMSDriver, SMSNotification, SimpleDriver, SimpleNotification };
287
+ export type { ChannelSettings, EmailDriver, EmailNotification, EmailTemplateRef, EmailTemplateSource, ModuleOptions, NotificationChannel, NotificationChannelsDto, NotificationChannelsRow, NotificationChoices, NotificationTopic, NotificationTopicDto, NotifyChoicesStore, NotifyEmailContext, NotifyRecipient, NotifyRecipientStore, NotifyUserInput, NotifyUserResult, PushDispatchResult, PushDriver, PushNotification, PushText, SMSDriver, SMSNotification, SimpleDriver, SimpleNotification, Translated };
package/dist/module.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@frigear-nu/notify",
3
3
  "configKey": "notify",
4
- "version": "0.2.5",
4
+ "version": "0.2.6",
5
5
  "builder": {
6
- "@nuxt/module-builder": "1.0.3",
6
+ "@nuxt/module-builder": "1.0.4",
7
7
  "unbuild": "unknown"
8
8
  }
9
9
  }
package/dist/module.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { defineNuxtModule, createResolver, addTypeTemplate, addServerImportsDir, addServerTemplate } from '@nuxt/kit';
2
- import { inlineModuleRuntime } from '@frigear-nu/module-kit/utils';
2
+ import { defineVirtualRegistry, inlineModuleRuntime } from '@frigear-nu/module-kit/utils';
3
+ import { topicsTemplate, notifyBuildState, storesTemplate } from '../dist/runtime/utils/topics.js';
3
4
  import { defu } from 'defu';
4
5
  import { joinURL } from 'ufo';
5
6
 
@@ -13,7 +14,8 @@ const module$1 = defineNuxtModule({
13
14
  defaults: {
14
15
  email: { driver: "log" },
15
16
  sms: { driver: "log" },
16
- simple: { driver: "log" }
17
+ simple: { driver: "log" },
18
+ push: { driver: "log" }
17
19
  },
18
20
  async setup(options, nuxt) {
19
21
  const resolver = createResolver(import.meta.url);
@@ -57,6 +59,7 @@ const module$1 = defineNuxtModule({
57
59
  registerServerDriver("email-driver", "EmailDriver", emailBuiltin ? "auto" : emailDriver, { auto: AUTO_EMAIL_DRIVER });
58
60
  registerServerDriver("sms-driver", "SMSDriver", options.sms?.driver ?? "log");
59
61
  registerServerDriver("simple-driver", "SimpleDriver", options.simple?.driver ?? "log");
62
+ registerServerDriver("push-driver", "PushDriver", options.push?.driver ?? "log");
60
63
  addTypeTemplate({
61
64
  filename: "types/notify-hooks.d.ts",
62
65
  getContents: () => `declare module 'nitropack/types' {
@@ -70,6 +73,32 @@ const module$1 = defineNuxtModule({
70
73
  }
71
74
 
72
75
  export {}
76
+ `
77
+ }, { nitro: true, nuxt: true });
78
+ defineVirtualRegistry(nuxt, {
79
+ filename: "#notify/topics",
80
+ target: "server",
81
+ collect: () => notifyBuildState(nuxt)._topics ?? [],
82
+ contents: (topics) => topicsTemplate(topics)
83
+ });
84
+ defineVirtualRegistry(nuxt, {
85
+ filename: "#notify/stores",
86
+ target: "server",
87
+ collect: () => ({ recipient: notifyBuildState(nuxt)._recipientStore, choices: notifyBuildState(nuxt)._choicesStore }),
88
+ contents: (stores) => storesTemplate(stores)
89
+ });
90
+ const types = JSON.stringify(resolver.resolve("./types"));
91
+ addTypeTemplate({
92
+ filename: "types/notify-registry.d.ts",
93
+ getContents: () => `declare module '#notify/topics' {
94
+ export const topics: import(${types}).NotificationTopic[]
95
+ }
96
+ declare module '#notify/stores' {
97
+ /** The registered recipient store, or \`null\` when no module registered one. */
98
+ export const recipientStore: import(${types}).NotifyRecipientStore | null
99
+ /** The registered choices store, or \`null\` when no module registered one. */
100
+ export const choicesStore: import(${types}).NotifyChoicesStore | null
101
+ }
73
102
  `
74
103
  }, { nitro: true, nuxt: true });
75
104
  addServerImportsDir(resolver.resolve("./runtime/server/utils"));
@@ -10,6 +10,7 @@ export const createCloudflareDriver = (config) => async (n) => {
10
10
  body: JSON.stringify({
11
11
  from: resolveFrom(config),
12
12
  to: toArray(n.to),
13
+ cc: n.cc ? toArray(n.cc) : void 0,
13
14
  subject: n.subject,
14
15
  html: n.body,
15
16
  text: n.text,
@@ -9,6 +9,7 @@ export const createResendDriver = (config) => async (n) => {
9
9
  body: JSON.stringify({
10
10
  from: resolveFrom(config),
11
11
  to: toArray(n.to),
12
+ cc: n.cc ? toArray(n.cc) : void 0,
12
13
  subject: n.subject,
13
14
  html: n.body,
14
15
  text: n.text,
@@ -7,7 +7,7 @@ export const createSesDriver = (config) => async (n) => {
7
7
  const url = `https://email.${region}.amazonaws.com/v2/email/outbound-emails`;
8
8
  const body = JSON.stringify({
9
9
  FromEmailAddress: resolveFrom(config),
10
- Destination: { ToAddresses: toArray(n.to) },
10
+ Destination: { ToAddresses: toArray(n.to), ...n.cc ? { CcAddresses: toArray(n.cc) } : {} },
11
11
  ReplyToAddresses: n.replyTo ? [n.replyTo] : void 0,
12
12
  Content: {
13
13
  Simple: {
@@ -1,7 +1,7 @@
1
- import type { SimpleNotification, SMSNotification, EmailNotification } from '../../types.js';
1
+ import type { SimpleNotification, SMSNotification, EmailNotification, PushNotification } from '../../types.js';
2
2
  /**
3
3
  * Logs the notification instead of sending it. Safe default for development/unconfigured setups,
4
- * and a reference implementation for the `EmailDriver` signature.
4
+ * and a reference implementation for the driver signatures.
5
5
  */
6
- export declare const logDriver: (notification: SimpleNotification | SMSNotification | EmailNotification) => void;
6
+ export declare const logDriver: (notification: SimpleNotification | SMSNotification | EmailNotification | PushNotification) => void;
7
7
  export default logDriver;
@@ -1,7 +1,9 @@
1
- import type { SimpleDriver, SMSDriver, EmailDriver, SimpleNotification, SMSNotification, EmailNotification } from '../../../types.js';
1
+ import type { SimpleDriver, SMSDriver, EmailDriver, PushDriver, PushNotification, SimpleNotification, SMSNotification, EmailNotification } from '../../../types.js';
2
2
  export declare const defineSimpleNotification: <T extends SimpleNotification>(notification: T) => T;
3
3
  export declare const defineEmailNotification: <T extends EmailNotification>(notification: T) => T;
4
4
  export declare const defineSMSNotification: <T extends SMSNotification>(notification: T) => T;
5
+ export declare const definePushNotification: <T extends PushNotification>(notification: T) => T;
5
6
  export declare const defineSimpleDriver: (driver: SimpleDriver) => SimpleDriver;
6
7
  export declare const defineSMSDriver: (driver: SMSDriver) => SMSDriver;
7
8
  export declare const defineEmailDriver: (driver: EmailDriver) => EmailDriver;
9
+ export declare const definePushDriver: (driver: PushDriver) => PushDriver;
@@ -1,6 +1,8 @@
1
1
  export const defineSimpleNotification = (notification) => notification;
2
2
  export const defineEmailNotification = (notification) => notification;
3
3
  export const defineSMSNotification = (notification) => notification;
4
+ export const definePushNotification = (notification) => notification;
4
5
  export const defineSimpleDriver = (driver) => driver;
5
6
  export const defineSMSDriver = (driver) => driver;
6
7
  export const defineEmailDriver = (driver) => driver;
8
+ export const definePushDriver = (driver) => driver;
@@ -1,4 +1,4 @@
1
- import type { EmailNotification, SMSNotification, SimpleNotification } from '../../../types.js';
1
+ import type { EmailNotification, PushDispatchResult, PushNotification, SMSNotification, SimpleNotification } from '../../../types.js';
2
2
  /**
3
3
  * Dispatches an email notification through the driver configured on the `@frigear-nu/notify`
4
4
  * module (`notify.email.driver`, see `#notify/email-driver`). Auto-imported wherever this module
@@ -20,3 +20,10 @@ export declare function dispatchSMSNotification(notification: SMSNotification):
20
20
  * this - driver selection stays entirely with the app/consuming layer.
21
21
  */
22
22
  export declare function dispatchSimpleNotification(notification: SimpleNotification): Promise<void>;
23
+ /**
24
+ * Dispatches a push notification to the devices of `notification.userIds` through the driver configured on the
25
+ * `@frigear-nu/notify` module (`notify.push.driver`, see `#notify/push-driver`; `@frigear-nu/push` when it is
26
+ * installed). Auto-imported wherever this module is installed, so consumers only ever build a `PushNotification` and
27
+ * call this. Resolves to what the driver reports (devices sent, failed), or `undefined` when it reports nothing (`log`).
28
+ */
29
+ export declare function dispatchPushNotification(notification: PushNotification): Promise<PushDispatchResult | undefined>;
@@ -1,5 +1,6 @@
1
1
  import smsDriver from "#notify/sms-driver";
2
2
  import simpleDriver from "#notify/simple-driver";
3
+ import pushDriver from "#notify/push-driver";
3
4
  export async function dispatchEmailNotification(notification) {
4
5
  const context = { notification };
5
6
  await useNitroApp().hooks.callHook("notify:email", context);
@@ -11,3 +12,7 @@ export async function dispatchSMSNotification(notification) {
11
12
  export async function dispatchSimpleNotification(notification) {
12
13
  await simpleDriver(notification);
13
14
  }
15
+ export async function dispatchPushNotification(notification) {
16
+ if (!notification.userIds.length) return { sent: 0, failed: 0 };
17
+ return await pushDriver(notification) ?? void 0;
18
+ }
@@ -0,0 +1,31 @@
1
+ import type { ChannelSettings, NotificationChannelsDto, NotificationTopic, NotifyUserInput, NotifyUserResult } from '../../../types.js';
2
+ /** The topics modules registered with `extendNotificationTopics`. */
3
+ export declare const registeredNotificationTopics: () => readonly NotificationTopic[];
4
+ export declare const findNotificationTopic: (id: string) => NotificationTopic | undefined;
5
+ /** Every registered topic with what applies to the user (their choice, or the topic's defaults). */
6
+ export declare function readNotificationChannels(userId: number): Promise<NotificationChannelsDto>;
7
+ /**
8
+ * Stores changes to the user's channels through the registered choices store. `changes` maps a topic id to the channels
9
+ * to set; an unknown topic and a channel the topic does not offer are ignored. Only the channels given are passed on:
10
+ * the store merges them per channel into what it has stored (read fresh), so two changes made at once to different
11
+ * channels both stick, and channels never set keep following the topic's defaults. Throws when no choices store is
12
+ * registered.
13
+ */
14
+ export declare function saveNotificationChannels(userId: number, changes: Record<string, Partial<ChannelSettings>>): Promise<void>;
15
+ /**
16
+ * Notifies one user on the channels they chose for `input.topic`: email through `dispatchEmailNotification`, SMS through
17
+ * `dispatchSMSNotification` and push through `dispatchPushNotification`. A channel goes out when the topic offers it, the
18
+ * user's choice (or the topic's default) has it on, there is content for it and the user can be reached on it (an
19
+ * address, a number; push asks notify's push driver).
20
+ *
21
+ * The contacts come from the registered recipient store (`@frigear-nu/users`) and the choices from the registered
22
+ * choices store (`@frigear-nu/preferences`; without it the defaults apply). Without a recipient store nothing is sent and
23
+ * a warning is logged. An error on one channel is logged and does not stop the others or throw; the result says which
24
+ * channels went out and why the others did not.
25
+ *
26
+ * It throws for an unknown topic (register it with `extendNotificationTopics`) and when a store fails: an error from the
27
+ * recipient store's `findRecipient` or the choices store's `readChoices` (a database error) rejects the call before any
28
+ * channel is sent, so nothing goes out on defaults the user may have turned off. Callers in hooks and tasks catch and log
29
+ * it so their own work goes on.
30
+ */
31
+ export declare function notifyUser(userId: number, input: NotifyUserInput): Promise<NotifyUserResult>;
@@ -0,0 +1,108 @@
1
+ import { topics } from "#notify/topics";
2
+ import { choicesStore, recipientStore } from "#notify/stores";
3
+ import { readTranslated, resolveChannelSettings, topicChannels } from "../../utils/topics.js";
4
+ import { dispatchEmailNotification, dispatchPushNotification, dispatchSMSNotification } from "./dispatch.js";
5
+ const warned = /* @__PURE__ */ new Set();
6
+ function warnOnce(key, message) {
7
+ if (warned.has(key)) return;
8
+ warned.add(key);
9
+ console.warn(`[@frigear-nu/notify] ${message}`);
10
+ }
11
+ export const registeredNotificationTopics = () => topics;
12
+ export const findNotificationTopic = (id) => topics.find((topic) => topic.id === id);
13
+ async function readStoredChoices(userId) {
14
+ if (!choicesStore) {
15
+ warnOnce("choices", "No choices store is registered (install @frigear-nu/preferences): every user gets the topics' defaults.");
16
+ return {};
17
+ }
18
+ return choicesStore.readChoices(userId);
19
+ }
20
+ export async function readNotificationChannels(userId) {
21
+ const [choices, recipient] = await Promise.all([readStoredChoices(userId), recipientStore?.findRecipient(userId)]);
22
+ const rows = topics.map((topic) => ({
23
+ id: topic.id,
24
+ label: topic.label ?? topic.id,
25
+ labelKey: topic.labelKey,
26
+ description: topic.description,
27
+ descriptionKey: topic.descriptionKey,
28
+ channels: topicChannels(topic),
29
+ settings: resolveChannelSettings(topic, choices[topic.id]),
30
+ custom: topic.id in choices
31
+ }));
32
+ return { hasPhone: !!recipient?.phone, topics: rows };
33
+ }
34
+ export async function saveNotificationChannels(userId, changes) {
35
+ if (!choicesStore) throw new Error("[@frigear-nu/notify] No choices store is registered: install @frigear-nu/preferences to store notification choices.");
36
+ const next = {};
37
+ for (const [id, change] of Object.entries(changes)) {
38
+ const topic = findNotificationTopic(id);
39
+ if (!topic) continue;
40
+ const offered = topicChannels(topic);
41
+ const allowed = Object.fromEntries(Object.entries(change).filter(([channel, value]) => offered.includes(channel) && typeof value === "boolean"));
42
+ if (Object.keys(allowed).length) next[id] = allowed;
43
+ }
44
+ if (Object.keys(next).length) await choicesStore.writeChoices(userId, next);
45
+ }
46
+ export async function notifyUser(userId, input) {
47
+ const topic = findNotificationTopic(input.topic);
48
+ if (!topic) {
49
+ throw new Error(`[@frigear-nu/notify] Unknown notification topic "${input.topic}". Register it with extendNotificationTopics(nuxt, [{ id, defaults }]).`);
50
+ }
51
+ const result = { channels: [], skipped: {} };
52
+ const offered = topicChannels(topic);
53
+ const content = { email: !!input.email, sms: !!input.sms, push: !!input.push };
54
+ if (!recipientStore) {
55
+ warnOnce("recipient", "No recipient store is registered (install @frigear-nu/users): notifyUser sends nothing.");
56
+ for (const channel of offered) if (content[channel]) result.skipped[channel] = "unavailable";
57
+ return result;
58
+ }
59
+ const [recipient, choices] = await Promise.all([recipientStore.findRecipient(userId), readStoredChoices(userId)]);
60
+ const settings = resolveChannelSettings(topic, choices[topic.id]);
61
+ const locale = recipient?.locale || "en";
62
+ const run = async (channel, send) => {
63
+ if (!offered.includes(channel) || !settings[channel]) {
64
+ result.skipped[channel] = "disabled";
65
+ return;
66
+ }
67
+ if (!content[channel]) {
68
+ result.skipped[channel] = "no_content";
69
+ return;
70
+ }
71
+ if (!recipient) {
72
+ result.skipped[channel] = "unavailable";
73
+ return;
74
+ }
75
+ try {
76
+ if (await send()) result.channels.push(channel);
77
+ else result.skipped[channel] = "unavailable";
78
+ } catch (error) {
79
+ console.error(`[@frigear-nu/notify] notifyUser: the ${channel} channel failed for user ${userId} (${topic.id}):`, error);
80
+ result.skipped[channel] = "failed";
81
+ }
82
+ };
83
+ await run("email", async () => {
84
+ if (!recipient?.email || !input.email) return false;
85
+ const { subject, body, text, replyTo, template, meta } = input.email;
86
+ await dispatchEmailNotification({
87
+ to: recipient.email,
88
+ subject,
89
+ body,
90
+ ...text !== void 0 ? { text } : {},
91
+ ...replyTo !== void 0 ? { replyTo } : {},
92
+ ...template !== void 0 ? { template: template.locale || !recipient.locale ? template : { ...template, locale: recipient.locale } } : {},
93
+ ...meta !== void 0 ? { meta } : {}
94
+ });
95
+ return true;
96
+ });
97
+ await run("sms", async () => {
98
+ if (!recipient?.phone || !input.sms) return false;
99
+ await dispatchSMSNotification({ to: recipient.phone, body: readTranslated(input.sms.body, locale) });
100
+ return true;
101
+ });
102
+ await run("push", async () => {
103
+ if (!input.push) return false;
104
+ const sent = await dispatchPushNotification({ userIds: [userId], ...input.push });
105
+ return sent === void 0 || sent.sent > 0;
106
+ });
107
+ return result;
108
+ }
@@ -0,0 +1,2 @@
1
+ export { NOTIFICATION_CHANNELS, NOTIFICATION_TOPIC_ID_MAX_LENGTH, extendNotificationTopics, readTranslated, resolveChannelSettings, setNotifyChoicesStore, setNotifyRecipientStore, topicChannels, } from './topics.js';
2
+ export type { ChannelSettings, NotificationChannel, NotificationChannelsDto, NotificationChannelsRow, NotificationChoices, NotificationTopic, NotificationTopicDto, NotifyChoicesStore, NotifyRecipient, NotifyRecipientStore, NotifyUserInput, NotifyUserResult, Translated, } from '../../types.js';
@@ -0,0 +1,10 @@
1
+ export {
2
+ NOTIFICATION_CHANNELS,
3
+ NOTIFICATION_TOPIC_ID_MAX_LENGTH,
4
+ extendNotificationTopics,
5
+ readTranslated,
6
+ resolveChannelSettings,
7
+ setNotifyChoicesStore,
8
+ setNotifyRecipientStore,
9
+ topicChannels
10
+ } from "./topics.js";
@@ -0,0 +1,50 @@
1
+ import type { Nuxt } from '@nuxt/schema';
2
+ import type { ChannelSettings, NotificationChannel, NotificationTopic, NotifyBuildState, Translated } from '../../types.js';
3
+ /** Every channel, in the order the account page shows them. */
4
+ export declare const NOTIFICATION_CHANNELS: readonly NotificationChannel[];
5
+ /** The longest topic id: choices are stored under it. */
6
+ export declare const NOTIFICATION_TOPIC_ID_MAX_LENGTH = 100;
7
+ /** The channels a topic offers: its `channels`, or all three. */
8
+ export declare function topicChannels(topic: Pick<NotificationTopic, 'channels'>): NotificationChannel[];
9
+ /**
10
+ * What applies to a user for a topic: a channel the topic does not offer is off; otherwise the stored choice, or the
11
+ * topic's default until the user chose.
12
+ */
13
+ export declare function resolveChannelSettings(topic: Pick<NotificationTopic, 'defaults' | 'channels'>, stored?: Partial<ChannelSettings> | null): ChannelSettings;
14
+ /** A label, description or text to show: the entry for `locale` (then its language, `da` for `da-DK`), then `en`, then the first one. */
15
+ export declare function readTranslated(value: Translated | undefined, locale: string): string;
16
+ /** What other modules registered with notify during their `setup()`, kept on `nuxt.options.notify`. */
17
+ export declare function notifyBuildState(nuxt: Nuxt): NotifyBuildState;
18
+ /**
19
+ * Build-time API for modules to declare the kinds of messages they send with `notifyUser`: one row each on the account
20
+ * notifications page. Call it during a module's own `setup()`; order between modules does not matter. A topic registered
21
+ * again under the same id replaces the earlier one. `notifyUser` refuses topics that are not registered.
22
+ *
23
+ * ```ts
24
+ * import { extendNotificationTopics } from '@frigear-nu/notify/utils'
25
+ *
26
+ * extendNotificationTopics(nuxt, [{
27
+ * id: 'shifts.reminder',
28
+ * label: { da: 'Vagtpåmindelser', en: 'Shift reminders' },
29
+ * defaults: { email: true, sms: false, push: true },
30
+ * }])
31
+ * ```
32
+ */
33
+ export declare function extendNotificationTopics(nuxt: Nuxt, topics: NotificationTopic | NotificationTopic[]): void;
34
+ /**
35
+ * Registers where `notifyUser` finds a user's email, phone and locale: `path` is a module whose default export is a
36
+ * `NotifyRecipientStore`. `@frigear-nu/users` registers one. The first registration wins.
37
+ */
38
+ export declare function setNotifyRecipientStore(nuxt: Nuxt, path: string): void;
39
+ /**
40
+ * Registers where users' channel choices per topic are read and written: `path` is a module whose default export is a
41
+ * `NotifyChoicesStore`. `@frigear-nu/preferences` registers one. The first registration wins.
42
+ */
43
+ export declare function setNotifyChoicesStore(nuxt: Nuxt, path: string): void;
44
+ /** The source of the server-side `#notify/topics`. */
45
+ export declare function topicsTemplate(topics: NotificationTopic[]): string;
46
+ /** The source of the server-side `#notify/stores`: the registered stores, `null` where none is. */
47
+ export declare function storesTemplate(stores: {
48
+ recipient?: string;
49
+ choices?: string;
50
+ }): string;
@@ -0,0 +1,59 @@
1
+ export const NOTIFICATION_CHANNELS = ["email", "sms", "push"];
2
+ const TOPIC_ID = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
3
+ export const NOTIFICATION_TOPIC_ID_MAX_LENGTH = 100;
4
+ export function topicChannels(topic) {
5
+ return NOTIFICATION_CHANNELS.filter((channel) => !topic.channels || topic.channels.includes(channel));
6
+ }
7
+ export function resolveChannelSettings(topic, stored) {
8
+ const result = { email: false, sms: false, push: false };
9
+ for (const channel of topicChannels(topic)) result[channel] = stored?.[channel] ?? topic.defaults[channel] === true;
10
+ return result;
11
+ }
12
+ export function readTranslated(value, locale) {
13
+ if (value === void 0) return "";
14
+ if (typeof value === "string") return value;
15
+ return value[locale] ?? value[locale.split(/[-_]/)[0]] ?? value.en ?? Object.values(value)[0] ?? "";
16
+ }
17
+ export function notifyBuildState(nuxt) {
18
+ const options = nuxt.options;
19
+ return options.notify ||= {};
20
+ }
21
+ function validate(topic) {
22
+ if (!TOPIC_ID.test(topic.id) || topic.id.length > NOTIFICATION_TOPIC_ID_MAX_LENGTH) {
23
+ throw new Error(`[@frigear-nu/notify] Notification topic id "${topic.id}" must be lower case words joined by "." "_" or "-" (for example "shifts.reminder"), at most ${NOTIFICATION_TOPIC_ID_MAX_LENGTH} characters.`);
24
+ }
25
+ for (const channel of topic.channels ?? []) {
26
+ if (!NOTIFICATION_CHANNELS.includes(channel)) throw new Error(`[@frigear-nu/notify] Notification topic "${topic.id}" offers an unknown channel "${channel}".`);
27
+ }
28
+ for (const channel of NOTIFICATION_CHANNELS) {
29
+ if (typeof topic.defaults?.[channel] !== "boolean") {
30
+ throw new TypeError(`[@frigear-nu/notify] Notification topic "${topic.id}" needs \`defaults.${channel}\` (true or false).`);
31
+ }
32
+ }
33
+ return { ...topic, channels: topicChannels(topic) };
34
+ }
35
+ export function extendNotificationTopics(nuxt, topics) {
36
+ const list = notifyBuildState(nuxt)._topics ||= [];
37
+ for (const topic of (Array.isArray(topics) ? topics : [topics]).map(validate)) {
38
+ const existing = list.findIndex((item) => item.id === topic.id);
39
+ if (existing === -1) list.push(topic);
40
+ else list[existing] = topic;
41
+ }
42
+ }
43
+ export function setNotifyRecipientStore(nuxt, path) {
44
+ notifyBuildState(nuxt)._recipientStore ||= path;
45
+ }
46
+ export function setNotifyChoicesStore(nuxt, path) {
47
+ notifyBuildState(nuxt)._choicesStore ||= path;
48
+ }
49
+ export function topicsTemplate(topics) {
50
+ return `export const topics = ${JSON.stringify(topics, null, 2)}
51
+ `;
52
+ }
53
+ export function storesTemplate(stores) {
54
+ return [
55
+ stores.recipient ? `export { default as recipientStore } from ${JSON.stringify(stores.recipient)}` : "export const recipientStore = null",
56
+ stores.choices ? `export { default as choicesStore } from ${JSON.stringify(stores.choices)}` : "export const choicesStore = null",
57
+ ""
58
+ ].join("\n");
59
+ }
package/dist/types.d.mts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { default } from './module.mjs'
2
2
 
3
- export { type EmailDriver, type EmailNotification, type EmailTemplateRef, type EmailTemplateSource, type ModuleOptions, type NotifyEmailContext, type SMSDriver, type SMSNotification, type SimpleDriver, type SimpleNotification } from './module.mjs'
3
+ export { type ChannelSettings, type EmailDriver, type EmailNotification, type EmailTemplateRef, type EmailTemplateSource, type ModuleOptions, type NotificationChannel, type NotificationChannelsDto, type NotificationChannelsRow, type NotificationChoices, type NotificationTopic, type NotificationTopicDto, type NotifyChoicesStore, type NotifyEmailContext, type NotifyRecipient, type NotifyRecipientStore, type NotifyUserInput, type NotifyUserResult, type PushDispatchResult, type PushDriver, type PushNotification, type PushText, type SMSDriver, type SMSNotification, type SimpleDriver, type SimpleNotification, type Translated } from './module.mjs'
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@frigear-nu/notify",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
- "description": "Email, SMS and generic notification dispatch (pluggable drivers) Nuxt module, shared across Frigear modules.",
5
+ "description": "Email, SMS, push and generic notification dispatch (pluggable drivers), and notifyUser: per-user channel choices over a topic registry. Shared across Frigear modules.",
6
6
  "license": "MIT",
7
- "homepage": "https://docs.frigear.dev/modules/platform/notify",
7
+ "homepage": "https://docs.frigear.dev/modules/communication/notify",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/Frigear-nu/frigear-nu.git",
@@ -18,6 +18,11 @@
18
18
  },
19
19
  "./types": {
20
20
  "types": "./dist/types.d.mts"
21
+ },
22
+ "./utils": {
23
+ "types": "./dist/runtime/utils/index.d.ts",
24
+ "import": "./dist/runtime/utils/index.js",
25
+ "default": "./dist/runtime/utils/index.js"
21
26
  }
22
27
  },
23
28
  "files": [
@@ -25,17 +30,17 @@
25
30
  ],
26
31
  "dependencies": {
27
32
  "@nuxt/kit": "^4.6.4",
28
- "@frigear-nu/module-kit": "^1.3.5",
33
+ "@frigear-nu/module-kit": "^1.3.6",
29
34
  "defu": "^6.1.7",
30
35
  "ufo": "^1.6.4"
31
36
  },
32
37
  "devDependencies": {
33
- "@nuxt/devtools": "^4.1.0",
38
+ "@nuxt/devtools": "^4.2.0",
34
39
  "@nuxt/eslint-config": "^1.17.0",
35
- "@nuxt/module-builder": "^1.0.3",
40
+ "@nuxt/module-builder": "^1.0.4",
36
41
  "@nuxt/schema": "^4.6.4",
37
- "@nuxt/test-utils": "^4.3.4",
38
- "eslint": "^10.14.0",
42
+ "@nuxt/test-utils": "^4.4.0",
43
+ "eslint": "^10.15.0",
39
44
  "typescript": "^6.0.3",
40
45
  "nuxt": "^4.6.4",
41
46
  "vitest": "^5.1.0",