@blamejs/core 0.7.1 → 0.7.18

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