@blamejs/core 0.7.18 → 0.7.19

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 (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
package/lib/notify.js CHANGED
@@ -1,612 +1,612 @@
1
- "use strict";
2
- /**
3
- * b.notify — generic notification dispatcher.
4
- *
5
- * Composes existing primitives — retry/backoff (b.retry), per-call
6
- * timeout (b.safeAsync.withTimeout), per-channel circuit breaker
7
- * (b.retry.CircuitBreaker), span+counter wrapping
8
- * (b.observability.tap), audit emission (b.audit.safeEmit),
9
- * 5 W's actor context (b.requestHelpers.extractActorContext), URL
10
- * validation (b.safeUrl.parse), HTTP I/O (b.httpClient.request), PII
11
- * redaction (b.redact.redact). Notify never re-implements any of these
12
- * — its job is to coordinate them around a transport abstraction.
13
- *
14
- * var notify = b.notify.create({
15
- * channels: {
16
- * slack: b.notify.transports.httpJson({ url: process.env.SLACK_HOOK }),
17
- * sms: operatorTwilioShim,
18
- * log: b.notify.transports.log(),
19
- * },
20
- * audit: b.audit,
21
- * });
22
- *
23
- * await notify.send({ channel: "slack", message: { text: "Hello" } });
24
- *
25
- * Transport contract:
26
- *
27
- * {
28
- * name: "slack",
29
- * send: async function (message, sendOpts) {
30
- * // Returns { id?, status, attempts?, durationMs? }
31
- * // Throws on permanent failure. For transient failures, throw
32
- * // with err.statusCode in b.retry.RETRYABLE_HTTP_STATUS or
33
- * // err.code in b.retry.RETRYABLE_NET_ERRORS — retry classifies
34
- * // them automatically. Operators can also set err.transient =
35
- * // true for shapes outside that classification.
36
- * },
37
- * }
38
- *
39
- * What this primitive intentionally does NOT do (per scope):
40
- * - Ship vendor SDKs (Twilio / FCM / APNs / Slack-API): operator brings
41
- * transports; the framework provides the contract + httpJson +
42
- * log + test built-ins.
43
- * - Render templates / handle i18n: operator uses b.template + b.i18n.
44
- * - Track recipient preferences: operator app concern.
45
- * - Replace b.mail (SMTP/MIME stays its own primitive).
46
- * - Replace b.websocketChannels (different abstraction —
47
- * transient pub/sub, not retry-on-fail delivery).
48
- */
49
-
50
- var lazyRequire = require("./lazy-require");
51
- var bootLog = require("./log");
52
- var numericChecks = require("./numeric-checks");
53
- var requestHelpers = require("./request-helpers");
54
- var safeAsync = require("./safe-async");
55
- var safeUrl = require("./safe-url");
56
- var validateOpts = require("./validate-opts");
57
- var C = require("./constants");
58
- var { NotifyError } = require("./framework-error");
59
-
60
- // Lazy-required modules to avoid load-order cycles. retry / observability /
61
- // redact / httpClient don't currently import notify, but treating them
62
- // the same way every primitive does keeps the load-order story uniform.
63
- var retryModule = lazyRequire(function () { return require("./retry"); });
64
- var observability = lazyRequire(function () { return require("./observability"); });
65
- var redactModule = lazyRequire(function () { return require("./redact"); });
66
- var httpClientModule = lazyRequire(function () { return require("./http-client"); });
67
-
68
- var _err = NotifyError.factory;
69
-
70
- var DEFAULTS = Object.freeze({
71
- auditSuccess: true,
72
- auditFailures: true,
73
- defaultTimeoutMs: C.TIME.seconds(30),
74
- // defaultRetry inherits from b.retry.DEFAULT_RETRY at create time so
75
- // we get the framework's policy without forking the constants.
76
- });
77
-
78
- // ---- Call-site validation (throw on bad input) ----
79
-
80
- var _isFiniteNonNegative = numericChecks.isFiniteNonNegative;
81
-
82
- function _validateTransport(name, t) {
83
- if (!t || typeof t !== "object") {
84
- throw _err("BAD_OPT", "notify: transport for channel '" + name +
85
- "' must be an object with a send() function");
86
- }
87
- if (typeof t.send !== "function") {
88
- throw _err("BAD_OPT", "notify: transport for channel '" + name +
89
- "' is missing required send() function");
90
- }
91
- }
92
-
93
- function _validateChannelEntry(name, entry) {
94
- if (typeof entry !== "object" || entry === null) {
95
- throw _err("BAD_OPT", "notify: channel '" + name + "' must map to a transport or { transport, ... } object");
96
- }
97
- // Two accepted shapes:
98
- // - Transport object directly: { name, send }
99
- // - Channel-config object: { transport, retry?, breaker?, timeoutMs?, serialize? }
100
- if (typeof entry.send === "function") {
101
- return { transport: entry, retry: null, breaker: null, timeoutMs: null, serialize: false };
102
- }
103
- if (entry.transport === undefined) {
104
- throw _err("BAD_OPT", "notify: channel '" + name +
105
- "': must be a transport (with send fn) OR an object with .transport");
106
- }
107
- _validateTransport(name, entry.transport);
108
- if (entry.retry !== undefined && (typeof entry.retry !== "object" || entry.retry === null)) {
109
- throw _err("BAD_OPT", "notify: channel '" + name + "' retry must be a b.retry.withRetry opts object");
110
- }
111
- if (entry.breaker !== undefined && entry.breaker !== null && typeof entry.breaker !== "object") {
112
- throw _err("BAD_OPT", "notify: channel '" + name + "' breaker must be a b.retry.CircuitBreaker opts object or null");
113
- }
114
- if (entry.timeoutMs !== undefined && entry.timeoutMs !== 0 && !_isFiniteNonNegative(entry.timeoutMs)) {
115
- throw _err("BAD_OPT", "notify: channel '" + name + "' timeoutMs must be a non-negative finite number (0 disables)");
116
- }
117
- if (entry.serialize !== undefined && typeof entry.serialize !== "boolean") {
118
- throw _err("BAD_OPT", "notify: channel '" + name + "' serialize must be a boolean");
119
- }
120
- return {
121
- transport: entry.transport,
122
- retry: entry.retry || null,
123
- breaker: entry.breaker || null,
124
- timeoutMs: (entry.timeoutMs !== undefined) ? entry.timeoutMs : null,
125
- serialize: entry.serialize === true,
126
- };
127
- }
128
-
129
- function _validateCreateOpts(opts) {
130
- validateOpts.requireObject(opts, "notify.create", NotifyError);
131
- if (!opts.channels || typeof opts.channels !== "object") {
132
- throw _err("BAD_OPT", "notify.create: channels must be an object mapping channel names to transports");
133
- }
134
- var keys = Object.keys(opts.channels);
135
- if (keys.length === 0) {
136
- throw _err("BAD_OPT", "notify.create: channels object must have at least one channel");
137
- }
138
- validateOpts.auditShape(opts.audit, "notify.create", NotifyError);
139
- validateOpts.optionalBoolean(opts.auditSuccess, "notify.create: auditSuccess", NotifyError);
140
- validateOpts.optionalBoolean(opts.auditFailures, "notify.create: auditFailures", NotifyError);
141
- if (opts.redact !== undefined && opts.redact !== null && typeof opts.redact !== "function") {
142
- throw _err("BAD_OPT", "notify.create: redact must be a function returning a redacted message");
143
- }
144
- if (opts.defaultTimeoutMs !== undefined &&
145
- opts.defaultTimeoutMs !== 0 &&
146
- !_isFiniteNonNegative(opts.defaultTimeoutMs)) {
147
- throw _err("BAD_OPT", "notify.create: defaultTimeoutMs must be a non-negative finite number (0 disables)");
148
- }
149
- if (opts.defaultRetry !== undefined && opts.defaultRetry !== null &&
150
- (typeof opts.defaultRetry !== "object")) {
151
- throw _err("BAD_OPT", "notify.create: defaultRetry must be a b.retry.withRetry opts object");
152
- }
153
- if (opts.defaultBreaker !== undefined && opts.defaultBreaker !== null &&
154
- typeof opts.defaultBreaker !== "object") {
155
- throw _err("BAD_OPT", "notify.create: defaultBreaker must be a b.retry.CircuitBreaker opts object");
156
- }
157
- validateOpts.optionalObjectWithMethod(opts.queue, "enqueue",
158
- "notify.create: queue", NotifyError, "BAD_OPT",
159
- "must be a b.queue-shaped handle (enqueue fn)");
160
- validateOpts.optionalFunction(opts.clock, "notify.create: clock", NotifyError);
161
- }
162
-
163
- // ---- Built-in transports ----
164
-
165
- // httpJson — POST JSON to a URL via b.httpClient. Default `transient`
166
- // classifier defers to b.retry.isRetryable so HTTP/network classification
167
- // matches the rest of the framework.
168
- function httpJson(opts) {
169
- if (!opts || typeof opts !== "object") {
170
- throw _err("BAD_OPT", "notify.transports.httpJson: opts must be { url, ... }");
171
- }
172
- validateOpts.requireNonEmptyString(opts.url, "notify.transports.httpJson: url", NotifyError, "BAD_OPT");
173
- var allowedProtocols = opts.allowHttp ? safeUrl.ALLOW_HTTP_ALL : safeUrl.ALLOW_HTTP_TLS;
174
- var allowInternal = opts.allowInternal != null ? opts.allowInternal : null;
175
- // Validate URL at create time so bad URLs surface at boot, not at first send.
176
- safeUrl.parse(opts.url, { allowedProtocols: allowedProtocols, errorClass: NotifyError });
177
-
178
- var method = opts.method || "POST";
179
- var bodyFormat = opts.bodyFormat || "json";
180
- if (bodyFormat !== "json" && bodyFormat !== "form") {
181
- throw _err("BAD_OPT", "notify.transports.httpJson: bodyFormat must be 'json' or 'form'");
182
- }
183
- var staticHeaders = opts.headers || {};
184
- var signing = opts.signing || null;
185
- if (signing && typeof signing.sign !== "function") {
186
- throw _err("BAD_OPT", "notify.transports.httpJson: signing must have a sign(body) function");
187
- }
188
- var successStatus = (typeof opts.successStatus === "function")
189
- ? opts.successStatus
190
- : function (s) { return typeof s === "number" && s >= 200 && s < 300; };
191
- var customClient = opts.httpClient || null;
192
- var name = opts.name || "httpJson";
193
-
194
- return {
195
- name: name,
196
- send: async function (message, sendOpts) {
197
- var client = customClient || httpClientModule();
198
- var body;
199
- var contentType;
200
- if (bodyFormat === "form") {
201
- body = new URLSearchParams(message || {}).toString();
202
- contentType = "application/x-www-form-urlencoded";
203
- } else {
204
- body = JSON.stringify(message || {});
205
- contentType = "application/json";
206
- }
207
- var headers = Object.assign({ "Content-Type": contentType }, staticHeaders);
208
- if (sendOpts && sendOpts.headers) Object.assign(headers, sendOpts.headers);
209
- if (signing) {
210
- // signing.sign(body) returns either a headers object or a string.
211
- // The shape mirrors b.webhook.signer outputs so operators can plug
212
- // a webhook signer in directly.
213
- var signed = signing.sign(body);
214
- if (signed && typeof signed === "object" && !Array.isArray(signed)) {
215
- if (signed.headers) Object.assign(headers, signed.headers);
216
- else Object.assign(headers, signed);
217
- }
218
- }
219
- var startedAt = Date.now();
220
- var res = await client.request({
221
- method: method,
222
- url: opts.url,
223
- headers: headers,
224
- body: body,
225
- allowedProtocols: allowedProtocols,
226
- allowInternal: allowInternal,
227
- errorClass: NotifyError,
228
- });
229
- var status = (res && (res.statusCode || res.status)) || 0;
230
- if (!successStatus(status)) {
231
- // Throw a plain Error (not NotifyError) so b.retry.isRetryable
232
- // can classify on err.statusCode. NotifyError is alwaysPermanent
233
- // by design — wrapping a 429 in it would tell retry "don't try
234
- // again" before retry's HTTP-status classifier ever runs.
235
- // We only convert to NotifyError after retry exhaustion (in the
236
- // caller), which is when the error truly IS permanent.
237
- var httpErr = new Error(
238
- "notify.httpJson: " + opts.url + " responded " + status);
239
- httpErr.code = "HTTP_FAILURE";
240
- httpErr.statusCode = status;
241
- throw httpErr;
242
- }
243
- return {
244
- id: null,
245
- status: "delivered",
246
- attempts: 1,
247
- durationMs: Date.now() - startedAt,
248
- response: res,
249
- };
250
- },
251
- };
252
- }
253
-
254
- // log — fire-and-forget developer logger. Never throws; audit + obs still emit.
255
- function logTransport(opts) {
256
- opts = opts || {};
257
- // bootLog.boot() returns a callable with .info / .warn / .error
258
- // attached; that shape satisfies the operator-supplied opts.logger
259
- // contract directly. No fallback wrapper needed.
260
- var logger;
261
- if (opts.logger && typeof opts.logger.info === "function") {
262
- logger = opts.logger;
263
- } else {
264
- logger = bootLog.boot("notify.log");
265
- }
266
- return {
267
- name: opts.name || "log",
268
- send: async function (message, _sendOpts) {
269
- try { logger.info(JSON.stringify(message)); }
270
- catch (_e) { /* logger best-effort */ }
271
- return { id: null, status: "delivered", attempts: 1, durationMs: 0 };
272
- },
273
- };
274
- }
275
-
276
- // test — captures sends to .sent for fixture inspection. Never throws.
277
- function testTransport() {
278
- var sent = [];
279
- return {
280
- name: "test",
281
- sent: sent,
282
- send: async function (message, sendOpts) {
283
- sent.push({
284
- message: message,
285
- sendOpts: sendOpts || null,
286
- sentAt: Date.now(),
287
- });
288
- return { id: null, status: "delivered", attempts: 1, durationMs: 0 };
289
- },
290
- clear: function () { sent.length = 0; },
291
- };
292
- }
293
-
294
- // ---- Public create ----
295
-
296
- function create(opts) {
297
- opts = opts || {};
298
- validateOpts(opts, [
299
- "channels", "audit", "auditSuccess", "auditFailures",
300
- "redact", "defaultTimeoutMs", "defaultRetry", "defaultBreaker",
301
- "queue", "clock",
302
- ], "notify");
303
- _validateCreateOpts(opts);
304
- var cfg = validateOpts.applyDefaults(opts, DEFAULTS);
305
-
306
- var auditSuccess = cfg.auditSuccess;
307
- var auditFailures = cfg.auditFailures;
308
- var audit = opts.audit || null;
309
- var redactFn = (typeof opts.redact === "function")
310
- ? opts.redact
311
- // Default: b.redact.redact — the framework's PII detector chain.
312
- : function (m) { return redactModule().redact(m); };
313
- var defaultTimeoutMs = cfg.defaultTimeoutMs;
314
- var defaultRetry = opts.defaultRetry || null;
315
- var defaultBreaker = opts.defaultBreaker || null;
316
- var operatorQueue = opts.queue || null;
317
- var clock = opts.clock || function () { return Date.now(); };
318
-
319
- // Build channel registry: name → { transport, retry, breaker, timeoutMs, serialize, mutex? }
320
- var channels = {};
321
- var channelNames = Object.keys(opts.channels);
322
- for (var i = 0; i < channelNames.length; i++) {
323
- var n = channelNames[i];
324
- var entry = _validateChannelEntry(n, opts.channels[n]);
325
- var registry = {
326
- transport: entry.transport,
327
- retry: entry.retry || defaultRetry,
328
- timeoutMs: (entry.timeoutMs === null) ? defaultTimeoutMs : entry.timeoutMs,
329
- breaker: null,
330
- mutex: null,
331
- };
332
- var breakerOpts = entry.breaker || defaultBreaker;
333
- if (breakerOpts) {
334
- registry.breaker = new (retryModule().CircuitBreaker)(n, breakerOpts);
335
- }
336
- if (entry.serialize) registry.mutex = new safeAsync.Mutex();
337
- channels[n] = registry;
338
- }
339
-
340
- function _emitObs(name, labels) {
341
- try { observability().event(name, 1, labels || {}); }
342
- catch (_e) { /* drop-silent — observability sink must not crash send() */ }
343
- }
344
-
345
- var _emitAudit = validateOpts.makeAuditEmitter(audit);
346
-
347
- function _actor(callerOpts) {
348
- return requestHelpers.resolveActorWithOverride(callerOpts);
349
- }
350
-
351
- function _redactedMetadata(channel, message, extra) {
352
- var redactedMessage;
353
- try { redactedMessage = redactFn(message); }
354
- catch (_e) { redactedMessage = "[redact-failed]"; }
355
- return Object.assign({
356
- channel: channel,
357
- message: redactedMessage,
358
- }, extra || {});
359
- }
360
-
361
- // Send a single message to one channel. The whole call is wrapped in
362
- // observability.tap (span+counter), inside which we layer:
363
- //
364
- // withRetry( withTimeout( breaker.wrap( transport.send ) ) )
365
- //
366
- // Each layer comes from an existing primitive — notify never
367
- // re-implements retry / timeout / breaker / span+counter logic.
368
- async function send(input) {
369
- if (!input || typeof input !== "object") {
370
- throw _err("BAD_OPT", "notify.send: input must be { channel, message, ... }");
371
- }
372
- if (typeof input.channel !== "string" || input.channel.length === 0) {
373
- throw _err("BAD_OPT", "notify.send: channel must be a non-empty string");
374
- }
375
- if (input.message === undefined || input.message === null) {
376
- throw _err("MISSING_MESSAGE", "notify.send: message is required");
377
- }
378
- var channel = input.channel;
379
- var entry = channels[channel];
380
- if (!entry) {
381
- throw _err("NO_CHANNEL", "notify.send: unknown channel '" + channel + "'");
382
- }
383
- var perCallTimeoutMs = (input.timeoutMs !== undefined) ? input.timeoutMs : entry.timeoutMs;
384
- var perCallRetry = input.retry || entry.retry;
385
- var message = input.message;
386
-
387
- var attemptCount = 0;
388
- var startedAt = clock();
389
- var transport = entry.transport;
390
- var transportName = transport.name || channel;
391
-
392
- // The retryable single attempt. Each call to this function is one
393
- // transport.send invocation (so withRetry's loop is the only retry
394
- // mechanism — no double-retry inside the breaker or transport).
395
- async function _oneAttempt(attemptIdx) {
396
- attemptCount = attemptIdx;
397
- _emitObs("notify.send.attempt", { channel: channel, attempt: attemptIdx });
398
- var sendPromise = entry.transport.send(message, input.sendOpts || null);
399
- // withTimeout from b.safeAsync — never re-implement timer races.
400
- var timed = (perCallTimeoutMs > 0)
401
- ? safeAsync.withTimeout(sendPromise, perCallTimeoutMs, { name: "notify." + channel })
402
- : sendPromise;
403
- try {
404
- return await timed;
405
- } catch (e) {
406
- // Map withTimeout's async/timeout into a transient error so retry
407
- // classifies it correctly (operators can still opt OUT by setting
408
- // err.permanent in their transport).
409
- if (e && e.code === "async/timeout") {
410
- _emitObs("notify.send.timeout", { channel: channel });
411
- var te = _err("TIMEOUT",
412
- "notify.send: '" + channel + "' transport timed out after " + perCallTimeoutMs + "ms");
413
- // Mark transient via a NETWORK-style code so b.retry.isRetryable
414
- // routes it through the retry path.
415
- te.code = "ETIMEDOUT";
416
- throw te;
417
- }
418
- throw e;
419
- }
420
- }
421
-
422
- // Wrap each attempt with the breaker, if configured.
423
- async function _attemptWithBreaker(attemptIdx) {
424
- if (entry.breaker) {
425
- try {
426
- return await entry.breaker.wrap(function () { return _oneAttempt(attemptIdx); });
427
- } catch (e) {
428
- if (e && e.code === "CIRCUIT_OPEN") {
429
- _emitObs("notify.send.breaker.open", { channel: channel });
430
- }
431
- throw e;
432
- }
433
- }
434
- return _oneAttempt(attemptIdx);
435
- }
436
-
437
- // Optional serialize: only one in-flight send per channel at a time.
438
- async function _attemptSerialized(attemptIdx) {
439
- if (!entry.mutex) return _attemptWithBreaker(attemptIdx);
440
- await entry.mutex.acquire();
441
- try { return await _attemptWithBreaker(attemptIdx); }
442
- finally { entry.mutex.release(); }
443
- }
444
-
445
- // Outer span+counter wrapping via b.observability.tap so a single call
446
- // produces both a span (under the operator's tracer) AND a counter.
447
- return observability().tap("notify.send", { channel: channel }, async function () {
448
- try {
449
- // b.retry.withRetry IS the retry loop. Notify never hand-rolls
450
- // backoff/jitter/classification — the framework owns it.
451
- var result = await retryModule().withRetry(function (attempt) {
452
- return _attemptSerialized(attempt);
453
- }, perCallRetry);
454
-
455
- var durationMs = clock() - startedAt;
456
- _emitObs("notify.send.success", { channel: channel, durationMs: durationMs });
457
- if (auditSuccess) {
458
- _emitAudit("notify.send.success", {
459
- actor: _actor(input),
460
- resource: { kind: "notify.channel", id: channel },
461
- outcome: "success",
462
- metadata: _redactedMetadata(channel, message, {
463
- transport: transportName,
464
- attempts: attemptCount,
465
- durationMs: durationMs,
466
- }),
467
- });
468
- }
469
- return Object.assign({}, result, {
470
- channel: channel,
471
- attempts: attemptCount,
472
- durationMs: durationMs,
473
- });
474
- } catch (e) {
475
- _emitObs("notify.send.failure", {
476
- channel: channel,
477
- reason: (e && e.code) || "unknown",
478
- });
479
- if (auditFailures) {
480
- _emitAudit("notify.send.failure", {
481
- actor: _actor(input),
482
- resource: { kind: "notify.channel", id: channel },
483
- outcome: "failure",
484
- reason: (e && e.code) || "send-failed",
485
- metadata: _redactedMetadata(channel, message, {
486
- transport: transportName,
487
- attempts: attemptCount,
488
- message_: (e && e.message) || String(e),
489
- }),
490
- });
491
- }
492
- // If the error is already a NotifyError, propagate verbatim.
493
- // Otherwise wrap so callers always catch a single class while
494
- // keeping the cause chain.
495
- if (e && e.isNotifyError) throw e;
496
- var wrapped = _err("SEND_FAILED",
497
- "notify.send: '" + channel + "' failed after " + attemptCount + " attempt(s): " +
498
- ((e && e.message) || String(e)));
499
- wrapped.cause = e;
500
- if (e && typeof e.statusCode === "number") wrapped.statusCode = e.statusCode;
501
- throw wrapped;
502
- }
503
- });
504
- }
505
-
506
- // sendBatch: settle each input independently. One channel down doesn't
507
- // fail the whole batch; the result array carries either the success
508
- // shape OR a NotifyError for each input position.
509
- async function sendBatch(inputs) {
510
- if (!Array.isArray(inputs)) {
511
- throw _err("BAD_OPT", "notify.sendBatch: inputs must be an array");
512
- }
513
- var promises = inputs.map(function (input) {
514
- return send(input).then(
515
- function (result) { return result; },
516
- function (err) { return err; }
517
- );
518
- });
519
- var results = await Promise.all(promises);
520
- var ok = 0;
521
- var failed = 0;
522
- for (var i = 0; i < results.length; i++) {
523
- if (results[i] && results[i].isNotifyError) failed++;
524
- else ok++;
525
- }
526
- _emitObs("notify.batch", { size: inputs.length, ok: ok, failed: failed });
527
- return results;
528
- }
529
-
530
- // queue: enqueue an async send onto the operator's b.queue. Requires a
531
- // queue handle wired at create() OR per-call. Notify registers a
532
- // default handler for `notifyQueueName` on first use.
533
- var _queueHandlerRegistered = {};
534
- async function queue(input, queueOpts) {
535
- queueOpts = queueOpts || {};
536
- var q = queueOpts.queue || operatorQueue;
537
- if (!q || typeof q.enqueue !== "function") {
538
- throw _err("NO_QUEUE", "notify.queue: requires a b.queue handle (pass at create or per-call)");
539
- }
540
- if (!input || typeof input !== "object" || typeof input.channel !== "string") {
541
- throw _err("BAD_OPT", "notify.queue: input must be { channel, message, ... }");
542
- }
543
- var queueName = queueOpts.queueName || "notify";
544
- // Handler registration is operator-driven for the b.queue primitive
545
- // — operators have their own worker boot. We don't try to start
546
- // workers here. The handler signature follows b.jobs / b.queue
547
- // conventions: receives { input } and re-invokes notify.send.
548
- if (!_queueHandlerRegistered[queueName] && typeof q.registerHandler === "function") {
549
- try {
550
- q.registerHandler(queueName, async function (job) {
551
- var payload = (job && job.payload) || job;
552
- return send(payload);
553
- });
554
- _queueHandlerRegistered[queueName] = true;
555
- } catch (_e) { /* operator may register their own handler */ }
556
- }
557
- var jobId = await q.enqueue(queueName, input);
558
- _emitObs("notify.queue.enqueued", { channel: input.channel, queueName: queueName });
559
- return { jobId: jobId };
560
- }
561
-
562
- function addChannel(name, transport, channelOpts) {
563
- if (channels[name]) {
564
- throw _err("CHANNEL_EXISTS", "notify.addChannel: channel '" + name + "' already exists");
565
- }
566
- channelOpts = channelOpts || {};
567
- var entry = _validateChannelEntry(name,
568
- channelOpts.transport || channelOpts.send || transport
569
- ? Object.assign({ transport: transport }, channelOpts)
570
- : transport);
571
- var registry = {
572
- transport: entry.transport,
573
- retry: entry.retry || defaultRetry,
574
- timeoutMs: (entry.timeoutMs === null) ? defaultTimeoutMs : entry.timeoutMs,
575
- breaker: null,
576
- mutex: null,
577
- };
578
- var breakerOpts = entry.breaker || defaultBreaker;
579
- if (breakerOpts) registry.breaker = new (retryModule().CircuitBreaker)(name, breakerOpts);
580
- if (entry.serialize) registry.mutex = new safeAsync.Mutex();
581
- channels[name] = registry;
582
- }
583
-
584
- function listChannels() {
585
- return Object.keys(channels);
586
- }
587
-
588
- function transportFor(name) {
589
- var entry = channels[name];
590
- return entry ? entry.transport : null;
591
- }
592
-
593
- return {
594
- send: send,
595
- sendBatch: sendBatch,
596
- queue: queue,
597
- addChannel: addChannel,
598
- channels: listChannels,
599
- transport: transportFor,
600
- };
601
- }
602
-
603
- module.exports = {
604
- create: create,
605
- NotifyError: NotifyError,
606
- DEFAULTS: DEFAULTS,
607
- transports: {
608
- httpJson: httpJson,
609
- log: logTransport,
610
- test: testTransport,
611
- },
612
- };
1
+ "use strict";
2
+ /**
3
+ * b.notify — generic notification dispatcher.
4
+ *
5
+ * Composes existing primitives — retry/backoff (b.retry), per-call
6
+ * timeout (b.safeAsync.withTimeout), per-channel circuit breaker
7
+ * (b.retry.CircuitBreaker), span+counter wrapping
8
+ * (b.observability.tap), audit emission (b.audit.safeEmit),
9
+ * 5 W's actor context (b.requestHelpers.extractActorContext), URL
10
+ * validation (b.safeUrl.parse), HTTP I/O (b.httpClient.request), PII
11
+ * redaction (b.redact.redact). Notify never re-implements any of these
12
+ * — its job is to coordinate them around a transport abstraction.
13
+ *
14
+ * var notify = b.notify.create({
15
+ * channels: {
16
+ * slack: b.notify.transports.httpJson({ url: process.env.SLACK_HOOK }),
17
+ * sms: operatorTwilioShim,
18
+ * log: b.notify.transports.log(),
19
+ * },
20
+ * audit: b.audit,
21
+ * });
22
+ *
23
+ * await notify.send({ channel: "slack", message: { text: "Hello" } });
24
+ *
25
+ * Transport contract:
26
+ *
27
+ * {
28
+ * name: "slack",
29
+ * send: async function (message, sendOpts) {
30
+ * // Returns { id?, status, attempts?, durationMs? }
31
+ * // Throws on permanent failure. For transient failures, throw
32
+ * // with err.statusCode in b.retry.RETRYABLE_HTTP_STATUS or
33
+ * // err.code in b.retry.RETRYABLE_NET_ERRORS — retry classifies
34
+ * // them automatically. Operators can also set err.transient =
35
+ * // true for shapes outside that classification.
36
+ * },
37
+ * }
38
+ *
39
+ * What this primitive intentionally does NOT do (per scope):
40
+ * - Ship vendor SDKs (Twilio / FCM / APNs / Slack-API): operator brings
41
+ * transports; the framework provides the contract + httpJson +
42
+ * log + test built-ins.
43
+ * - Render templates / handle i18n: operator uses b.template + b.i18n.
44
+ * - Track recipient preferences: operator app concern.
45
+ * - Replace b.mail (SMTP/MIME stays its own primitive).
46
+ * - Replace b.websocketChannels (different abstraction —
47
+ * transient pub/sub, not retry-on-fail delivery).
48
+ */
49
+
50
+ var lazyRequire = require("./lazy-require");
51
+ var bootLog = require("./log");
52
+ var numericChecks = require("./numeric-checks");
53
+ var requestHelpers = require("./request-helpers");
54
+ var safeAsync = require("./safe-async");
55
+ var safeUrl = require("./safe-url");
56
+ var validateOpts = require("./validate-opts");
57
+ var C = require("./constants");
58
+ var { NotifyError } = require("./framework-error");
59
+
60
+ // Lazy-required modules to avoid load-order cycles. retry / observability /
61
+ // redact / httpClient don't currently import notify, but treating them
62
+ // the same way every primitive does keeps the load-order story uniform.
63
+ var retryModule = lazyRequire(function () { return require("./retry"); });
64
+ var observability = lazyRequire(function () { return require("./observability"); });
65
+ var redactModule = lazyRequire(function () { return require("./redact"); });
66
+ var httpClientModule = lazyRequire(function () { return require("./http-client"); });
67
+
68
+ var _err = NotifyError.factory;
69
+
70
+ var DEFAULTS = Object.freeze({
71
+ auditSuccess: true,
72
+ auditFailures: true,
73
+ defaultTimeoutMs: C.TIME.seconds(30),
74
+ // defaultRetry inherits from b.retry.DEFAULT_RETRY at create time so
75
+ // we get the framework's policy without forking the constants.
76
+ });
77
+
78
+ // ---- Call-site validation (throw on bad input) ----
79
+
80
+ var _isFiniteNonNegative = numericChecks.isFiniteNonNegative;
81
+
82
+ function _validateTransport(name, t) {
83
+ if (!t || typeof t !== "object") {
84
+ throw _err("BAD_OPT", "notify: transport for channel '" + name +
85
+ "' must be an object with a send() function");
86
+ }
87
+ if (typeof t.send !== "function") {
88
+ throw _err("BAD_OPT", "notify: transport for channel '" + name +
89
+ "' is missing required send() function");
90
+ }
91
+ }
92
+
93
+ function _validateChannelEntry(name, entry) {
94
+ if (typeof entry !== "object" || entry === null) {
95
+ throw _err("BAD_OPT", "notify: channel '" + name + "' must map to a transport or { transport, ... } object");
96
+ }
97
+ // Two accepted shapes:
98
+ // - Transport object directly: { name, send }
99
+ // - Channel-config object: { transport, retry?, breaker?, timeoutMs?, serialize? }
100
+ if (typeof entry.send === "function") {
101
+ return { transport: entry, retry: null, breaker: null, timeoutMs: null, serialize: false };
102
+ }
103
+ if (entry.transport === undefined) {
104
+ throw _err("BAD_OPT", "notify: channel '" + name +
105
+ "': must be a transport (with send fn) OR an object with .transport");
106
+ }
107
+ _validateTransport(name, entry.transport);
108
+ if (entry.retry !== undefined && (typeof entry.retry !== "object" || entry.retry === null)) {
109
+ throw _err("BAD_OPT", "notify: channel '" + name + "' retry must be a b.retry.withRetry opts object");
110
+ }
111
+ if (entry.breaker !== undefined && entry.breaker !== null && typeof entry.breaker !== "object") {
112
+ throw _err("BAD_OPT", "notify: channel '" + name + "' breaker must be a b.retry.CircuitBreaker opts object or null");
113
+ }
114
+ if (entry.timeoutMs !== undefined && entry.timeoutMs !== 0 && !_isFiniteNonNegative(entry.timeoutMs)) {
115
+ throw _err("BAD_OPT", "notify: channel '" + name + "' timeoutMs must be a non-negative finite number (0 disables)");
116
+ }
117
+ if (entry.serialize !== undefined && typeof entry.serialize !== "boolean") {
118
+ throw _err("BAD_OPT", "notify: channel '" + name + "' serialize must be a boolean");
119
+ }
120
+ return {
121
+ transport: entry.transport,
122
+ retry: entry.retry || null,
123
+ breaker: entry.breaker || null,
124
+ timeoutMs: (entry.timeoutMs !== undefined) ? entry.timeoutMs : null,
125
+ serialize: entry.serialize === true,
126
+ };
127
+ }
128
+
129
+ function _validateCreateOpts(opts) {
130
+ validateOpts.requireObject(opts, "notify.create", NotifyError);
131
+ if (!opts.channels || typeof opts.channels !== "object") {
132
+ throw _err("BAD_OPT", "notify.create: channels must be an object mapping channel names to transports");
133
+ }
134
+ var keys = Object.keys(opts.channels);
135
+ if (keys.length === 0) {
136
+ throw _err("BAD_OPT", "notify.create: channels object must have at least one channel");
137
+ }
138
+ validateOpts.auditShape(opts.audit, "notify.create", NotifyError);
139
+ validateOpts.optionalBoolean(opts.auditSuccess, "notify.create: auditSuccess", NotifyError);
140
+ validateOpts.optionalBoolean(opts.auditFailures, "notify.create: auditFailures", NotifyError);
141
+ if (opts.redact !== undefined && opts.redact !== null && typeof opts.redact !== "function") {
142
+ throw _err("BAD_OPT", "notify.create: redact must be a function returning a redacted message");
143
+ }
144
+ if (opts.defaultTimeoutMs !== undefined &&
145
+ opts.defaultTimeoutMs !== 0 &&
146
+ !_isFiniteNonNegative(opts.defaultTimeoutMs)) {
147
+ throw _err("BAD_OPT", "notify.create: defaultTimeoutMs must be a non-negative finite number (0 disables)");
148
+ }
149
+ if (opts.defaultRetry !== undefined && opts.defaultRetry !== null &&
150
+ (typeof opts.defaultRetry !== "object")) {
151
+ throw _err("BAD_OPT", "notify.create: defaultRetry must be a b.retry.withRetry opts object");
152
+ }
153
+ if (opts.defaultBreaker !== undefined && opts.defaultBreaker !== null &&
154
+ typeof opts.defaultBreaker !== "object") {
155
+ throw _err("BAD_OPT", "notify.create: defaultBreaker must be a b.retry.CircuitBreaker opts object");
156
+ }
157
+ validateOpts.optionalObjectWithMethod(opts.queue, "enqueue",
158
+ "notify.create: queue", NotifyError, "BAD_OPT",
159
+ "must be a b.queue-shaped handle (enqueue fn)");
160
+ validateOpts.optionalFunction(opts.clock, "notify.create: clock", NotifyError);
161
+ }
162
+
163
+ // ---- Built-in transports ----
164
+
165
+ // httpJson — POST JSON to a URL via b.httpClient. Default `transient`
166
+ // classifier defers to b.retry.isRetryable so HTTP/network classification
167
+ // matches the rest of the framework.
168
+ function httpJson(opts) {
169
+ if (!opts || typeof opts !== "object") {
170
+ throw _err("BAD_OPT", "notify.transports.httpJson: opts must be { url, ... }");
171
+ }
172
+ validateOpts.requireNonEmptyString(opts.url, "notify.transports.httpJson: url", NotifyError, "BAD_OPT");
173
+ var allowedProtocols = opts.allowHttp ? safeUrl.ALLOW_HTTP_ALL : safeUrl.ALLOW_HTTP_TLS;
174
+ var allowInternal = opts.allowInternal != null ? opts.allowInternal : null;
175
+ // Validate URL at create time so bad URLs surface at boot, not at first send.
176
+ safeUrl.parse(opts.url, { allowedProtocols: allowedProtocols, errorClass: NotifyError });
177
+
178
+ var method = opts.method || "POST";
179
+ var bodyFormat = opts.bodyFormat || "json";
180
+ if (bodyFormat !== "json" && bodyFormat !== "form") {
181
+ throw _err("BAD_OPT", "notify.transports.httpJson: bodyFormat must be 'json' or 'form'");
182
+ }
183
+ var staticHeaders = opts.headers || {};
184
+ var signing = opts.signing || null;
185
+ if (signing && typeof signing.sign !== "function") {
186
+ throw _err("BAD_OPT", "notify.transports.httpJson: signing must have a sign(body) function");
187
+ }
188
+ var successStatus = (typeof opts.successStatus === "function")
189
+ ? opts.successStatus
190
+ : function (s) { return typeof s === "number" && s >= 200 && s < 300; };
191
+ var customClient = opts.httpClient || null;
192
+ var name = opts.name || "httpJson";
193
+
194
+ return {
195
+ name: name,
196
+ send: async function (message, sendOpts) {
197
+ var client = customClient || httpClientModule();
198
+ var body;
199
+ var contentType;
200
+ if (bodyFormat === "form") {
201
+ body = new URLSearchParams(message || {}).toString();
202
+ contentType = "application/x-www-form-urlencoded";
203
+ } else {
204
+ body = JSON.stringify(message || {});
205
+ contentType = "application/json";
206
+ }
207
+ var headers = Object.assign({ "Content-Type": contentType }, staticHeaders);
208
+ if (sendOpts && sendOpts.headers) Object.assign(headers, sendOpts.headers);
209
+ if (signing) {
210
+ // signing.sign(body) returns either a headers object or a string.
211
+ // The shape mirrors b.webhook.signer outputs so operators can plug
212
+ // a webhook signer in directly.
213
+ var signed = signing.sign(body);
214
+ if (signed && typeof signed === "object" && !Array.isArray(signed)) {
215
+ if (signed.headers) Object.assign(headers, signed.headers);
216
+ else Object.assign(headers, signed);
217
+ }
218
+ }
219
+ var startedAt = Date.now();
220
+ var res = await client.request({
221
+ method: method,
222
+ url: opts.url,
223
+ headers: headers,
224
+ body: body,
225
+ allowedProtocols: allowedProtocols,
226
+ allowInternal: allowInternal,
227
+ errorClass: NotifyError,
228
+ });
229
+ var status = (res && (res.statusCode || res.status)) || 0;
230
+ if (!successStatus(status)) {
231
+ // Throw a plain Error (not NotifyError) so b.retry.isRetryable
232
+ // can classify on err.statusCode. NotifyError is alwaysPermanent
233
+ // by design — wrapping a 429 in it would tell retry "don't try
234
+ // again" before retry's HTTP-status classifier ever runs.
235
+ // We only convert to NotifyError after retry exhaustion (in the
236
+ // caller), which is when the error truly IS permanent.
237
+ var httpErr = new Error(
238
+ "notify.httpJson: " + opts.url + " responded " + status);
239
+ httpErr.code = "HTTP_FAILURE";
240
+ httpErr.statusCode = status;
241
+ throw httpErr;
242
+ }
243
+ return {
244
+ id: null,
245
+ status: "delivered",
246
+ attempts: 1,
247
+ durationMs: Date.now() - startedAt,
248
+ response: res,
249
+ };
250
+ },
251
+ };
252
+ }
253
+
254
+ // log — fire-and-forget developer logger. Never throws; audit + obs still emit.
255
+ function logTransport(opts) {
256
+ opts = opts || {};
257
+ // bootLog.boot() returns a callable with .info / .warn / .error
258
+ // attached; that shape satisfies the operator-supplied opts.logger
259
+ // contract directly. No fallback wrapper needed.
260
+ var logger;
261
+ if (opts.logger && typeof opts.logger.info === "function") {
262
+ logger = opts.logger;
263
+ } else {
264
+ logger = bootLog.boot("notify.log");
265
+ }
266
+ return {
267
+ name: opts.name || "log",
268
+ send: async function (message, _sendOpts) {
269
+ try { logger.info(JSON.stringify(message)); }
270
+ catch (_e) { /* logger best-effort */ }
271
+ return { id: null, status: "delivered", attempts: 1, durationMs: 0 };
272
+ },
273
+ };
274
+ }
275
+
276
+ // test — captures sends to .sent for fixture inspection. Never throws.
277
+ function testTransport() {
278
+ var sent = [];
279
+ return {
280
+ name: "test",
281
+ sent: sent,
282
+ send: async function (message, sendOpts) {
283
+ sent.push({
284
+ message: message,
285
+ sendOpts: sendOpts || null,
286
+ sentAt: Date.now(),
287
+ });
288
+ return { id: null, status: "delivered", attempts: 1, durationMs: 0 };
289
+ },
290
+ clear: function () { sent.length = 0; },
291
+ };
292
+ }
293
+
294
+ // ---- Public create ----
295
+
296
+ function create(opts) {
297
+ opts = opts || {};
298
+ validateOpts(opts, [
299
+ "channels", "audit", "auditSuccess", "auditFailures",
300
+ "redact", "defaultTimeoutMs", "defaultRetry", "defaultBreaker",
301
+ "queue", "clock",
302
+ ], "notify");
303
+ _validateCreateOpts(opts);
304
+ var cfg = validateOpts.applyDefaults(opts, DEFAULTS);
305
+
306
+ var auditSuccess = cfg.auditSuccess;
307
+ var auditFailures = cfg.auditFailures;
308
+ var audit = opts.audit || null;
309
+ var redactFn = (typeof opts.redact === "function")
310
+ ? opts.redact
311
+ // Default: b.redact.redact — the framework's PII detector chain.
312
+ : function (m) { return redactModule().redact(m); };
313
+ var defaultTimeoutMs = cfg.defaultTimeoutMs;
314
+ var defaultRetry = opts.defaultRetry || null;
315
+ var defaultBreaker = opts.defaultBreaker || null;
316
+ var operatorQueue = opts.queue || null;
317
+ var clock = opts.clock || function () { return Date.now(); };
318
+
319
+ // Build channel registry: name → { transport, retry, breaker, timeoutMs, serialize, mutex? }
320
+ var channels = {};
321
+ var channelNames = Object.keys(opts.channels);
322
+ for (var i = 0; i < channelNames.length; i++) {
323
+ var n = channelNames[i];
324
+ var entry = _validateChannelEntry(n, opts.channels[n]);
325
+ var registry = {
326
+ transport: entry.transport,
327
+ retry: entry.retry || defaultRetry,
328
+ timeoutMs: (entry.timeoutMs === null) ? defaultTimeoutMs : entry.timeoutMs,
329
+ breaker: null,
330
+ mutex: null,
331
+ };
332
+ var breakerOpts = entry.breaker || defaultBreaker;
333
+ if (breakerOpts) {
334
+ registry.breaker = new (retryModule().CircuitBreaker)(n, breakerOpts);
335
+ }
336
+ if (entry.serialize) registry.mutex = new safeAsync.Mutex();
337
+ channels[n] = registry;
338
+ }
339
+
340
+ function _emitObs(name, labels) {
341
+ try { observability().event(name, 1, labels || {}); }
342
+ catch (_e) { /* drop-silent — observability sink must not crash send() */ }
343
+ }
344
+
345
+ var _emitAudit = validateOpts.makeAuditEmitter(audit);
346
+
347
+ function _actor(callerOpts) {
348
+ return requestHelpers.resolveActorWithOverride(callerOpts);
349
+ }
350
+
351
+ function _redactedMetadata(channel, message, extra) {
352
+ var redactedMessage;
353
+ try { redactedMessage = redactFn(message); }
354
+ catch (_e) { redactedMessage = "[redact-failed]"; }
355
+ return Object.assign({
356
+ channel: channel,
357
+ message: redactedMessage,
358
+ }, extra || {});
359
+ }
360
+
361
+ // Send a single message to one channel. The whole call is wrapped in
362
+ // observability.tap (span+counter), inside which we layer:
363
+ //
364
+ // withRetry( withTimeout( breaker.wrap( transport.send ) ) )
365
+ //
366
+ // Each layer comes from an existing primitive — notify never
367
+ // re-implements retry / timeout / breaker / span+counter logic.
368
+ async function send(input) {
369
+ if (!input || typeof input !== "object") {
370
+ throw _err("BAD_OPT", "notify.send: input must be { channel, message, ... }");
371
+ }
372
+ if (typeof input.channel !== "string" || input.channel.length === 0) {
373
+ throw _err("BAD_OPT", "notify.send: channel must be a non-empty string");
374
+ }
375
+ if (input.message === undefined || input.message === null) {
376
+ throw _err("MISSING_MESSAGE", "notify.send: message is required");
377
+ }
378
+ var channel = input.channel;
379
+ var entry = channels[channel];
380
+ if (!entry) {
381
+ throw _err("NO_CHANNEL", "notify.send: unknown channel '" + channel + "'");
382
+ }
383
+ var perCallTimeoutMs = (input.timeoutMs !== undefined) ? input.timeoutMs : entry.timeoutMs;
384
+ var perCallRetry = input.retry || entry.retry;
385
+ var message = input.message;
386
+
387
+ var attemptCount = 0;
388
+ var startedAt = clock();
389
+ var transport = entry.transport;
390
+ var transportName = transport.name || channel;
391
+
392
+ // The retryable single attempt. Each call to this function is one
393
+ // transport.send invocation (so withRetry's loop is the only retry
394
+ // mechanism — no double-retry inside the breaker or transport).
395
+ async function _oneAttempt(attemptIdx) {
396
+ attemptCount = attemptIdx;
397
+ _emitObs("notify.send.attempt", { channel: channel, attempt: attemptIdx });
398
+ var sendPromise = entry.transport.send(message, input.sendOpts || null);
399
+ // withTimeout from b.safeAsync — never re-implement timer races.
400
+ var timed = (perCallTimeoutMs > 0)
401
+ ? safeAsync.withTimeout(sendPromise, perCallTimeoutMs, { name: "notify." + channel })
402
+ : sendPromise;
403
+ try {
404
+ return await timed;
405
+ } catch (e) {
406
+ // Map withTimeout's async/timeout into a transient error so retry
407
+ // classifies it correctly (operators can still opt OUT by setting
408
+ // err.permanent in their transport).
409
+ if (e && e.code === "async/timeout") {
410
+ _emitObs("notify.send.timeout", { channel: channel });
411
+ var te = _err("TIMEOUT",
412
+ "notify.send: '" + channel + "' transport timed out after " + perCallTimeoutMs + "ms");
413
+ // Mark transient via a NETWORK-style code so b.retry.isRetryable
414
+ // routes it through the retry path.
415
+ te.code = "ETIMEDOUT";
416
+ throw te;
417
+ }
418
+ throw e;
419
+ }
420
+ }
421
+
422
+ // Wrap each attempt with the breaker, if configured.
423
+ async function _attemptWithBreaker(attemptIdx) {
424
+ if (entry.breaker) {
425
+ try {
426
+ return await entry.breaker.wrap(function () { return _oneAttempt(attemptIdx); });
427
+ } catch (e) {
428
+ if (e && e.code === "CIRCUIT_OPEN") {
429
+ _emitObs("notify.send.breaker.open", { channel: channel });
430
+ }
431
+ throw e;
432
+ }
433
+ }
434
+ return _oneAttempt(attemptIdx);
435
+ }
436
+
437
+ // Optional serialize: only one in-flight send per channel at a time.
438
+ async function _attemptSerialized(attemptIdx) {
439
+ if (!entry.mutex) return _attemptWithBreaker(attemptIdx);
440
+ await entry.mutex.acquire();
441
+ try { return await _attemptWithBreaker(attemptIdx); }
442
+ finally { entry.mutex.release(); }
443
+ }
444
+
445
+ // Outer span+counter wrapping via b.observability.tap so a single call
446
+ // produces both a span (under the operator's tracer) AND a counter.
447
+ return observability().tap("notify.send", { channel: channel }, async function () {
448
+ try {
449
+ // b.retry.withRetry IS the retry loop. Notify never hand-rolls
450
+ // backoff/jitter/classification — the framework owns it.
451
+ var result = await retryModule().withRetry(function (attempt) {
452
+ return _attemptSerialized(attempt);
453
+ }, perCallRetry);
454
+
455
+ var durationMs = clock() - startedAt;
456
+ _emitObs("notify.send.success", { channel: channel, durationMs: durationMs });
457
+ if (auditSuccess) {
458
+ _emitAudit("notify.send.success", {
459
+ actor: _actor(input),
460
+ resource: { kind: "notify.channel", id: channel },
461
+ outcome: "success",
462
+ metadata: _redactedMetadata(channel, message, {
463
+ transport: transportName,
464
+ attempts: attemptCount,
465
+ durationMs: durationMs,
466
+ }),
467
+ });
468
+ }
469
+ return Object.assign({}, result, {
470
+ channel: channel,
471
+ attempts: attemptCount,
472
+ durationMs: durationMs,
473
+ });
474
+ } catch (e) {
475
+ _emitObs("notify.send.failure", {
476
+ channel: channel,
477
+ reason: (e && e.code) || "unknown",
478
+ });
479
+ if (auditFailures) {
480
+ _emitAudit("notify.send.failure", {
481
+ actor: _actor(input),
482
+ resource: { kind: "notify.channel", id: channel },
483
+ outcome: "failure",
484
+ reason: (e && e.code) || "send-failed",
485
+ metadata: _redactedMetadata(channel, message, {
486
+ transport: transportName,
487
+ attempts: attemptCount,
488
+ message_: (e && e.message) || String(e),
489
+ }),
490
+ });
491
+ }
492
+ // If the error is already a NotifyError, propagate verbatim.
493
+ // Otherwise wrap so callers always catch a single class while
494
+ // keeping the cause chain.
495
+ if (e && e.isNotifyError) throw e;
496
+ var wrapped = _err("SEND_FAILED",
497
+ "notify.send: '" + channel + "' failed after " + attemptCount + " attempt(s): " +
498
+ ((e && e.message) || String(e)));
499
+ wrapped.cause = e;
500
+ if (e && typeof e.statusCode === "number") wrapped.statusCode = e.statusCode;
501
+ throw wrapped;
502
+ }
503
+ });
504
+ }
505
+
506
+ // sendBatch: settle each input independently. One channel down doesn't
507
+ // fail the whole batch; the result array carries either the success
508
+ // shape OR a NotifyError for each input position.
509
+ async function sendBatch(inputs) {
510
+ if (!Array.isArray(inputs)) {
511
+ throw _err("BAD_OPT", "notify.sendBatch: inputs must be an array");
512
+ }
513
+ var promises = inputs.map(function (input) {
514
+ return send(input).then(
515
+ function (result) { return result; },
516
+ function (err) { return err; }
517
+ );
518
+ });
519
+ var results = await Promise.all(promises);
520
+ var ok = 0;
521
+ var failed = 0;
522
+ for (var i = 0; i < results.length; i++) {
523
+ if (results[i] && results[i].isNotifyError) failed++;
524
+ else ok++;
525
+ }
526
+ _emitObs("notify.batch", { size: inputs.length, ok: ok, failed: failed });
527
+ return results;
528
+ }
529
+
530
+ // queue: enqueue an async send onto the operator's b.queue. Requires a
531
+ // queue handle wired at create() OR per-call. Notify registers a
532
+ // default handler for `notifyQueueName` on first use.
533
+ var _queueHandlerRegistered = {};
534
+ async function queue(input, queueOpts) {
535
+ queueOpts = queueOpts || {};
536
+ var q = queueOpts.queue || operatorQueue;
537
+ if (!q || typeof q.enqueue !== "function") {
538
+ throw _err("NO_QUEUE", "notify.queue: requires a b.queue handle (pass at create or per-call)");
539
+ }
540
+ if (!input || typeof input !== "object" || typeof input.channel !== "string") {
541
+ throw _err("BAD_OPT", "notify.queue: input must be { channel, message, ... }");
542
+ }
543
+ var queueName = queueOpts.queueName || "notify";
544
+ // Handler registration is operator-driven for the b.queue primitive
545
+ // — operators have their own worker boot. We don't try to start
546
+ // workers here. The handler signature follows b.jobs / b.queue
547
+ // conventions: receives { input } and re-invokes notify.send.
548
+ if (!_queueHandlerRegistered[queueName] && typeof q.registerHandler === "function") {
549
+ try {
550
+ q.registerHandler(queueName, async function (job) {
551
+ var payload = (job && job.payload) || job;
552
+ return send(payload);
553
+ });
554
+ _queueHandlerRegistered[queueName] = true;
555
+ } catch (_e) { /* operator may register their own handler */ }
556
+ }
557
+ var jobId = await q.enqueue(queueName, input);
558
+ _emitObs("notify.queue.enqueued", { channel: input.channel, queueName: queueName });
559
+ return { jobId: jobId };
560
+ }
561
+
562
+ function addChannel(name, transport, channelOpts) {
563
+ if (channels[name]) {
564
+ throw _err("CHANNEL_EXISTS", "notify.addChannel: channel '" + name + "' already exists");
565
+ }
566
+ channelOpts = channelOpts || {};
567
+ var entry = _validateChannelEntry(name,
568
+ channelOpts.transport || channelOpts.send || transport
569
+ ? Object.assign({ transport: transport }, channelOpts)
570
+ : transport);
571
+ var registry = {
572
+ transport: entry.transport,
573
+ retry: entry.retry || defaultRetry,
574
+ timeoutMs: (entry.timeoutMs === null) ? defaultTimeoutMs : entry.timeoutMs,
575
+ breaker: null,
576
+ mutex: null,
577
+ };
578
+ var breakerOpts = entry.breaker || defaultBreaker;
579
+ if (breakerOpts) registry.breaker = new (retryModule().CircuitBreaker)(name, breakerOpts);
580
+ if (entry.serialize) registry.mutex = new safeAsync.Mutex();
581
+ channels[name] = registry;
582
+ }
583
+
584
+ function listChannels() {
585
+ return Object.keys(channels);
586
+ }
587
+
588
+ function transportFor(name) {
589
+ var entry = channels[name];
590
+ return entry ? entry.transport : null;
591
+ }
592
+
593
+ return {
594
+ send: send,
595
+ sendBatch: sendBatch,
596
+ queue: queue,
597
+ addChannel: addChannel,
598
+ channels: listChannels,
599
+ transport: transportFor,
600
+ };
601
+ }
602
+
603
+ module.exports = {
604
+ create: create,
605
+ NotifyError: NotifyError,
606
+ DEFAULTS: DEFAULTS,
607
+ transports: {
608
+ httpJson: httpJson,
609
+ log: logTransport,
610
+ test: testTransport,
611
+ },
612
+ };