@nage-api/notify 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @nage-api/notify
2
+
3
+ Channel-abstracted notifications with templates (PLAN.md §8, §25 P2).
4
+
5
+ The application says "tell this user their order shipped"; whether that becomes
6
+ an email, an SMS, a push, or all three is configuration and per-recipient
7
+ preference, not a branch in domain code.
8
+
9
+ <!-- docs-example: fragment -->
10
+
11
+ ```ts
12
+ import { NotifyService } from '@nage-api/notify';
13
+
14
+ // Exported by `NageNotifyModule.forRoot`, so injecting the class is enough.
15
+ declare const notify: NotifyService;
16
+ declare const user: { id: string; email: string; name: string };
17
+ declare const order: { reference: string };
18
+
19
+ const report = await notify.send({
20
+ template: 'order.shipped',
21
+ to: { id: user.id, email: user.email, locale: 'fr-CA' },
22
+ data: { user, order },
23
+ });
24
+ // → { template: 'order.shipped', results: [ … ], delivered: true, skipped: ['sms'] }
25
+ ```
26
+
27
+ ## Three properties, in order of importance
28
+
29
+ **Preferences are consulted first.** A recipient who opted out of marketing SMS
30
+ must not get one because a new code path forgot to check, so the check lives in
31
+ the service rather than at every call site. Opt-outs can be per channel or per
32
+ channel-and-template.
33
+
34
+ **One channel failing does not fail the rest.** A dead SMS provider should not
35
+ stop the email, so channels are attempted independently and every outcome is
36
+ reported.
37
+
38
+ **A failure never carries the body.** A notification body holds whatever the
39
+ template put in it — a name, an address, an order — and error paths end up in
40
+ logs that live far longer than the message did.
41
+
42
+ ## Templates have no expression language
43
+
44
+ `{{ user.name }}` interpolates a value. That is the entire grammar: no `{{#if}}`,
45
+ no method calls, no property access that reaches a prototype. The moment a
46
+ template can evaluate an expression, a template stored in a database becomes
47
+ remote code execution — and "let marketing edit the emails" is a feature every
48
+ product eventually ships. `{{ constructor.name }}` and `{{ __proto__.x }}`
49
+ render as empty strings.
50
+
51
+ Anything the grammar cannot express belongs in the code that builds the data.
52
+
53
+ Locale selection falls back exact → language → `default`, and interpolated
54
+ values are HTML-escaped in the `html` body only.
55
+
56
+ ## Channels
57
+
58
+ `MemoryChannel` records instead of sending, so a developer can exercise a
59
+ signup flow without an SMTP account and a test can assert on the message that
60
+ would have gone out. Like the queue's memory driver, it is refused in
61
+ production — it would silently swallow every message.
62
+
63
+ ## Not yet implemented
64
+
65
+ - Real channels. `@nage-api/integrations-email` and `@nage-api/integrations-sms` are
66
+ where they belong; `NotificationChannel` is the port they implement.
67
+ - Template loading from `notify.templateDirectory`; templates are registered
68
+ in code today.
69
+ - `notify.from`. It is declared in `NotifyConfig` and this package never reads
70
+ it, so the sender address belongs to whichever channel you supply.
71
+ - Retries. `send` reports a channel's failure and returns; nothing re-attempts
72
+ it. Retrying is `@nage-api/queue`'s job, from a job that calls `send`.
73
+ - Digest/batching, and delivery-receipt tracking.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@nage-api/notify` — channel-abstracted notifications with templates
3
+ * (PLAN.md §8, §25 P2).
4
+ */
5
+ export type * from '@nage-api/contracts';
6
+ export { NageNotifyModule, type NageNotifyModuleOptions } from './notify.module.js';
7
+ export { NotifyService, type NotifyReport, type NotifyServiceOptions } from './notify.service.js';
8
+ export { StringTemplate, escape, interpolate, type StringTemplateDefinition, type StringTemplateOptions, } from './template.js';
9
+ export { MemoryChannel, MemoryPreferenceStore, type CapturedNotification, } from './memory.channels.js';
10
+ export { NAGE_NOTIFY, NAGE_NOTIFY_PREFERENCES } from './tokens.js';
11
+ export type { ChannelName, NotificationChannel, NotificationTemplate, NotifyInput, PreferenceStore, Recipient, RenderedMessage, SendResult, } from './ports.js';
12
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ /**
3
+ * `@nage-api/notify` — channel-abstracted notifications with templates
4
+ * (PLAN.md §8, §25 P2).
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.NAGE_NOTIFY_PREFERENCES = exports.NAGE_NOTIFY = exports.MemoryPreferenceStore = exports.MemoryChannel = exports.interpolate = exports.StringTemplate = exports.NotifyService = exports.NageNotifyModule = void 0;
8
+ var notify_module_js_1 = require("./notify.module.js");
9
+ Object.defineProperty(exports, "NageNotifyModule", { enumerable: true, get: function () { return notify_module_js_1.NageNotifyModule; } });
10
+ var notify_service_js_1 = require("./notify.service.js");
11
+ Object.defineProperty(exports, "NotifyService", { enumerable: true, get: function () { return notify_service_js_1.NotifyService; } });
12
+ var template_js_1 = require("./template.js");
13
+ Object.defineProperty(exports, "StringTemplate", { enumerable: true, get: function () { return template_js_1.StringTemplate; } });
14
+ Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return template_js_1.escape; } });
15
+ Object.defineProperty(exports, "interpolate", { enumerable: true, get: function () { return template_js_1.interpolate; } });
16
+ var memory_channels_js_1 = require("./memory.channels.js");
17
+ Object.defineProperty(exports, "MemoryChannel", { enumerable: true, get: function () { return memory_channels_js_1.MemoryChannel; } });
18
+ Object.defineProperty(exports, "MemoryPreferenceStore", { enumerable: true, get: function () { return memory_channels_js_1.MemoryPreferenceStore; } });
19
+ var tokens_js_1 = require("./tokens.js");
20
+ Object.defineProperty(exports, "NAGE_NOTIFY", { enumerable: true, get: function () { return tokens_js_1.NAGE_NOTIFY; } });
21
+ Object.defineProperty(exports, "NAGE_NOTIFY_PREFERENCES", { enumerable: true, get: function () { return tokens_js_1.NAGE_NOTIFY_PREFERENCES; } });
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Channels that record instead of sending.
3
+ *
4
+ * The default in development and in tests: a developer exercising a signup
5
+ * flow should not need an SMTP account, and a test should be able to assert on
6
+ * the message that would have gone out.
7
+ */
8
+ import type { ChannelName, NotificationChannel, Recipient, RenderedMessage, SendResult } from './ports.js';
9
+ export interface CapturedNotification {
10
+ readonly channel: ChannelName;
11
+ readonly to: Recipient;
12
+ readonly message: RenderedMessage;
13
+ readonly at: number;
14
+ }
15
+ export declare class MemoryChannel implements NotificationChannel {
16
+ readonly name: ChannelName;
17
+ readonly sent: CapturedNotification[];
18
+ /** Set to make the next send fail, for testing partial delivery. */
19
+ failNext: boolean;
20
+ constructor(name: ChannelName);
21
+ supports(recipient: Recipient): boolean;
22
+ send(recipient: Recipient, message: RenderedMessage): Promise<SendResult>;
23
+ /** The most recent message on this channel. */
24
+ latest(): CapturedNotification | undefined;
25
+ }
26
+ /** Opt-outs held in memory; a real deployment stores them per user. */
27
+ export declare class MemoryPreferenceStore {
28
+ #private;
29
+ block(recipientId: string, channel: ChannelName, template?: string): this;
30
+ allows(recipientId: string, channel: ChannelName, template: string): Promise<boolean>;
31
+ }
32
+ //# sourceMappingURL=memory.channels.d.ts.map
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /**
3
+ * Channels that record instead of sending.
4
+ *
5
+ * The default in development and in tests: a developer exercising a signup
6
+ * flow should not need an SMTP account, and a test should be able to assert on
7
+ * the message that would have gone out.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.MemoryPreferenceStore = exports.MemoryChannel = void 0;
11
+ const core_1 = require("@nage-api/core");
12
+ class MemoryChannel {
13
+ name;
14
+ sent = [];
15
+ /** Set to make the next send fail, for testing partial delivery. */
16
+ failNext = false;
17
+ constructor(name) {
18
+ this.name = name;
19
+ }
20
+ supports(recipient) {
21
+ switch (this.name) {
22
+ case 'email':
23
+ return recipient.email !== undefined;
24
+ case 'sms':
25
+ return recipient.phone !== undefined;
26
+ case 'push':
27
+ return (recipient.deviceTokens?.length ?? 0) > 0;
28
+ }
29
+ }
30
+ async send(recipient, message) {
31
+ await Promise.resolve();
32
+ if (this.failNext) {
33
+ this.failNext = false;
34
+ throw new Error(`${this.name} provider refused the message`);
35
+ }
36
+ this.sent.push({ channel: this.name, to: recipient, message, at: Date.now() });
37
+ return { channel: this.name, delivered: true, messageId: (0, core_1.randomId)() };
38
+ }
39
+ /** The most recent message on this channel. */
40
+ latest() {
41
+ return this.sent[this.sent.length - 1];
42
+ }
43
+ }
44
+ exports.MemoryChannel = MemoryChannel;
45
+ /** Opt-outs held in memory; a real deployment stores them per user. */
46
+ class MemoryPreferenceStore {
47
+ #blocked = new Set();
48
+ block(recipientId, channel, template) {
49
+ this.#blocked.add(`${recipientId}:${channel}:${template ?? '*'}`);
50
+ return this;
51
+ }
52
+ async allows(recipientId, channel, template) {
53
+ await Promise.resolve();
54
+ return (!this.#blocked.has(`${recipientId}:${channel}:*`) &&
55
+ !this.#blocked.has(`${recipientId}:${channel}:${template}`));
56
+ }
57
+ }
58
+ exports.MemoryPreferenceStore = MemoryPreferenceStore;
59
+ //# sourceMappingURL=memory.channels.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * `NageNotifyModule.forRoot(config)` (PLAN.md §11.1 item 6).
3
+ *
4
+ * Channels are supplied by the application, because a real one needs a
5
+ * provider SDK and a credential. The in-memory channels are the default so the
6
+ * flow works before either exists — and, like the queue's in-memory driver,
7
+ * they are refused in production, where "the emails silently went nowhere" is
8
+ * the failure they would otherwise produce.
9
+ */
10
+ import { type DynamicModule } from '@nestjs/common';
11
+ import type { NotifyConfig } from '@nage-api/contracts';
12
+ import type { NotificationChannel, NotificationTemplate, PreferenceStore } from './ports.js';
13
+ export interface NageNotifyModuleOptions {
14
+ readonly notify?: NotifyConfig;
15
+ readonly environment?: string;
16
+ readonly channels?: readonly NotificationChannel[];
17
+ readonly templates?: readonly NotificationTemplate[];
18
+ readonly preferences?: PreferenceStore;
19
+ }
20
+ export declare class NageNotifyModule {
21
+ static forRoot(options?: NageNotifyModuleOptions): DynamicModule;
22
+ private static memoryChannels;
23
+ }
24
+ //# sourceMappingURL=notify.module.d.ts.map
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ /**
3
+ * `NageNotifyModule.forRoot(config)` (PLAN.md §11.1 item 6).
4
+ *
5
+ * Channels are supplied by the application, because a real one needs a
6
+ * provider SDK and a credential. The in-memory channels are the default so the
7
+ * flow works before either exists — and, like the queue's in-memory driver,
8
+ * they are refused in production, where "the emails silently went nowhere" is
9
+ * the failure they would otherwise produce.
10
+ */
11
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
12
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
14
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
15
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
16
+ };
17
+ var NageNotifyModule_1;
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.NageNotifyModule = void 0;
20
+ const common_1 = require("@nestjs/common");
21
+ const core_1 = require("@nage-api/core");
22
+ const memory_channels_js_1 = require("./memory.channels.js");
23
+ const notify_service_js_1 = require("./notify.service.js");
24
+ const tokens_js_1 = require("./tokens.js");
25
+ let NageNotifyModule = NageNotifyModule_1 = class NageNotifyModule {
26
+ static forRoot(options = {}) {
27
+ const config = options.notify ?? {};
28
+ if (config.enabled !== true) {
29
+ return { module: NageNotifyModule_1, providers: [], exports: [] };
30
+ }
31
+ const wanted = config.channels ?? ['email'];
32
+ const channels = options.channels ?? NageNotifyModule_1.memoryChannels(wanted, options);
33
+ const service = new notify_service_js_1.NotifyService({
34
+ channels,
35
+ templates: options.templates ?? [],
36
+ ...(options.preferences === undefined ? {} : { preferences: options.preferences }),
37
+ // Only a configured list becomes the default. Passing `wanted` here
38
+ // unconditionally made its `['email']` fallback the default for an
39
+ // application that supplied its own channels, so an app registering an
40
+ // SMS channel and configuring none sent nothing and reported no error.
41
+ // With the key absent the service defaults to every channel it was given.
42
+ ...(config.channels === undefined ? {} : { defaultChannels: config.channels }),
43
+ });
44
+ const providers = [
45
+ { provide: tokens_js_1.NAGE_NOTIFY, useValue: service },
46
+ { provide: notify_service_js_1.NotifyService, useValue: service },
47
+ ...(options.preferences === undefined
48
+ ? []
49
+ : [{ provide: tokens_js_1.NAGE_NOTIFY_PREFERENCES, useValue: options.preferences }]),
50
+ ];
51
+ return {
52
+ module: NageNotifyModule_1,
53
+ providers,
54
+ exports: [
55
+ tokens_js_1.NAGE_NOTIFY,
56
+ notify_service_js_1.NotifyService,
57
+ ...(options.preferences === undefined ? [] : [tokens_js_1.NAGE_NOTIFY_PREFERENCES]),
58
+ ],
59
+ };
60
+ }
61
+ static memoryChannels(wanted, options) {
62
+ if (options.environment === 'production' || options.environment === 'staging') {
63
+ throw new core_1.ConfigurationError({
64
+ detail: 'The in-memory notification channels record messages instead of sending them; pass real channels to NageNotifyModule.forRoot({ channels }) in a deployed environment',
65
+ meta: { environment: options.environment },
66
+ });
67
+ }
68
+ return wanted.map((name) => new memory_channels_js_1.MemoryChannel(name));
69
+ }
70
+ };
71
+ exports.NageNotifyModule = NageNotifyModule;
72
+ exports.NageNotifyModule = NageNotifyModule = NageNotifyModule_1 = __decorate([
73
+ (0, common_1.Module)({})
74
+ ], NageNotifyModule);
75
+ //# sourceMappingURL=notify.module.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Sending a notification across channels (PLAN.md §8).
3
+ *
4
+ * Three properties, in the order they matter:
5
+ *
6
+ * **Preferences are consulted first.** A recipient who opted out of marketing
7
+ * SMS must not receive one because a new code path forgot to check. The check
8
+ * lives here, once, rather than at every call site.
9
+ *
10
+ * **One channel failing does not fail the rest.** A dead SMS provider should
11
+ * not stop the email going out, so channels are attempted independently and
12
+ * every outcome is reported.
13
+ *
14
+ * **A failure never carries the body.** A notification body contains whatever
15
+ * the template put in it — a name, an address, an order — and error paths end
16
+ * up in logs that live far longer than the message did.
17
+ */
18
+ import type { ChannelName, NotificationChannel, NotificationTemplate, NotifyInput, PreferenceStore, SendResult } from './ports.js';
19
+ export interface NotifyServiceOptions {
20
+ readonly channels: readonly NotificationChannel[];
21
+ readonly templates: readonly NotificationTemplate[];
22
+ readonly preferences?: PreferenceStore;
23
+ /** Channels used when an input names none. Defaults to every registered one. */
24
+ readonly defaultChannels?: readonly ChannelName[];
25
+ }
26
+ export interface NotifyReport {
27
+ readonly template: string;
28
+ readonly results: readonly SendResult[];
29
+ /** True when at least one channel delivered. */
30
+ readonly delivered: boolean;
31
+ /** Channels skipped by preference or because the recipient lacks an address. */
32
+ readonly skipped: readonly ChannelName[];
33
+ }
34
+ export declare class NotifyService {
35
+ #private;
36
+ constructor(options: NotifyServiceOptions);
37
+ /**
38
+ * Render and deliver.
39
+ *
40
+ * @throws ConfigurationError when the template is not registered — a typo in
41
+ * a template name should fail loudly rather than silently send nothing.
42
+ */
43
+ send<TData extends Record<string, unknown>>(input: NotifyInput<TData>): Promise<NotifyReport>;
44
+ get channels(): readonly ChannelName[];
45
+ get templates(): readonly string[];
46
+ }
47
+ //# sourceMappingURL=notify.service.d.ts.map
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ /**
3
+ * Sending a notification across channels (PLAN.md §8).
4
+ *
5
+ * Three properties, in the order they matter:
6
+ *
7
+ * **Preferences are consulted first.** A recipient who opted out of marketing
8
+ * SMS must not receive one because a new code path forgot to check. The check
9
+ * lives here, once, rather than at every call site.
10
+ *
11
+ * **One channel failing does not fail the rest.** A dead SMS provider should
12
+ * not stop the email going out, so channels are attempted independently and
13
+ * every outcome is reported.
14
+ *
15
+ * **A failure never carries the body.** A notification body contains whatever
16
+ * the template put in it — a name, an address, an order — and error paths end
17
+ * up in logs that live far longer than the message did.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.NotifyService = void 0;
21
+ const core_1 = require("@nage-api/core");
22
+ class NotifyService {
23
+ #channels = new Map();
24
+ #templates = new Map();
25
+ #preferences;
26
+ #defaultChannels;
27
+ constructor(options) {
28
+ for (const channel of options.channels)
29
+ this.#channels.set(channel.name, channel);
30
+ for (const template of options.templates)
31
+ this.#templates.set(template.name, template);
32
+ this.#preferences = options.preferences;
33
+ this.#defaultChannels = options.defaultChannels ?? [...this.#channels.keys()];
34
+ }
35
+ /**
36
+ * Render and deliver.
37
+ *
38
+ * @throws ConfigurationError when the template is not registered — a typo in
39
+ * a template name should fail loudly rather than silently send nothing.
40
+ */
41
+ async send(input) {
42
+ const template = this.#templates.get(input.template);
43
+ if (template === undefined) {
44
+ throw new core_1.ConfigurationError({
45
+ detail: `No notification template named "${input.template}" is registered`,
46
+ meta: { template: input.template, available: [...this.#templates.keys()] },
47
+ });
48
+ }
49
+ const requested = input.channels ?? this.#defaultChannels;
50
+ const results = [];
51
+ const skipped = [];
52
+ const message = template.render(input.data, input.to.locale);
53
+ for (const name of requested) {
54
+ const channel = this.#channels.get(name);
55
+ if (!channel?.supports(input.to)) {
56
+ skipped.push(name);
57
+ continue;
58
+ }
59
+ if (!(await this.#allowed(input.to, name, input.template))) {
60
+ skipped.push(name);
61
+ continue;
62
+ }
63
+ results.push(await this.#deliver(channel, input.to, message));
64
+ }
65
+ return {
66
+ template: input.template,
67
+ results,
68
+ delivered: results.some((result) => result.delivered),
69
+ skipped,
70
+ };
71
+ }
72
+ get channels() {
73
+ return [...this.#channels.keys()];
74
+ }
75
+ get templates() {
76
+ return [...this.#templates.keys()];
77
+ }
78
+ async #allowed(to, channel, template) {
79
+ if (this.#preferences === undefined || to.id === undefined)
80
+ return true;
81
+ return this.#preferences.allows(to.id, channel, template);
82
+ }
83
+ async #deliver(channel, to, message) {
84
+ try {
85
+ return await channel.send(to, message);
86
+ }
87
+ catch (error) {
88
+ // One channel throwing must not take the others down with it.
89
+ return {
90
+ channel: channel.name,
91
+ delivered: false,
92
+ error: error instanceof Error ? error.message : String(error),
93
+ };
94
+ }
95
+ }
96
+ }
97
+ exports.NotifyService = NotifyService;
98
+ //# sourceMappingURL=notify.service.js.map
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Notifications (PLAN.md §8, §25 P2).
3
+ *
4
+ * One message, several channels. The application says "tell this user their
5
+ * order shipped"; whether that becomes an email, an SMS, a push, or all three
6
+ * is configuration and per-recipient preference, not a branch in domain code.
7
+ *
8
+ * Channels are ports, so `@nage-api/integrations-email` and friends can implement
9
+ * them without this package depending on any provider SDK.
10
+ */
11
+ export type ChannelName = 'email' | 'sms' | 'push';
12
+ /** Where a notification is going, per channel. */
13
+ export interface Recipient {
14
+ /** Identifies the person, for preferences and audit. */
15
+ readonly id?: string;
16
+ readonly email?: string;
17
+ readonly phone?: string;
18
+ /** Device tokens for push. */
19
+ readonly deviceTokens?: readonly string[];
20
+ /** BCP 47 tag used to pick a template translation. */
21
+ readonly locale?: string;
22
+ }
23
+ /** A rendered message, ready for one channel. */
24
+ export interface RenderedMessage {
25
+ readonly subject?: string;
26
+ readonly body: string;
27
+ /** HTML body for channels that support it. */
28
+ readonly html?: string;
29
+ }
30
+ export interface SendResult {
31
+ readonly channel: ChannelName;
32
+ readonly delivered: boolean;
33
+ /** Provider message id, when there is one. */
34
+ readonly messageId?: string;
35
+ /** Why it failed. Never the message body, which may be personal. */
36
+ readonly error?: string;
37
+ }
38
+ /** A delivery channel. */
39
+ export interface NotificationChannel {
40
+ readonly name: ChannelName;
41
+ /** Whether this recipient can be reached on this channel at all. */
42
+ supports(recipient: Recipient): boolean;
43
+ send(recipient: Recipient, message: RenderedMessage): Promise<SendResult>;
44
+ }
45
+ /**
46
+ * A template, identified by name and rendered per locale.
47
+ *
48
+ * Templates are data, not code: a `render` that evaluated arbitrary
49
+ * expressions from a stored string would be a server-side template injection
50
+ * waiting for someone to make templates editable in an admin screen.
51
+ */
52
+ export interface NotificationTemplate<TData = Record<string, unknown>> {
53
+ readonly name: string;
54
+ render(data: TData, locale?: string): RenderedMessage;
55
+ }
56
+ /** Per-recipient opt-outs, consulted before every send. */
57
+ export interface PreferenceStore {
58
+ /** False means "do not contact this person on this channel". */
59
+ allows(recipientId: string, channel: ChannelName, template: string): Promise<boolean>;
60
+ }
61
+ export interface NotifyInput<TData = Record<string, unknown>> {
62
+ readonly template: string;
63
+ readonly to: Recipient;
64
+ readonly data: TData;
65
+ /** Restrict to these channels; defaults to every configured one. */
66
+ readonly channels?: readonly ChannelName[];
67
+ }
68
+ //# sourceMappingURL=ports.d.ts.map
package/dist/ports.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ /**
3
+ * Notifications (PLAN.md §8, §25 P2).
4
+ *
5
+ * One message, several channels. The application says "tell this user their
6
+ * order shipped"; whether that becomes an email, an SMS, a push, or all three
7
+ * is configuration and per-recipient preference, not a branch in domain code.
8
+ *
9
+ * Channels are ports, so `@nage-api/integrations-email` and friends can implement
10
+ * them without this package depending on any provider SDK.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Template rendering, deliberately without an expression language.
3
+ *
4
+ * `{{ user.name }}` interpolates a value. That is the whole grammar. There is
5
+ * no `{{#if}}`, no method calls, no property access on prototypes — because
6
+ * the moment a template can evaluate an expression, a template stored in a
7
+ * database becomes remote code execution, and "let marketing edit the emails"
8
+ * is a feature every product eventually ships.
9
+ *
10
+ * Anything the grammar cannot express belongs in the code that builds the
11
+ * template's data.
12
+ */
13
+ import type { NotificationTemplate, RenderedMessage } from './ports.js';
14
+ export interface StringTemplateDefinition {
15
+ readonly subject?: string;
16
+ readonly body: string;
17
+ readonly html?: string;
18
+ }
19
+ export interface StringTemplateOptions {
20
+ readonly name: string;
21
+ /** One definition per locale; `default` is the fallback. */
22
+ readonly locales: Readonly<Record<string, StringTemplateDefinition>>;
23
+ /** Escape interpolated values for HTML. On for the `html` body only. */
24
+ readonly escapeHtml?: boolean;
25
+ }
26
+ export declare class StringTemplate implements NotificationTemplate {
27
+ #private;
28
+ readonly name: string;
29
+ constructor(options: StringTemplateOptions);
30
+ render(data: Record<string, unknown>, locale?: string): RenderedMessage;
31
+ }
32
+ /**
33
+ * Replace `{{ path }}` with a value from `data`.
34
+ *
35
+ * A placeholder whose path is missing renders as an empty string rather than
36
+ * as the literal `{{ path }}`: an email that reads "Hello {{ user.name }}" is
37
+ * worse than one that reads "Hello".
38
+ */
39
+ export declare function interpolate(template: string, data: Record<string, unknown>, escapeHtml: boolean): string;
40
+ /** The five characters that matter in an HTML body. */
41
+ export declare function escape(value: string): string;
42
+ //# sourceMappingURL=template.d.ts.map
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ /**
3
+ * Template rendering, deliberately without an expression language.
4
+ *
5
+ * `{{ user.name }}` interpolates a value. That is the whole grammar. There is
6
+ * no `{{#if}}`, no method calls, no property access on prototypes — because
7
+ * the moment a template can evaluate an expression, a template stored in a
8
+ * database becomes remote code execution, and "let marketing edit the emails"
9
+ * is a feature every product eventually ships.
10
+ *
11
+ * Anything the grammar cannot express belongs in the code that builds the
12
+ * template's data.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.StringTemplate = void 0;
16
+ exports.interpolate = interpolate;
17
+ exports.escape = escape;
18
+ const core_1 = require("@nage-api/core");
19
+ /** `{{ path.to.value }}`, and nothing else. */
20
+ const PLACEHOLDER = /\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\s*\}\}/g;
21
+ /** Keys that would reach the prototype chain rather than the data. */
22
+ const FORBIDDEN_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype']);
23
+ class StringTemplate {
24
+ name;
25
+ #locales;
26
+ #escapeHtml;
27
+ constructor(options) {
28
+ if (options.locales['default'] === undefined) {
29
+ throw new core_1.ConfigurationError({
30
+ detail: `Template "${options.name}" has no "default" locale to fall back to`,
31
+ meta: { template: options.name },
32
+ });
33
+ }
34
+ this.name = options.name;
35
+ this.#locales = options.locales;
36
+ this.#escapeHtml = options.escapeHtml ?? true;
37
+ }
38
+ render(data, locale) {
39
+ const definition = this.#definitionFor(locale);
40
+ return {
41
+ ...(definition.subject === undefined
42
+ ? {}
43
+ : { subject: interpolate(definition.subject, data, false) }),
44
+ body: interpolate(definition.body, data, false),
45
+ ...(definition.html === undefined
46
+ ? {}
47
+ : { html: interpolate(definition.html, data, this.#escapeHtml) }),
48
+ };
49
+ }
50
+ /** Exact locale, then the language, then the default. */
51
+ #definitionFor(locale) {
52
+ if (locale !== undefined) {
53
+ const exact = this.#locales[locale];
54
+ if (exact !== undefined)
55
+ return exact;
56
+ const language = locale.split('-')[0];
57
+ const byLanguage = language === undefined ? undefined : this.#locales[language];
58
+ if (byLanguage !== undefined)
59
+ return byLanguage;
60
+ }
61
+ // Non-null: the constructor refuses a template without one.
62
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guarded in the constructor
63
+ return this.#locales['default'];
64
+ }
65
+ }
66
+ exports.StringTemplate = StringTemplate;
67
+ /**
68
+ * Replace `{{ path }}` with a value from `data`.
69
+ *
70
+ * A placeholder whose path is missing renders as an empty string rather than
71
+ * as the literal `{{ path }}`: an email that reads "Hello {{ user.name }}" is
72
+ * worse than one that reads "Hello".
73
+ */
74
+ function interpolate(template, data, escapeHtml) {
75
+ return template.replace(PLACEHOLDER, (_match, path) => {
76
+ const value = lookup(data, path);
77
+ if (value === undefined || value === null)
78
+ return '';
79
+ const text = stringify(value);
80
+ return escapeHtml ? escape(text) : text;
81
+ });
82
+ }
83
+ /**
84
+ * Render a looked-up value as text.
85
+ *
86
+ * Explicit per type rather than `String(value)`: an object would become
87
+ * "[object Object]", and a function or a symbol would throw — neither is what
88
+ * a template author meant to put in a customer-facing message.
89
+ */
90
+ function stringify(value) {
91
+ switch (typeof value) {
92
+ case 'string':
93
+ return value;
94
+ case 'number':
95
+ case 'boolean':
96
+ case 'bigint':
97
+ return String(value);
98
+ case 'object':
99
+ return json(value);
100
+ default:
101
+ // A function or a symbol reached a template; render nothing rather than
102
+ // leak an implementation detail.
103
+ return '';
104
+ }
105
+ }
106
+ /**
107
+ * `JSON.stringify` for a value that is on its way to a customer.
108
+ *
109
+ * It throws on a cycle and on a bigint nested inside an object, and returns
110
+ * `undefined` when the value's own `toJSON` does. Rendering happens before any
111
+ * channel is attempted, so letting the throw escape would abort the whole
112
+ * notification over one placeholder — the opposite of the missing-value rule
113
+ * above — and the `undefined` would reach the recipient as the word
114
+ * "undefined".
115
+ */
116
+ function json(value) {
117
+ try {
118
+ // `unknown` rather than the `string` the lib's signature claims, which is
119
+ // wrong for a value whose own `toJSON` returns `undefined`.
120
+ const text = JSON.stringify(value);
121
+ return typeof text === 'string' ? text : '';
122
+ }
123
+ catch {
124
+ return '';
125
+ }
126
+ }
127
+ function lookup(data, path) {
128
+ let current = data;
129
+ for (const segment of path.split('.')) {
130
+ // Prototype-chain access is how `{{ constructor.constructor }}` becomes a
131
+ // way to reach `Function`.
132
+ if (FORBIDDEN_SEGMENTS.has(segment))
133
+ return undefined;
134
+ if (typeof current !== 'object' || current === null)
135
+ return undefined;
136
+ if (!Object.hasOwn(current, segment))
137
+ return undefined;
138
+ current = current[segment];
139
+ }
140
+ return current;
141
+ }
142
+ /** The five characters that matter in an HTML body. */
143
+ function escape(value) {
144
+ return value
145
+ .replace(/&/g, '&amp;')
146
+ .replace(/</g, '&lt;')
147
+ .replace(/>/g, '&gt;')
148
+ .replace(/"/g, '&quot;')
149
+ .replace(/'/g, '&#39;');
150
+ }
151
+ //# sourceMappingURL=template.js.map
@@ -0,0 +1,7 @@
1
+ /** DI tokens for notifications (PLAN.md §7.3). */
2
+ import { type Token } from '@nage-api/core';
3
+ import type { NotifyService } from './notify.service.js';
4
+ import type { PreferenceStore } from './ports.js';
5
+ export declare const NAGE_NOTIFY: Token<NotifyService>;
6
+ export declare const NAGE_NOTIFY_PREFERENCES: Token<PreferenceStore>;
7
+ //# sourceMappingURL=tokens.d.ts.map
package/dist/tokens.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ /** DI tokens for notifications (PLAN.md §7.3). */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.NAGE_NOTIFY_PREFERENCES = exports.NAGE_NOTIFY = void 0;
5
+ const core_1 = require("@nage-api/core");
6
+ exports.NAGE_NOTIFY = (0, core_1.createToken)('NAGE_NOTIFY');
7
+ exports.NAGE_NOTIFY_PREFERENCES = (0, core_1.createToken)('NAGE_NOTIFY_PREFERENCES');
8
+ //# sourceMappingURL=tokens.js.map
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@nage-api/notify",
3
+ "version": "1.0.0-beta.2",
4
+ "description": "Notifications for @nage-api — channel abstraction and templates",
5
+ "license": "Apache-2.0",
6
+ "type": "commonjs",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "!dist/.tsbuildinfo",
20
+ "!dist/**/*.map",
21
+ "README.md"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "dependencies": {
27
+ "@nage-api/contracts": "1.0.0-beta.2",
28
+ "@nage-api/core": "1.0.0-beta.2"
29
+ },
30
+ "peerDependencies": {
31
+ "@nestjs/common": "^11.0.0",
32
+ "@nestjs/core": "^11.0.0",
33
+ "reflect-metadata": "^0.2.0"
34
+ },
35
+ "devDependencies": {
36
+ "@nestjs/common": "11.1.29",
37
+ "@nestjs/core": "11.1.29",
38
+ "@nestjs/testing": "11.1.29",
39
+ "@swc/core": "1.15.47",
40
+ "@types/node": "22.20.1",
41
+ "@vitest/coverage-v8": "4.1.10",
42
+ "reflect-metadata": "0.2.2",
43
+ "rimraf": "6.1.3",
44
+ "rxjs": "7.8.2",
45
+ "typescript": "5.9.3",
46
+ "unplugin-swc": "1.5.11",
47
+ "vitest": "4.1.10",
48
+ "@nage-api/testing": "1.0.0-beta.2"
49
+ },
50
+ "engines": {
51
+ "node": ">=22.0.0"
52
+ },
53
+ "scripts": {
54
+ "build": "tsc -b tsconfig.build.json",
55
+ "clean": "rimraf dist .turbo",
56
+ "typecheck": "tsc -p tsconfig.json --noEmit",
57
+ "test": "vitest run"
58
+ }
59
+ }