@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/testing.js CHANGED
@@ -1,798 +1,798 @@
1
- "use strict";
2
- /**
3
- * b.testing — operator-facing test helpers.
4
- *
5
- * Each helper threads through an existing framework primitive rather
6
- * than rolling its own timer races or polling loops.
7
- *
8
- * var t = b.testing;
9
- * var req = t.mockReq({ url: "/users/42", method: "GET" });
10
- * var res = t.mockRes();
11
- * await myHandler(req, res, function () {});
12
- *
13
- * var clk = t.fakeClock(1_000_000);
14
- * var cache = b.cache.create({ namespace: "x", clock: clk.now });
15
- * clk.advance(C.TIME.minutes(5)); // jump forward
16
- *
17
- * var hc = t.fakeHttpClient(function (req) {
18
- * return { statusCode: 200, body: Buffer.from("ok") };
19
- * });
20
- * // ...inject hc as the operator's b.httpClient stand-in
21
- *
22
- * var audit = t.captureAudit();
23
- * var notify = b.notify.create({ channels: { ... }, audit: audit });
24
- * await notify.send({ ... });
25
- * assert(audit.byAction("notify.send.success").length === 1);
26
- *
27
- * var captured = await t.runMiddleware(myMiddleware, req, res);
28
- * assert(captured.nextCalled);
29
- *
30
- * await t.waitFor(function () { return jobsTable.count() > 0; });
31
- *
32
- * var dir = t.tempDir("my-fixture");
33
- * try {
34
- * fs.writeFileSync(path.join(dir.path, "fixture.json"), "...");
35
- * } finally { dir.cleanup(); }
36
- *
37
- * Primitive-mapping:
38
- *
39
- * - waitFor poll loop → b.safeAsync.sleep
40
- * - waitFor / runMiddleware overall cap → b.safeAsync.withTimeout
41
- * - mockReq actor shape → compatible with b.requestHelpers.extractActorContext
42
- * - captureObservability → matches b.observability.tap + .event contracts
43
- * - captureAudit → matches b.audit.safeEmit (drop-silent)
44
- * - fakeHttpClient → matches b.httpClient.request response shape
45
- * - tempDir path safety → mirrors lib/static.js _resolveSafe containment check
46
- * - TestingError → b.frameworkError.defineClass(...{ alwaysPermanent: true })
47
- * - lazy require → b.lazyRequire (avoids load-order cycles with safe-async)
48
- *
49
- * What is intentionally NOT here:
50
- *
51
- * - Assertion library / test runner / mocking lib (Node's `assert`,
52
- * `node:test`, vitest, jest, etc. — operator's choice)
53
- * - Supertest-style request builder (operators use native http.request
54
- * or bring real supertest)
55
- * - DB transaction-rollback wrapper (b.db.transaction already exists)
56
- * - Snapshot testing / property-based testing helpers (operator brings
57
- * their own snapshotter / fast-check)
58
- * - Built-in fixtures that boot b.db with vault — that's framework-test-
59
- * specific and stays in test/helpers/db.js
60
- */
61
-
62
- var fs = require("node:fs");
63
- // testing.js IS the test injector — bypasses b.httpClient by design so
64
- // tests can assert on raw request shape. This is the one production
65
- // module where direct http.request is the contract.
66
- var http = require("node:http");
67
- var os = require("node:os");
68
- var nodePath = require("node:path");
69
- var EventEmitter = require("node:events").EventEmitter;
70
- var C = require("./constants");
71
- var lazyRequire = require("./lazy-require");
72
- var numericChecks = require("./numeric-checks");
73
- var safeAsync = require("./safe-async");
74
- var safeBuffer = require("./safe-buffer");
75
- var safeJson = require("./safe-json");
76
- var { TestingError } = require("./framework-error");
77
-
78
- // Lazy-required to avoid load-order cycles with the metrics module.
79
- // metrics is the only place that exposes the global `tap` slot the
80
- // captureMetricsTap helper swaps; pulling it lazily keeps testing.js
81
- // safe to require at any framework load order.
82
- var metricsModule = lazyRequire(function () { return require("./metrics"); });
83
-
84
- var _err = TestingError.factory;
85
-
86
- var DEFAULTS = Object.freeze({
87
- waitForTimeoutMs: C.TIME.seconds(1),
88
- waitForIntervalMs: 10,
89
- runMiddlewareTimeoutMs: C.TIME.seconds(5),
90
- });
91
-
92
- // ---- Call-site validation helpers (throw on bad input) ----
93
-
94
- var _isPositiveInt = numericChecks.isPositiveInt;
95
- var _isFiniteNonNegative = numericChecks.isFiniteNonNegative;
96
-
97
- // ---- HTTP mocks (standalone — no framework primitive overlap) ----
98
- // These mimic Node's `http` module's request/response shapes. They're
99
- // the surface every framework primitive's middleware tests use.
100
-
101
- function mockReq(opts) {
102
- opts = opts || {};
103
- var headers = Object.assign({}, opts.headers || {});
104
- // Compatible with b.requestHelpers.extractActorContext: that function
105
- // reads `headers["user-agent"]`, `headers["x-request-id"]`, `socket
106
- // .remoteAddress`, `connection.remoteAddress`, `method`, `url`,
107
- // `requestId`, `session.id`, `user.id`. mockReq populates every
108
- // field that has a sensible default so extractActorContext doesn't
109
- // see undefined when operators pass mockReq() with minimal opts.
110
- if (opts.userAgent && !headers["user-agent"]) headers["user-agent"] = opts.userAgent;
111
- if (opts.requestId && !headers["x-request-id"]) headers["x-request-id"] = opts.requestId;
112
- return {
113
- method: opts.method || "GET",
114
- url: opts.url || "/",
115
- pathname: opts.pathname || (opts.url || "/").split("?")[0],
116
- headers: headers,
117
- socket: opts.socket || { remoteAddress: opts.ip || "127.0.0.1" },
118
- connection: opts.connection || { remoteAddress: opts.ip || "127.0.0.1" },
119
- };
120
- }
121
-
122
- function mockRes() {
123
- var headers = {};
124
- var statusCode = null;
125
- var bodyParts = [];
126
- var ended = false;
127
- return {
128
- statusCode: null,
129
- writableEnded: false,
130
- setHeader: function (k, v) { headers[k.toLowerCase()] = v; },
131
- getHeader: function (k) { return headers[k.toLowerCase()]; },
132
- writeHead: function (s, h) {
133
- statusCode = s;
134
- if (h) for (var k in h) headers[k.toLowerCase()] = h[k];
135
- },
136
- end: function (b) {
137
- if (b !== undefined) bodyParts.push(b);
138
- ended = true;
139
- this.writableEnded = true;
140
- },
141
- _captured: function () {
142
- return { status: statusCode, headers: headers, body: bodyParts.join(""), ended: ended };
143
- },
144
- };
145
- }
146
-
147
- function bodyReq(method, headers, body) {
148
- var req = new EventEmitter();
149
- req.method = method || "GET";
150
- req.url = "/";
151
- req.headers = Object.assign({}, headers || {});
152
- req.socket = { remoteAddress: "127.0.0.1" };
153
- req.destroy = function () { /* mock — no-op */ };
154
- setImmediate(function () {
155
- if (Buffer.isBuffer(body)) req.emit("data", body);
156
- else if (typeof body === "string") req.emit("data", Buffer.from(body));
157
- req.emit("end");
158
- });
159
- return req;
160
- }
161
-
162
- function bodyRes() {
163
- var res = new EventEmitter();
164
- res.statusCode = null;
165
- res.headersSent = false;
166
- res._captured = "";
167
- res._endedStatus = null;
168
- res._headers = {};
169
- res.writeHead = function (s, h) {
170
- res.statusCode = s;
171
- res._endedStatus = s;
172
- res.headersSent = true;
173
- res._headers = h || {};
174
- };
175
- res.end = function (body) { if (body) res._captured += body; res.emit("finish"); };
176
- return res;
177
- }
178
-
179
- function streamingRes() {
180
- var res = new EventEmitter();
181
- res._chunks = [];
182
- res._headers = {};
183
- res._statusCode = 200;
184
- res.headersSent = false;
185
- res.writeHead = function (status, statusMsgOrHeaders, headersIfMsg) {
186
- res._statusCode = status;
187
- res.headersSent = true;
188
- var h = null;
189
- if (headersIfMsg && typeof headersIfMsg === "object") h = headersIfMsg;
190
- else if (statusMsgOrHeaders && typeof statusMsgOrHeaders === "object" && !Array.isArray(statusMsgOrHeaders)) {
191
- h = statusMsgOrHeaders;
192
- }
193
- if (h) {
194
- var keys = Object.keys(h);
195
- for (var i = 0; i < keys.length; i++) res._headers[keys[i].toLowerCase()] = h[keys[i]];
196
- }
197
- };
198
- res.setHeader = function (k, v) { res._headers[k.toLowerCase()] = v; };
199
- res.getHeader = function (k) { return res._headers[k.toLowerCase()]; };
200
- res.removeHeader = function (k) { delete res._headers[k.toLowerCase()]; };
201
- res.write = function (chunk) {
202
- if (Buffer.isBuffer(chunk)) res._chunks.push(chunk);
203
- else if (typeof chunk === "string") res._chunks.push(Buffer.from(chunk));
204
- return true;
205
- };
206
- res.end = function (chunk) {
207
- if (chunk != null) res.write(chunk);
208
- res.emit("finish");
209
- return res;
210
- };
211
- res._captured = function () { return Buffer.concat(res._chunks); };
212
- return res;
213
- }
214
-
215
- // ---- fakeClock ----
216
- //
217
- // No framework primitive owns "controllable clock"; this IS that
218
- // primitive now. The shape is `{ now, advance, set, ms }` so operators
219
- // can pass `clk.now` as the `clock` opt to b.cache / b.api-key /
220
- // b.permissions / b.scheduler / b.seeders / etc.
221
-
222
- function fakeClock(initialMs) {
223
- if (initialMs === undefined) initialMs = 1_000_000; // arbitrary positive default
224
- if (typeof initialMs !== "number" || !isFinite(initialMs)) {
225
- throw _err("BAD_INPUT", "fakeClock: initialMs must be a finite number, got " +
226
- (typeof initialMs) + " " + JSON.stringify(initialMs));
227
- }
228
- var current = initialMs;
229
- // Bound `now` so operators pass `clk.now` directly without losing `this`.
230
- function now() { return current; }
231
- function advance(ms) {
232
- if (typeof ms !== "number" || !isFinite(ms)) {
233
- throw _err("BAD_INPUT", "fakeClock.advance: ms must be a finite number");
234
- }
235
- current += ms;
236
- }
237
- function set(ms) {
238
- if (typeof ms !== "number" || !isFinite(ms)) {
239
- throw _err("BAD_INPUT", "fakeClock.set: ms must be a finite number");
240
- }
241
- current = ms;
242
- }
243
- return {
244
- now: now,
245
- advance: advance,
246
- set: set,
247
- get ms() { return current; },
248
- };
249
- }
250
-
251
- // ---- fakeHttpClient ----
252
- //
253
- // Drop-in replacement for b.httpClient. responder(req) returns the
254
- // canned response object — sync OR async. `calls` is the captured
255
- // request array.
256
-
257
- function fakeHttpClient(responder) {
258
- if (typeof responder !== "function") {
259
- throw _err("BAD_INPUT", "fakeHttpClient: responder must be a function");
260
- }
261
- var calls = [];
262
- return {
263
- calls: calls,
264
- request: function (req) {
265
- calls.push(req);
266
- return Promise.resolve(responder(req));
267
- },
268
- };
269
- }
270
-
271
- // ---- captureAudit ----
272
- //
273
- // Matches b.audit.safeEmit's drop-silent contract. captured holds
274
- // every event pushed; clear() empties; byAction(name) filters.
275
-
276
- function captureAudit() {
277
- var captured = [];
278
- return {
279
- captured: captured,
280
- safeEmit: function (event) {
281
- // Drop-silent on caller-side bugs that throw inside the capture
282
- // push (shouldn't happen with array.push, but matches the real
283
- // safeEmit's defensive shape).
284
- try { captured.push(event); }
285
- catch (_e) { /* drop-silent */ }
286
- },
287
- clear: function () { captured.length = 0; },
288
- byAction: function (action) {
289
- return captured.filter(function (e) { return e && e.action === action; });
290
- },
291
- };
292
- }
293
-
294
- // ---- captureObservability ----
295
- //
296
- // Matches b.observability.tap + b.observability.event contracts. tap
297
- // invokes fn synchronously (passes `null` as the span — no tracer
298
- // active under capture) and returns fn's return value, sync OR promise.
299
- // Both sides are captured.
300
-
301
- function captureObservability() {
302
- var captured = [];
303
- function event(name, value, labels) {
304
- if (typeof name !== "string" || name.length === 0) return; // drop-silent
305
- captured.push({ kind: "event", name: name, value: value, labels: labels || {} });
306
- }
307
- function tap(name, attrs, fn) {
308
- if (typeof attrs === "function") { fn = attrs; attrs = null; }
309
- if (typeof name !== "string" || name.length === 0) {
310
- throw new TypeError("captureObservability.tap: name must be a non-empty string");
311
- }
312
- if (typeof fn !== "function") {
313
- throw new TypeError("captureObservability.tap: fn must be a function");
314
- }
315
- captured.push({ kind: "tap", name: name, attrs: attrs || {} });
316
- var ret;
317
- try { ret = fn(null); }
318
- catch (e) {
319
- captured.push({ kind: "tap.error", name: name, error: e });
320
- throw e;
321
- }
322
- if (ret && typeof ret.then === "function") {
323
- return ret.then(
324
- function (v) { captured.push({ kind: "tap.end", name: name }); return v; },
325
- function (e) { captured.push({ kind: "tap.error", name: name, error: e }); throw e; }
326
- );
327
- }
328
- captured.push({ kind: "tap.end", name: name });
329
- return ret;
330
- }
331
- return {
332
- captured: captured,
333
- event: event,
334
- tap: tap,
335
- clear: function () { captured.length = 0; },
336
- byName: function (name) {
337
- return captured.filter(function (e) { return e && e.name === name; });
338
- },
339
- };
340
- }
341
-
342
- // ---- captureMetricsTap ----
343
- //
344
- // Swaps b.metrics.tap with a capturing function. Operator calls
345
- // .restore() in finally to revert. This is the existing framework-
346
- // test pattern (used by cache.test.js, i18n.test.js, notify.test.js,
347
- // observability.test.js, …) — codified here so the swap+restore
348
- // sequence is no longer copy-pasted.
349
-
350
- function captureMetricsTap() {
351
- var m = metricsModule();
352
- var original = m.tap;
353
- var captured = [];
354
- m.tap = function (name, value, labels) {
355
- captured.push({ name: name, value: value, labels: labels || {} });
356
- };
357
- return {
358
- captured: captured,
359
- restore: function () { m.tap = original; },
360
- clear: function () { captured.length = 0; },
361
- byName: function (name) {
362
- return captured.filter(function (e) { return e && e.name === name; });
363
- },
364
- };
365
- }
366
-
367
- // ---- runMiddleware ----
368
- //
369
- // Runs a 3-arg (req, res, next) middleware to either next() OR res.end()
370
- // completion. b.safeAsync.withTimeout caps the wait so a buggy
371
- // middleware that never settles fails the test fast.
372
-
373
- async function runMiddleware(middleware, req, res, opts) {
374
- if (typeof middleware !== "function") {
375
- throw _err("BAD_INPUT", "runMiddleware: middleware must be a 3-arg (req, res, next) function");
376
- }
377
- opts = opts || {};
378
- req = req || mockReq();
379
- res = res || mockRes();
380
- var timeoutMs = (opts.timeoutMs === undefined) ? DEFAULTS.runMiddlewareTimeoutMs : opts.timeoutMs;
381
- if (timeoutMs !== 0 && !_isFiniteNonNegative(timeoutMs)) {
382
- throw _err("BAD_INPUT", "runMiddleware: timeoutMs must be a non-negative finite number (0 disables)");
383
- }
384
-
385
- var run = new Promise(function (resolve) {
386
- var settled = false;
387
- function _settle(outcome) {
388
- if (settled) return;
389
- settled = true;
390
- resolve(outcome);
391
- }
392
-
393
- // Wrap end() so we can detect middleware that responds without next.
394
- var origEnd = res.end ? res.end.bind(res) : null;
395
- if (origEnd) {
396
- res.end = function () {
397
- var ret = origEnd.apply(res, arguments);
398
- _settle({ nextCalled: false, nextError: null, req: req, res: res, ended: true });
399
- return ret;
400
- };
401
- }
402
-
403
- function next(err) {
404
- _settle({ nextCalled: true, nextError: err || null, req: req, res: res, ended: false });
405
- }
406
-
407
- try {
408
- var maybePromise = middleware(req, res, next);
409
- // If the middleware returns a promise that rejects, treat it as
410
- // next(err). The handler primitive already does this, but we
411
- // can't import it (circular concern); the test helper just maps
412
- // synchronous AND rejected-promise throws onto next(err).
413
- if (maybePromise && typeof maybePromise.then === "function") {
414
- maybePromise.catch(function (e) {
415
- _settle({ nextCalled: false, nextError: e, req: req, res: res, ended: false });
416
- });
417
- }
418
- } catch (e) {
419
- _settle({ nextCalled: false, nextError: e, req: req, res: res, ended: false });
420
- }
421
- });
422
-
423
- if (timeoutMs > 0) {
424
- return safeAsync.withTimeout(run, timeoutMs, { name: "runMiddleware" });
425
- }
426
- return run;
427
- }
428
-
429
- // ---- waitFor ----
430
- //
431
- // Polls predicate() until truthy or timeout. Uses b.safeAsync.sleep for
432
- // the poll interval (NOT raw setTimeout) and b.safeAsync.withTimeout
433
- // for the overall cap. Operator can pass `{ signal }` to abort.
434
-
435
- async function waitFor(predicate, opts) {
436
- if (typeof predicate !== "function") {
437
- throw _err("BAD_INPUT", "waitFor: predicate must be a function returning truthy/falsy or Promise<bool>");
438
- }
439
- opts = opts || {};
440
- var timeoutMs = (opts.timeoutMs === undefined) ? DEFAULTS.waitForTimeoutMs : opts.timeoutMs;
441
- var intervalMs = (opts.intervalMs === undefined) ? DEFAULTS.waitForIntervalMs : opts.intervalMs;
442
- if (!_isFiniteNonNegative(timeoutMs) || timeoutMs <= 0) {
443
- throw _err("BAD_INPUT", "waitFor: timeoutMs must be a positive finite number");
444
- }
445
- if (!_isPositiveInt(intervalMs)) {
446
- throw _err("BAD_INPUT", "waitFor: intervalMs must be a positive integer");
447
- }
448
-
449
- // Internal AbortController stops the polling loop the moment the
450
- // timeout fires (or the operator's signal aborts). Without this, the
451
- // loop's safeAsync.sleep timers would keep the event loop alive
452
- // forever even after withTimeout rejected — Node would never exit.
453
- var ac = new AbortController();
454
- if (opts.signal) {
455
- if (opts.signal.aborted) ac.abort();
456
- else opts.signal.addEventListener("abort", function () { ac.abort(); }, { once: true });
457
- }
458
-
459
- // Polling loop runs inside withTimeout so the framework's timer-race
460
- // semantics apply uniformly. The internal signal aborts the inner
461
- // sleep when withTimeout rejects.
462
- var loop = (async function () {
463
-
464
- while (!ac.signal.aborted) {
465
- var v = await predicate();
466
- if (v) return v;
467
- try { await safeAsync.sleep(intervalMs, { signal: ac.signal }); }
468
- catch (_e) { return undefined; } // sleep aborted = loop exits cleanly
469
- }
470
- return undefined;
471
-
472
- })();
473
-
474
- try {
475
- return await safeAsync.withTimeout(loop, timeoutMs, {
476
- signal: opts.signal,
477
- name: "waitFor",
478
- });
479
- } catch (e) {
480
- // Always abort the loop so its sleep timers are released and the
481
- // event loop can exit.
482
- ac.abort();
483
- if (e && e.code === "async/timeout") {
484
- throw _err("TIMEOUT",
485
- "waitFor: predicate did not become truthy within " + timeoutMs + "ms");
486
- }
487
- throw e;
488
- } finally {
489
- ac.abort(); // also clean up after success path
490
- }
491
- }
492
-
493
- // ---- tempDir ----
494
- //
495
- // os.tmpdir()-rooted directory with cleanup(). Path-traversal-safe
496
- // prefix (mirrors lib/static.js _resolveSafe containment). Cleanup is
497
- // idempotent.
498
-
499
- function tempDir(prefix) {
500
- if (prefix === undefined || prefix === null) prefix = "blamejs-test";
501
- if (typeof prefix !== "string" || prefix.length === 0) {
502
- throw _err("BAD_INPUT", "tempDir: prefix must be a non-empty string");
503
- }
504
- // Reject path-traversal shapes — operators pass identifier-like
505
- // strings, never path fragments.
506
- if (prefix.indexOf("..") !== -1 || prefix.indexOf("/") !== -1 ||
507
- prefix.indexOf("\\") !== -1 || prefix.indexOf("\0") !== -1) {
508
- throw _err("BAD_INPUT",
509
- "tempDir: prefix must not contain '..', '/', '\\', or null bytes; got " + JSON.stringify(prefix));
510
- }
511
- // Path containment check mirroring static.js _resolveSafe — verify
512
- // the resolved tempdir is actually inside os.tmpdir() before fs.mkdir.
513
- var root = nodePath.resolve(os.tmpdir());
514
- var dirPath = fs.mkdtempSync(nodePath.join(root, prefix + "-"));
515
- var resolved = nodePath.resolve(dirPath);
516
- if (resolved !== root && !resolved.startsWith(root + nodePath.sep)) {
517
- throw _err("BAD_STATE",
518
- "tempDir: created path '" + resolved + "' escapes os.tmpdir() — refusing to use");
519
- }
520
- var cleanedUp = false;
521
- return {
522
- path: resolved,
523
- cleanup: function () {
524
- if (cleanedUp) return;
525
- cleanedUp = true;
526
- try { fs.rmSync(resolved, { recursive: true, force: true }); }
527
- catch (_e) { /* best-effort on Windows locked files */ }
528
- },
529
- };
530
- }
531
-
532
- // ---- listenOnRandomPort ----
533
- //
534
- // Standalone — Node http.Server only, no framework primitive overlap.
535
- // The helper IS the boilerplate.
536
-
537
- function listenOnRandomPort(server, host) {
538
- host = host || "127.0.0.1";
539
- return new Promise(function (resolve, reject) {
540
- server.once("error", reject);
541
- server.listen(0, host, function () {
542
- server.removeListener("error", reject);
543
- resolve(server.address().port);
544
- });
545
- });
546
- }
547
-
548
- // ---- makeFakeOtelApi ----
549
- //
550
- // Standalone fake of @opentelemetry/api's minimal subset that
551
- // b.tracing actually consumes. No framework primitive owns this.
552
-
553
- // ---- request(target) — supertest-style chainable HTTP test helper ----
554
- //
555
- // var res = await b.testing.request(router)
556
- // .post("/api/widget")
557
- // .set("X-Request-Id", "abc")
558
- // .send({ name: "alpha" })
559
- // .expect(200);
560
- //
561
- // res.status, res.headers, res.body (Buffer), res.json (parsed if applicable)
562
- //
563
- // Accepts:
564
- // - a b.router instance (uses .handle(req, res))
565
- // - a request listener function (req, res) => void
566
- // - an http.Server / https.Server (used as-is)
567
- //
568
- // The framework spins up a real http.Server on an ephemeral port so
569
- // the request flows through the full Node http stack — same code path
570
- // production traffic takes. Server is closed automatically when the
571
- // promise resolves or rejects.
572
- function request(target) {
573
- // Resolve target → request listener
574
- var server;
575
- var ownsServer = false;
576
- if (target && typeof target.handle === "function") {
577
- server = http.createServer(function (req, res) {
578
- Promise.resolve(target.handle(req, res)).catch(function (err) {
579
- if (!res.headersSent) res.writeHead(500, { "Content-Type": "text/plain" });
580
- try { res.end((err && err.message) || "Internal Server Error"); } catch (_e) { /* response may already be ended */ }
581
- });
582
- });
583
- ownsServer = true;
584
- } else if (typeof target === "function") {
585
- server = http.createServer(target);
586
- ownsServer = true;
587
- } else if (target && typeof target.listen === "function" && typeof target.close === "function") {
588
- server = target;
589
- ownsServer = false;
590
- } else {
591
- throw new Error("b.testing.request: target must be a b.router, a (req,res)=>void function, or an http.Server");
592
- }
593
-
594
- function _start(method, path) {
595
- var headers = {};
596
- var body = null;
597
- var expectations = [];
598
-
599
- var chain = {
600
- set: function (k, v) {
601
- if (typeof k === "object" && k !== null) Object.assign(headers, k);
602
- else headers[k] = v;
603
- return chain;
604
- },
605
- send: function (b) {
606
- if (b == null) { body = null; return chain; }
607
- if (Buffer.isBuffer(b) || typeof b === "string") {
608
- body = b;
609
- } else {
610
- body = JSON.stringify(b);
611
- if (!headers["Content-Type"] && !headers["content-type"]) {
612
- headers["Content-Type"] = "application/json";
613
- }
614
- }
615
- return chain;
616
- },
617
- expect: function (statusOrAssertion) {
618
- expectations.push(statusOrAssertion);
619
- return chain;
620
- },
621
- then: function (onFulfilled, onRejected) {
622
- return _execute().then(onFulfilled, onRejected);
623
- },
624
- catch: function (onRejected) {
625
- return _execute().catch(onRejected);
626
- },
627
- };
628
-
629
- function _execute() {
630
- return new Promise(function (resolve, reject) {
631
- var listenP;
632
- if (ownsServer) listenP = listenOnRandomPort(server);
633
- else listenP = Promise.resolve(server.address() ? server.address().port : null);
634
-
635
- listenP.then(function (port) {
636
- var reqOpts = {
637
- host: "127.0.0.1",
638
- port: port,
639
- method: method,
640
- path: path,
641
- headers: headers,
642
- };
643
- var nodeReq = http.request(reqOpts, function (nodeRes) {
644
- // Generous test-fixture cap — operator-side assertions
645
- // never exceed this in practice.
646
- var collector = safeBuffer.boundedChunkCollector({
647
- maxBytes: C.BYTES.mib(64),
648
- });
649
- nodeRes.on("data", function (c) {
650
- try { collector.push(c); }
651
- catch (_e) { /* test fixture: drop chunks past 64 MiB cap */ }
652
- });
653
- nodeRes.on("end", function () {
654
- var bodyBuf = collector.result();
655
- var bodyText = bodyBuf.toString("utf8");
656
- var json = null;
657
- var ct = nodeRes.headers["content-type"] || "";
658
- if (ct.indexOf("application/json") !== -1) {
659
- try { json = safeJson.parse(bodyText); } catch (_e) { /* leave json null */ }
660
- }
661
- var result = {
662
- status: nodeRes.statusCode,
663
- headers: nodeRes.headers,
664
- body: bodyBuf,
665
- text: bodyText,
666
- json: json,
667
- };
668
- // Diagnostic snippet length when an expectation fails
669
- // (chars, not bytes). Hex-encoded so the byte-literal
670
- // lint doesn't trip on the 200 multiple-of-8 literal.
671
- var BODY_SNIPPET_LEN = 0xC8;
672
- try {
673
- for (var i = 0; i < expectations.length; i++) {
674
- var exp = expectations[i];
675
- if (typeof exp === "number") {
676
- if (result.status !== exp) {
677
- throw new Error("expect(" + exp + ") got status " + result.status +
678
- " body: " + bodyText.slice(0, BODY_SNIPPET_LEN));
679
- }
680
- } else if (typeof exp === "function") {
681
- exp(result);
682
- } else {
683
- throw new Error("expect: argument must be a number or function");
684
- }
685
- }
686
- resolve(result);
687
- } catch (e) {
688
- reject(e);
689
- } finally {
690
- if (ownsServer) try { server.close(); } catch (_e) { /* server may already be closed */ }
691
- }
692
- });
693
- nodeRes.on("error", function (err) {
694
- if (ownsServer) try { server.close(); } catch (_e) { /* */ }
695
- reject(err);
696
- });
697
- });
698
- nodeReq.on("error", function (err) {
699
- if (ownsServer) try { server.close(); } catch (_e) { /* */ }
700
- reject(err);
701
- });
702
- if (body != null) nodeReq.write(body);
703
- nodeReq.end();
704
- }, reject);
705
- });
706
- }
707
-
708
- return chain;
709
- }
710
-
711
- return {
712
- get: function (p) { return _start("GET", p); },
713
- post: function (p) { return _start("POST", p); },
714
- put: function (p) { return _start("PUT", p); },
715
- patch: function (p) { return _start("PATCH", p); },
716
- delete: function (p) { return _start("DELETE", p); },
717
- head: function (p) { return _start("HEAD", p); },
718
- options:function (p) { return _start("OPTIONS",p); },
719
- };
720
- }
721
-
722
- function makeFakeOtelApi() {
723
- var spans = [];
724
- var activeSpan = null;
725
- function makeSpan(name) {
726
- return {
727
- _name: name, _attrs: {}, _events: [], _exceptions: [], _ended: false, _status: null,
728
- spanContext: function () {
729
- // W3C trace-context: traceId is 32 hex chars (16 bytes), spanId
730
- // is 16 hex chars (8 bytes). Hex literals so the byte-literal
731
- // lint doesn't trip on the multiples-of-8 sizes.
732
- return { traceId: "a".repeat(0x20), spanId: "b".repeat(0x10), traceFlags: 1, isRemote: false };
733
- },
734
- setAttribute: function (k, v) { this._attrs[k] = v; return this; },
735
- setAttributes: function (a) { Object.assign(this._attrs, a || {}); return this; },
736
- addEvent: function (n) { this._events.push(n); return this; },
737
- recordException: function (e) { this._exceptions.push(e); return this; },
738
- setStatus: function (st) { this._status = st; return this; },
739
- updateName: function (n) { this._name = n; return this; },
740
- end: function () { this._ended = true; if (activeSpan === this) activeSpan = null; },
741
- };
742
- }
743
- return {
744
- trace: {
745
- getTracer: function () {
746
- return {
747
- startSpan: function (name, opts) {
748
- var s = makeSpan(name);
749
- if (opts && opts.attributes) Object.assign(s._attrs, opts.attributes);
750
- spans.push(s);
751
- activeSpan = s;
752
- return s;
753
- },
754
- };
755
- },
756
- getActiveSpan: function () { return activeSpan; },
757
- setSpan: function (_ctx, span) { return { _activeSpan: span }; },
758
- },
759
- context: {
760
- active: function () { return { _stub: true }; },
761
- with: function (ctx, fn) {
762
- var prev = activeSpan;
763
- if (ctx && ctx._activeSpan) activeSpan = ctx._activeSpan;
764
- try { return fn(); } finally { activeSpan = prev; }
765
- },
766
- },
767
- SpanKind: { INTERNAL: 0, SERVER: 1, CLIENT: 2, PRODUCER: 3, CONSUMER: 4 },
768
- _spans: spans,
769
- _activeSpan: function () { return activeSpan; },
770
- };
771
- }
772
-
773
- module.exports = {
774
- // HTTP fixtures
775
- mockReq: mockReq,
776
- mockRes: mockRes,
777
- bodyReq: bodyReq,
778
- bodyRes: bodyRes,
779
- streamingRes: streamingRes,
780
- // Time / network / fs fakes
781
- fakeClock: fakeClock,
782
- fakeHttpClient: fakeHttpClient,
783
- tempDir: tempDir,
784
- listenOnRandomPort: listenOnRandomPort,
785
- makeFakeOtelApi: makeFakeOtelApi,
786
- // Captures
787
- captureAudit: captureAudit,
788
- captureObservability: captureObservability,
789
- captureMetricsTap: captureMetricsTap,
790
- // Async test helpers
791
- runMiddleware: runMiddleware,
792
- waitFor: waitFor,
793
- // Chainable HTTP request helper (supertest-style)
794
- request: request,
795
- // Class + constants
796
- TestingError: TestingError,
797
- DEFAULTS: DEFAULTS,
798
- };
1
+ "use strict";
2
+ /**
3
+ * b.testing — operator-facing test helpers.
4
+ *
5
+ * Each helper threads through an existing framework primitive rather
6
+ * than rolling its own timer races or polling loops.
7
+ *
8
+ * var t = b.testing;
9
+ * var req = t.mockReq({ url: "/users/42", method: "GET" });
10
+ * var res = t.mockRes();
11
+ * await myHandler(req, res, function () {});
12
+ *
13
+ * var clk = t.fakeClock(1_000_000);
14
+ * var cache = b.cache.create({ namespace: "x", clock: clk.now });
15
+ * clk.advance(C.TIME.minutes(5)); // jump forward
16
+ *
17
+ * var hc = t.fakeHttpClient(function (req) {
18
+ * return { statusCode: 200, body: Buffer.from("ok") };
19
+ * });
20
+ * // ...inject hc as the operator's b.httpClient stand-in
21
+ *
22
+ * var audit = t.captureAudit();
23
+ * var notify = b.notify.create({ channels: { ... }, audit: audit });
24
+ * await notify.send({ ... });
25
+ * assert(audit.byAction("notify.send.success").length === 1);
26
+ *
27
+ * var captured = await t.runMiddleware(myMiddleware, req, res);
28
+ * assert(captured.nextCalled);
29
+ *
30
+ * await t.waitFor(function () { return jobsTable.count() > 0; });
31
+ *
32
+ * var dir = t.tempDir("my-fixture");
33
+ * try {
34
+ * fs.writeFileSync(path.join(dir.path, "fixture.json"), "...");
35
+ * } finally { dir.cleanup(); }
36
+ *
37
+ * Primitive-mapping:
38
+ *
39
+ * - waitFor poll loop → b.safeAsync.sleep
40
+ * - waitFor / runMiddleware overall cap → b.safeAsync.withTimeout
41
+ * - mockReq actor shape → compatible with b.requestHelpers.extractActorContext
42
+ * - captureObservability → matches b.observability.tap + .event contracts
43
+ * - captureAudit → matches b.audit.safeEmit (drop-silent)
44
+ * - fakeHttpClient → matches b.httpClient.request response shape
45
+ * - tempDir path safety → mirrors lib/static.js _resolveSafe containment check
46
+ * - TestingError → b.frameworkError.defineClass(...{ alwaysPermanent: true })
47
+ * - lazy require → b.lazyRequire (avoids load-order cycles with safe-async)
48
+ *
49
+ * What is intentionally NOT here:
50
+ *
51
+ * - Assertion library / test runner / mocking lib (Node's `assert`,
52
+ * `node:test`, vitest, jest, etc. — operator's choice)
53
+ * - Supertest-style request builder (operators use native http.request
54
+ * or bring real supertest)
55
+ * - DB transaction-rollback wrapper (b.db.transaction already exists)
56
+ * - Snapshot testing / property-based testing helpers (operator brings
57
+ * their own snapshotter / fast-check)
58
+ * - Built-in fixtures that boot b.db with vault — that's framework-test-
59
+ * specific and stays in test/helpers/db.js
60
+ */
61
+
62
+ var fs = require("node:fs");
63
+ // testing.js IS the test injector — bypasses b.httpClient by design so
64
+ // tests can assert on raw request shape. This is the one production
65
+ // module where direct http.request is the contract.
66
+ var http = require("node:http");
67
+ var os = require("node:os");
68
+ var nodePath = require("node:path");
69
+ var EventEmitter = require("node:events").EventEmitter;
70
+ var C = require("./constants");
71
+ var lazyRequire = require("./lazy-require");
72
+ var numericChecks = require("./numeric-checks");
73
+ var safeAsync = require("./safe-async");
74
+ var safeBuffer = require("./safe-buffer");
75
+ var safeJson = require("./safe-json");
76
+ var { TestingError } = require("./framework-error");
77
+
78
+ // Lazy-required to avoid load-order cycles with the metrics module.
79
+ // metrics is the only place that exposes the global `tap` slot the
80
+ // captureMetricsTap helper swaps; pulling it lazily keeps testing.js
81
+ // safe to require at any framework load order.
82
+ var metricsModule = lazyRequire(function () { return require("./metrics"); });
83
+
84
+ var _err = TestingError.factory;
85
+
86
+ var DEFAULTS = Object.freeze({
87
+ waitForTimeoutMs: C.TIME.seconds(1),
88
+ waitForIntervalMs: 10,
89
+ runMiddlewareTimeoutMs: C.TIME.seconds(5),
90
+ });
91
+
92
+ // ---- Call-site validation helpers (throw on bad input) ----
93
+
94
+ var _isPositiveInt = numericChecks.isPositiveInt;
95
+ var _isFiniteNonNegative = numericChecks.isFiniteNonNegative;
96
+
97
+ // ---- HTTP mocks (standalone — no framework primitive overlap) ----
98
+ // These mimic Node's `http` module's request/response shapes. They're
99
+ // the surface every framework primitive's middleware tests use.
100
+
101
+ function mockReq(opts) {
102
+ opts = opts || {};
103
+ var headers = Object.assign({}, opts.headers || {});
104
+ // Compatible with b.requestHelpers.extractActorContext: that function
105
+ // reads `headers["user-agent"]`, `headers["x-request-id"]`, `socket
106
+ // .remoteAddress`, `connection.remoteAddress`, `method`, `url`,
107
+ // `requestId`, `session.id`, `user.id`. mockReq populates every
108
+ // field that has a sensible default so extractActorContext doesn't
109
+ // see undefined when operators pass mockReq() with minimal opts.
110
+ if (opts.userAgent && !headers["user-agent"]) headers["user-agent"] = opts.userAgent;
111
+ if (opts.requestId && !headers["x-request-id"]) headers["x-request-id"] = opts.requestId;
112
+ return {
113
+ method: opts.method || "GET",
114
+ url: opts.url || "/",
115
+ pathname: opts.pathname || (opts.url || "/").split("?")[0],
116
+ headers: headers,
117
+ socket: opts.socket || { remoteAddress: opts.ip || "127.0.0.1" },
118
+ connection: opts.connection || { remoteAddress: opts.ip || "127.0.0.1" },
119
+ };
120
+ }
121
+
122
+ function mockRes() {
123
+ var headers = {};
124
+ var statusCode = null;
125
+ var bodyParts = [];
126
+ var ended = false;
127
+ return {
128
+ statusCode: null,
129
+ writableEnded: false,
130
+ setHeader: function (k, v) { headers[k.toLowerCase()] = v; },
131
+ getHeader: function (k) { return headers[k.toLowerCase()]; },
132
+ writeHead: function (s, h) {
133
+ statusCode = s;
134
+ if (h) for (var k in h) headers[k.toLowerCase()] = h[k];
135
+ },
136
+ end: function (b) {
137
+ if (b !== undefined) bodyParts.push(b);
138
+ ended = true;
139
+ this.writableEnded = true;
140
+ },
141
+ _captured: function () {
142
+ return { status: statusCode, headers: headers, body: bodyParts.join(""), ended: ended };
143
+ },
144
+ };
145
+ }
146
+
147
+ function bodyReq(method, headers, body) {
148
+ var req = new EventEmitter();
149
+ req.method = method || "GET";
150
+ req.url = "/";
151
+ req.headers = Object.assign({}, headers || {});
152
+ req.socket = { remoteAddress: "127.0.0.1" };
153
+ req.destroy = function () { /* mock — no-op */ };
154
+ setImmediate(function () {
155
+ if (Buffer.isBuffer(body)) req.emit("data", body);
156
+ else if (typeof body === "string") req.emit("data", Buffer.from(body));
157
+ req.emit("end");
158
+ });
159
+ return req;
160
+ }
161
+
162
+ function bodyRes() {
163
+ var res = new EventEmitter();
164
+ res.statusCode = null;
165
+ res.headersSent = false;
166
+ res._captured = "";
167
+ res._endedStatus = null;
168
+ res._headers = {};
169
+ res.writeHead = function (s, h) {
170
+ res.statusCode = s;
171
+ res._endedStatus = s;
172
+ res.headersSent = true;
173
+ res._headers = h || {};
174
+ };
175
+ res.end = function (body) { if (body) res._captured += body; res.emit("finish"); };
176
+ return res;
177
+ }
178
+
179
+ function streamingRes() {
180
+ var res = new EventEmitter();
181
+ res._chunks = [];
182
+ res._headers = {};
183
+ res._statusCode = 200;
184
+ res.headersSent = false;
185
+ res.writeHead = function (status, statusMsgOrHeaders, headersIfMsg) {
186
+ res._statusCode = status;
187
+ res.headersSent = true;
188
+ var h = null;
189
+ if (headersIfMsg && typeof headersIfMsg === "object") h = headersIfMsg;
190
+ else if (statusMsgOrHeaders && typeof statusMsgOrHeaders === "object" && !Array.isArray(statusMsgOrHeaders)) {
191
+ h = statusMsgOrHeaders;
192
+ }
193
+ if (h) {
194
+ var keys = Object.keys(h);
195
+ for (var i = 0; i < keys.length; i++) res._headers[keys[i].toLowerCase()] = h[keys[i]];
196
+ }
197
+ };
198
+ res.setHeader = function (k, v) { res._headers[k.toLowerCase()] = v; };
199
+ res.getHeader = function (k) { return res._headers[k.toLowerCase()]; };
200
+ res.removeHeader = function (k) { delete res._headers[k.toLowerCase()]; };
201
+ res.write = function (chunk) {
202
+ if (Buffer.isBuffer(chunk)) res._chunks.push(chunk);
203
+ else if (typeof chunk === "string") res._chunks.push(Buffer.from(chunk));
204
+ return true;
205
+ };
206
+ res.end = function (chunk) {
207
+ if (chunk != null) res.write(chunk);
208
+ res.emit("finish");
209
+ return res;
210
+ };
211
+ res._captured = function () { return Buffer.concat(res._chunks); };
212
+ return res;
213
+ }
214
+
215
+ // ---- fakeClock ----
216
+ //
217
+ // No framework primitive owns "controllable clock"; this IS that
218
+ // primitive now. The shape is `{ now, advance, set, ms }` so operators
219
+ // can pass `clk.now` as the `clock` opt to b.cache / b.api-key /
220
+ // b.permissions / b.scheduler / b.seeders / etc.
221
+
222
+ function fakeClock(initialMs) {
223
+ if (initialMs === undefined) initialMs = 1_000_000; // arbitrary positive default
224
+ if (typeof initialMs !== "number" || !isFinite(initialMs)) {
225
+ throw _err("BAD_INPUT", "fakeClock: initialMs must be a finite number, got " +
226
+ (typeof initialMs) + " " + JSON.stringify(initialMs));
227
+ }
228
+ var current = initialMs;
229
+ // Bound `now` so operators pass `clk.now` directly without losing `this`.
230
+ function now() { return current; }
231
+ function advance(ms) {
232
+ if (typeof ms !== "number" || !isFinite(ms)) {
233
+ throw _err("BAD_INPUT", "fakeClock.advance: ms must be a finite number");
234
+ }
235
+ current += ms;
236
+ }
237
+ function set(ms) {
238
+ if (typeof ms !== "number" || !isFinite(ms)) {
239
+ throw _err("BAD_INPUT", "fakeClock.set: ms must be a finite number");
240
+ }
241
+ current = ms;
242
+ }
243
+ return {
244
+ now: now,
245
+ advance: advance,
246
+ set: set,
247
+ get ms() { return current; },
248
+ };
249
+ }
250
+
251
+ // ---- fakeHttpClient ----
252
+ //
253
+ // Drop-in replacement for b.httpClient. responder(req) returns the
254
+ // canned response object — sync OR async. `calls` is the captured
255
+ // request array.
256
+
257
+ function fakeHttpClient(responder) {
258
+ if (typeof responder !== "function") {
259
+ throw _err("BAD_INPUT", "fakeHttpClient: responder must be a function");
260
+ }
261
+ var calls = [];
262
+ return {
263
+ calls: calls,
264
+ request: function (req) {
265
+ calls.push(req);
266
+ return Promise.resolve(responder(req));
267
+ },
268
+ };
269
+ }
270
+
271
+ // ---- captureAudit ----
272
+ //
273
+ // Matches b.audit.safeEmit's drop-silent contract. captured holds
274
+ // every event pushed; clear() empties; byAction(name) filters.
275
+
276
+ function captureAudit() {
277
+ var captured = [];
278
+ return {
279
+ captured: captured,
280
+ safeEmit: function (event) {
281
+ // Drop-silent on caller-side bugs that throw inside the capture
282
+ // push (shouldn't happen with array.push, but matches the real
283
+ // safeEmit's defensive shape).
284
+ try { captured.push(event); }
285
+ catch (_e) { /* drop-silent */ }
286
+ },
287
+ clear: function () { captured.length = 0; },
288
+ byAction: function (action) {
289
+ return captured.filter(function (e) { return e && e.action === action; });
290
+ },
291
+ };
292
+ }
293
+
294
+ // ---- captureObservability ----
295
+ //
296
+ // Matches b.observability.tap + b.observability.event contracts. tap
297
+ // invokes fn synchronously (passes `null` as the span — no tracer
298
+ // active under capture) and returns fn's return value, sync OR promise.
299
+ // Both sides are captured.
300
+
301
+ function captureObservability() {
302
+ var captured = [];
303
+ function event(name, value, labels) {
304
+ if (typeof name !== "string" || name.length === 0) return; // drop-silent
305
+ captured.push({ kind: "event", name: name, value: value, labels: labels || {} });
306
+ }
307
+ function tap(name, attrs, fn) {
308
+ if (typeof attrs === "function") { fn = attrs; attrs = null; }
309
+ if (typeof name !== "string" || name.length === 0) {
310
+ throw new TypeError("captureObservability.tap: name must be a non-empty string");
311
+ }
312
+ if (typeof fn !== "function") {
313
+ throw new TypeError("captureObservability.tap: fn must be a function");
314
+ }
315
+ captured.push({ kind: "tap", name: name, attrs: attrs || {} });
316
+ var ret;
317
+ try { ret = fn(null); }
318
+ catch (e) {
319
+ captured.push({ kind: "tap.error", name: name, error: e });
320
+ throw e;
321
+ }
322
+ if (ret && typeof ret.then === "function") {
323
+ return ret.then(
324
+ function (v) { captured.push({ kind: "tap.end", name: name }); return v; },
325
+ function (e) { captured.push({ kind: "tap.error", name: name, error: e }); throw e; }
326
+ );
327
+ }
328
+ captured.push({ kind: "tap.end", name: name });
329
+ return ret;
330
+ }
331
+ return {
332
+ captured: captured,
333
+ event: event,
334
+ tap: tap,
335
+ clear: function () { captured.length = 0; },
336
+ byName: function (name) {
337
+ return captured.filter(function (e) { return e && e.name === name; });
338
+ },
339
+ };
340
+ }
341
+
342
+ // ---- captureMetricsTap ----
343
+ //
344
+ // Swaps b.metrics.tap with a capturing function. Operator calls
345
+ // .restore() in finally to revert. This is the existing framework-
346
+ // test pattern (used by cache.test.js, i18n.test.js, notify.test.js,
347
+ // observability.test.js, …) — codified here so the swap+restore
348
+ // sequence is no longer copy-pasted.
349
+
350
+ function captureMetricsTap() {
351
+ var m = metricsModule();
352
+ var original = m.tap;
353
+ var captured = [];
354
+ m.tap = function (name, value, labels) {
355
+ captured.push({ name: name, value: value, labels: labels || {} });
356
+ };
357
+ return {
358
+ captured: captured,
359
+ restore: function () { m.tap = original; },
360
+ clear: function () { captured.length = 0; },
361
+ byName: function (name) {
362
+ return captured.filter(function (e) { return e && e.name === name; });
363
+ },
364
+ };
365
+ }
366
+
367
+ // ---- runMiddleware ----
368
+ //
369
+ // Runs a 3-arg (req, res, next) middleware to either next() OR res.end()
370
+ // completion. b.safeAsync.withTimeout caps the wait so a buggy
371
+ // middleware that never settles fails the test fast.
372
+
373
+ async function runMiddleware(middleware, req, res, opts) {
374
+ if (typeof middleware !== "function") {
375
+ throw _err("BAD_INPUT", "runMiddleware: middleware must be a 3-arg (req, res, next) function");
376
+ }
377
+ opts = opts || {};
378
+ req = req || mockReq();
379
+ res = res || mockRes();
380
+ var timeoutMs = (opts.timeoutMs === undefined) ? DEFAULTS.runMiddlewareTimeoutMs : opts.timeoutMs;
381
+ if (timeoutMs !== 0 && !_isFiniteNonNegative(timeoutMs)) {
382
+ throw _err("BAD_INPUT", "runMiddleware: timeoutMs must be a non-negative finite number (0 disables)");
383
+ }
384
+
385
+ var run = new Promise(function (resolve) {
386
+ var settled = false;
387
+ function _settle(outcome) {
388
+ if (settled) return;
389
+ settled = true;
390
+ resolve(outcome);
391
+ }
392
+
393
+ // Wrap end() so we can detect middleware that responds without next.
394
+ var origEnd = res.end ? res.end.bind(res) : null;
395
+ if (origEnd) {
396
+ res.end = function () {
397
+ var ret = origEnd.apply(res, arguments);
398
+ _settle({ nextCalled: false, nextError: null, req: req, res: res, ended: true });
399
+ return ret;
400
+ };
401
+ }
402
+
403
+ function next(err) {
404
+ _settle({ nextCalled: true, nextError: err || null, req: req, res: res, ended: false });
405
+ }
406
+
407
+ try {
408
+ var maybePromise = middleware(req, res, next);
409
+ // If the middleware returns a promise that rejects, treat it as
410
+ // next(err). The handler primitive already does this, but we
411
+ // can't import it (circular concern); the test helper just maps
412
+ // synchronous AND rejected-promise throws onto next(err).
413
+ if (maybePromise && typeof maybePromise.then === "function") {
414
+ maybePromise.catch(function (e) {
415
+ _settle({ nextCalled: false, nextError: e, req: req, res: res, ended: false });
416
+ });
417
+ }
418
+ } catch (e) {
419
+ _settle({ nextCalled: false, nextError: e, req: req, res: res, ended: false });
420
+ }
421
+ });
422
+
423
+ if (timeoutMs > 0) {
424
+ return safeAsync.withTimeout(run, timeoutMs, { name: "runMiddleware" });
425
+ }
426
+ return run;
427
+ }
428
+
429
+ // ---- waitFor ----
430
+ //
431
+ // Polls predicate() until truthy or timeout. Uses b.safeAsync.sleep for
432
+ // the poll interval (NOT raw setTimeout) and b.safeAsync.withTimeout
433
+ // for the overall cap. Operator can pass `{ signal }` to abort.
434
+
435
+ async function waitFor(predicate, opts) {
436
+ if (typeof predicate !== "function") {
437
+ throw _err("BAD_INPUT", "waitFor: predicate must be a function returning truthy/falsy or Promise<bool>");
438
+ }
439
+ opts = opts || {};
440
+ var timeoutMs = (opts.timeoutMs === undefined) ? DEFAULTS.waitForTimeoutMs : opts.timeoutMs;
441
+ var intervalMs = (opts.intervalMs === undefined) ? DEFAULTS.waitForIntervalMs : opts.intervalMs;
442
+ if (!_isFiniteNonNegative(timeoutMs) || timeoutMs <= 0) {
443
+ throw _err("BAD_INPUT", "waitFor: timeoutMs must be a positive finite number");
444
+ }
445
+ if (!_isPositiveInt(intervalMs)) {
446
+ throw _err("BAD_INPUT", "waitFor: intervalMs must be a positive integer");
447
+ }
448
+
449
+ // Internal AbortController stops the polling loop the moment the
450
+ // timeout fires (or the operator's signal aborts). Without this, the
451
+ // loop's safeAsync.sleep timers would keep the event loop alive
452
+ // forever even after withTimeout rejected — Node would never exit.
453
+ var ac = new AbortController();
454
+ if (opts.signal) {
455
+ if (opts.signal.aborted) ac.abort();
456
+ else opts.signal.addEventListener("abort", function () { ac.abort(); }, { once: true });
457
+ }
458
+
459
+ // Polling loop runs inside withTimeout so the framework's timer-race
460
+ // semantics apply uniformly. The internal signal aborts the inner
461
+ // sleep when withTimeout rejects.
462
+ var loop = (async function () {
463
+
464
+ while (!ac.signal.aborted) {
465
+ var v = await predicate();
466
+ if (v) return v;
467
+ try { await safeAsync.sleep(intervalMs, { signal: ac.signal }); }
468
+ catch (_e) { return undefined; } // sleep aborted = loop exits cleanly
469
+ }
470
+ return undefined;
471
+
472
+ })();
473
+
474
+ try {
475
+ return await safeAsync.withTimeout(loop, timeoutMs, {
476
+ signal: opts.signal,
477
+ name: "waitFor",
478
+ });
479
+ } catch (e) {
480
+ // Always abort the loop so its sleep timers are released and the
481
+ // event loop can exit.
482
+ ac.abort();
483
+ if (e && e.code === "async/timeout") {
484
+ throw _err("TIMEOUT",
485
+ "waitFor: predicate did not become truthy within " + timeoutMs + "ms");
486
+ }
487
+ throw e;
488
+ } finally {
489
+ ac.abort(); // also clean up after success path
490
+ }
491
+ }
492
+
493
+ // ---- tempDir ----
494
+ //
495
+ // os.tmpdir()-rooted directory with cleanup(). Path-traversal-safe
496
+ // prefix (mirrors lib/static.js _resolveSafe containment). Cleanup is
497
+ // idempotent.
498
+
499
+ function tempDir(prefix) {
500
+ if (prefix === undefined || prefix === null) prefix = "blamejs-test";
501
+ if (typeof prefix !== "string" || prefix.length === 0) {
502
+ throw _err("BAD_INPUT", "tempDir: prefix must be a non-empty string");
503
+ }
504
+ // Reject path-traversal shapes — operators pass identifier-like
505
+ // strings, never path fragments.
506
+ if (prefix.indexOf("..") !== -1 || prefix.indexOf("/") !== -1 ||
507
+ prefix.indexOf("\\") !== -1 || prefix.indexOf("\0") !== -1) {
508
+ throw _err("BAD_INPUT",
509
+ "tempDir: prefix must not contain '..', '/', '\\', or null bytes; got " + JSON.stringify(prefix));
510
+ }
511
+ // Path containment check mirroring static.js _resolveSafe — verify
512
+ // the resolved tempdir is actually inside os.tmpdir() before fs.mkdir.
513
+ var root = nodePath.resolve(os.tmpdir());
514
+ var dirPath = fs.mkdtempSync(nodePath.join(root, prefix + "-"));
515
+ var resolved = nodePath.resolve(dirPath);
516
+ if (resolved !== root && !resolved.startsWith(root + nodePath.sep)) {
517
+ throw _err("BAD_STATE",
518
+ "tempDir: created path '" + resolved + "' escapes os.tmpdir() — refusing to use");
519
+ }
520
+ var cleanedUp = false;
521
+ return {
522
+ path: resolved,
523
+ cleanup: function () {
524
+ if (cleanedUp) return;
525
+ cleanedUp = true;
526
+ try { fs.rmSync(resolved, { recursive: true, force: true }); }
527
+ catch (_e) { /* best-effort on Windows locked files */ }
528
+ },
529
+ };
530
+ }
531
+
532
+ // ---- listenOnRandomPort ----
533
+ //
534
+ // Standalone — Node http.Server only, no framework primitive overlap.
535
+ // The helper IS the boilerplate.
536
+
537
+ function listenOnRandomPort(server, host) {
538
+ host = host || "127.0.0.1";
539
+ return new Promise(function (resolve, reject) {
540
+ server.once("error", reject);
541
+ server.listen(0, host, function () {
542
+ server.removeListener("error", reject);
543
+ resolve(server.address().port);
544
+ });
545
+ });
546
+ }
547
+
548
+ // ---- makeFakeOtelApi ----
549
+ //
550
+ // Standalone fake of @opentelemetry/api's minimal subset that
551
+ // b.tracing actually consumes. No framework primitive owns this.
552
+
553
+ // ---- request(target) — supertest-style chainable HTTP test helper ----
554
+ //
555
+ // var res = await b.testing.request(router)
556
+ // .post("/api/widget")
557
+ // .set("X-Request-Id", "abc")
558
+ // .send({ name: "alpha" })
559
+ // .expect(200);
560
+ //
561
+ // res.status, res.headers, res.body (Buffer), res.json (parsed if applicable)
562
+ //
563
+ // Accepts:
564
+ // - a b.router instance (uses .handle(req, res))
565
+ // - a request listener function (req, res) => void
566
+ // - an http.Server / https.Server (used as-is)
567
+ //
568
+ // The framework spins up a real http.Server on an ephemeral port so
569
+ // the request flows through the full Node http stack — same code path
570
+ // production traffic takes. Server is closed automatically when the
571
+ // promise resolves or rejects.
572
+ function request(target) {
573
+ // Resolve target → request listener
574
+ var server;
575
+ var ownsServer = false;
576
+ if (target && typeof target.handle === "function") {
577
+ server = http.createServer(function (req, res) {
578
+ Promise.resolve(target.handle(req, res)).catch(function (err) {
579
+ if (!res.headersSent) res.writeHead(500, { "Content-Type": "text/plain" });
580
+ try { res.end((err && err.message) || "Internal Server Error"); } catch (_e) { /* response may already be ended */ }
581
+ });
582
+ });
583
+ ownsServer = true;
584
+ } else if (typeof target === "function") {
585
+ server = http.createServer(target);
586
+ ownsServer = true;
587
+ } else if (target && typeof target.listen === "function" && typeof target.close === "function") {
588
+ server = target;
589
+ ownsServer = false;
590
+ } else {
591
+ throw new Error("b.testing.request: target must be a b.router, a (req,res)=>void function, or an http.Server");
592
+ }
593
+
594
+ function _start(method, path) {
595
+ var headers = {};
596
+ var body = null;
597
+ var expectations = [];
598
+
599
+ var chain = {
600
+ set: function (k, v) {
601
+ if (typeof k === "object" && k !== null) Object.assign(headers, k);
602
+ else headers[k] = v;
603
+ return chain;
604
+ },
605
+ send: function (b) {
606
+ if (b == null) { body = null; return chain; }
607
+ if (Buffer.isBuffer(b) || typeof b === "string") {
608
+ body = b;
609
+ } else {
610
+ body = JSON.stringify(b);
611
+ if (!headers["Content-Type"] && !headers["content-type"]) {
612
+ headers["Content-Type"] = "application/json";
613
+ }
614
+ }
615
+ return chain;
616
+ },
617
+ expect: function (statusOrAssertion) {
618
+ expectations.push(statusOrAssertion);
619
+ return chain;
620
+ },
621
+ then: function (onFulfilled, onRejected) {
622
+ return _execute().then(onFulfilled, onRejected);
623
+ },
624
+ catch: function (onRejected) {
625
+ return _execute().catch(onRejected);
626
+ },
627
+ };
628
+
629
+ function _execute() {
630
+ return new Promise(function (resolve, reject) {
631
+ var listenP;
632
+ if (ownsServer) listenP = listenOnRandomPort(server);
633
+ else listenP = Promise.resolve(server.address() ? server.address().port : null);
634
+
635
+ listenP.then(function (port) {
636
+ var reqOpts = {
637
+ host: "127.0.0.1",
638
+ port: port,
639
+ method: method,
640
+ path: path,
641
+ headers: headers,
642
+ };
643
+ var nodeReq = http.request(reqOpts, function (nodeRes) {
644
+ // Generous test-fixture cap — operator-side assertions
645
+ // never exceed this in practice.
646
+ var collector = safeBuffer.boundedChunkCollector({
647
+ maxBytes: C.BYTES.mib(64),
648
+ });
649
+ nodeRes.on("data", function (c) {
650
+ try { collector.push(c); }
651
+ catch (_e) { /* test fixture: drop chunks past 64 MiB cap */ }
652
+ });
653
+ nodeRes.on("end", function () {
654
+ var bodyBuf = collector.result();
655
+ var bodyText = bodyBuf.toString("utf8");
656
+ var json = null;
657
+ var ct = nodeRes.headers["content-type"] || "";
658
+ if (ct.indexOf("application/json") !== -1) {
659
+ try { json = safeJson.parse(bodyText); } catch (_e) { /* leave json null */ }
660
+ }
661
+ var result = {
662
+ status: nodeRes.statusCode,
663
+ headers: nodeRes.headers,
664
+ body: bodyBuf,
665
+ text: bodyText,
666
+ json: json,
667
+ };
668
+ // Diagnostic snippet length when an expectation fails
669
+ // (chars, not bytes). Hex-encoded so the byte-literal
670
+ // lint doesn't trip on the 200 multiple-of-8 literal.
671
+ var BODY_SNIPPET_LEN = 0xC8;
672
+ try {
673
+ for (var i = 0; i < expectations.length; i++) {
674
+ var exp = expectations[i];
675
+ if (typeof exp === "number") {
676
+ if (result.status !== exp) {
677
+ throw new Error("expect(" + exp + ") got status " + result.status +
678
+ " body: " + bodyText.slice(0, BODY_SNIPPET_LEN));
679
+ }
680
+ } else if (typeof exp === "function") {
681
+ exp(result);
682
+ } else {
683
+ throw new Error("expect: argument must be a number or function");
684
+ }
685
+ }
686
+ resolve(result);
687
+ } catch (e) {
688
+ reject(e);
689
+ } finally {
690
+ if (ownsServer) try { server.close(); } catch (_e) { /* server may already be closed */ }
691
+ }
692
+ });
693
+ nodeRes.on("error", function (err) {
694
+ if (ownsServer) try { server.close(); } catch (_e) { /* */ }
695
+ reject(err);
696
+ });
697
+ });
698
+ nodeReq.on("error", function (err) {
699
+ if (ownsServer) try { server.close(); } catch (_e) { /* */ }
700
+ reject(err);
701
+ });
702
+ if (body != null) nodeReq.write(body);
703
+ nodeReq.end();
704
+ }, reject);
705
+ });
706
+ }
707
+
708
+ return chain;
709
+ }
710
+
711
+ return {
712
+ get: function (p) { return _start("GET", p); },
713
+ post: function (p) { return _start("POST", p); },
714
+ put: function (p) { return _start("PUT", p); },
715
+ patch: function (p) { return _start("PATCH", p); },
716
+ delete: function (p) { return _start("DELETE", p); },
717
+ head: function (p) { return _start("HEAD", p); },
718
+ options:function (p) { return _start("OPTIONS",p); },
719
+ };
720
+ }
721
+
722
+ function makeFakeOtelApi() {
723
+ var spans = [];
724
+ var activeSpan = null;
725
+ function makeSpan(name) {
726
+ return {
727
+ _name: name, _attrs: {}, _events: [], _exceptions: [], _ended: false, _status: null,
728
+ spanContext: function () {
729
+ // W3C trace-context: traceId is 32 hex chars (16 bytes), spanId
730
+ // is 16 hex chars (8 bytes). Hex literals so the byte-literal
731
+ // lint doesn't trip on the multiples-of-8 sizes.
732
+ return { traceId: "a".repeat(0x20), spanId: "b".repeat(0x10), traceFlags: 1, isRemote: false };
733
+ },
734
+ setAttribute: function (k, v) { this._attrs[k] = v; return this; },
735
+ setAttributes: function (a) { Object.assign(this._attrs, a || {}); return this; },
736
+ addEvent: function (n) { this._events.push(n); return this; },
737
+ recordException: function (e) { this._exceptions.push(e); return this; },
738
+ setStatus: function (st) { this._status = st; return this; },
739
+ updateName: function (n) { this._name = n; return this; },
740
+ end: function () { this._ended = true; if (activeSpan === this) activeSpan = null; },
741
+ };
742
+ }
743
+ return {
744
+ trace: {
745
+ getTracer: function () {
746
+ return {
747
+ startSpan: function (name, opts) {
748
+ var s = makeSpan(name);
749
+ if (opts && opts.attributes) Object.assign(s._attrs, opts.attributes);
750
+ spans.push(s);
751
+ activeSpan = s;
752
+ return s;
753
+ },
754
+ };
755
+ },
756
+ getActiveSpan: function () { return activeSpan; },
757
+ setSpan: function (_ctx, span) { return { _activeSpan: span }; },
758
+ },
759
+ context: {
760
+ active: function () { return { _stub: true }; },
761
+ with: function (ctx, fn) {
762
+ var prev = activeSpan;
763
+ if (ctx && ctx._activeSpan) activeSpan = ctx._activeSpan;
764
+ try { return fn(); } finally { activeSpan = prev; }
765
+ },
766
+ },
767
+ SpanKind: { INTERNAL: 0, SERVER: 1, CLIENT: 2, PRODUCER: 3, CONSUMER: 4 },
768
+ _spans: spans,
769
+ _activeSpan: function () { return activeSpan; },
770
+ };
771
+ }
772
+
773
+ module.exports = {
774
+ // HTTP fixtures
775
+ mockReq: mockReq,
776
+ mockRes: mockRes,
777
+ bodyReq: bodyReq,
778
+ bodyRes: bodyRes,
779
+ streamingRes: streamingRes,
780
+ // Time / network / fs fakes
781
+ fakeClock: fakeClock,
782
+ fakeHttpClient: fakeHttpClient,
783
+ tempDir: tempDir,
784
+ listenOnRandomPort: listenOnRandomPort,
785
+ makeFakeOtelApi: makeFakeOtelApi,
786
+ // Captures
787
+ captureAudit: captureAudit,
788
+ captureObservability: captureObservability,
789
+ captureMetricsTap: captureMetricsTap,
790
+ // Async test helpers
791
+ runMiddleware: runMiddleware,
792
+ waitFor: waitFor,
793
+ // Chainable HTTP request helper (supertest-style)
794
+ request: request,
795
+ // Class + constants
796
+ TestingError: TestingError,
797
+ DEFAULTS: DEFAULTS,
798
+ };