@blamejs/core 0.4.1

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 (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
package/lib/testing.js ADDED
@@ -0,0 +1,621 @@
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
+ var os = require("node:os");
64
+ var nodePath = require("node:path");
65
+ var EventEmitter = require("node:events").EventEmitter;
66
+ var lazyRequire = require("./lazy-require");
67
+ var safeAsync = require("./safe-async");
68
+ var { TestingError } = require("./framework-error");
69
+
70
+ // Lazy-required to avoid load-order cycles with the metrics module.
71
+ // metrics is the only place that exposes the global `tap` slot the
72
+ // captureMetricsTap helper swaps; pulling it lazily keeps testing.js
73
+ // safe to require at any framework load order.
74
+ var metricsModule = lazyRequire(function () { return require("./metrics"); });
75
+
76
+ var _err = TestingError.factory;
77
+
78
+ var DEFAULTS = Object.freeze({
79
+ waitForTimeoutMs: 1000,
80
+ waitForIntervalMs: 10,
81
+ runMiddlewareTimeoutMs: 5000,
82
+ });
83
+
84
+ // ---- Tier-A helpers ----
85
+
86
+ function _isPositiveInt(n) {
87
+ return typeof n === "number" && isFinite(n) && n >= 1 && Math.floor(n) === n;
88
+ }
89
+
90
+ function _isFiniteNonNegative(n) {
91
+ return typeof n === "number" && isFinite(n) && n >= 0;
92
+ }
93
+
94
+ // ---- HTTP mocks (standalone — no framework primitive overlap) ----
95
+ // These mimic Node's `http` module's request/response shapes. They're
96
+ // the surface every framework primitive's middleware tests use.
97
+
98
+ function mockReq(opts) {
99
+ opts = opts || {};
100
+ var headers = Object.assign({}, opts.headers || {});
101
+ // Compatible with b.requestHelpers.extractActorContext: that function
102
+ // reads `headers["user-agent"]`, `headers["x-request-id"]`, `socket
103
+ // .remoteAddress`, `connection.remoteAddress`, `method`, `url`,
104
+ // `requestId`, `session.id`, `user.id`. mockReq populates every
105
+ // field that has a sensible default so extractActorContext doesn't
106
+ // see undefined when operators pass mockReq() with minimal opts.
107
+ if (opts.userAgent && !headers["user-agent"]) headers["user-agent"] = opts.userAgent;
108
+ if (opts.requestId && !headers["x-request-id"]) headers["x-request-id"] = opts.requestId;
109
+ return {
110
+ method: opts.method || "GET",
111
+ url: opts.url || "/",
112
+ pathname: opts.pathname || (opts.url || "/").split("?")[0],
113
+ headers: headers,
114
+ socket: opts.socket || { remoteAddress: opts.ip || "127.0.0.1" },
115
+ connection: opts.connection || { remoteAddress: opts.ip || "127.0.0.1" },
116
+ };
117
+ }
118
+
119
+ function mockRes() {
120
+ var headers = {};
121
+ var statusCode = null;
122
+ var bodyParts = [];
123
+ var ended = false;
124
+ return {
125
+ statusCode: null,
126
+ writableEnded: false,
127
+ setHeader: function (k, v) { headers[k.toLowerCase()] = v; },
128
+ getHeader: function (k) { return headers[k.toLowerCase()]; },
129
+ writeHead: function (s, h) {
130
+ statusCode = s;
131
+ if (h) for (var k in h) headers[k.toLowerCase()] = h[k];
132
+ },
133
+ end: function (b) {
134
+ if (b !== undefined) bodyParts.push(b);
135
+ ended = true;
136
+ this.writableEnded = true;
137
+ },
138
+ _captured: function () {
139
+ return { status: statusCode, headers: headers, body: bodyParts.join(""), ended: ended };
140
+ },
141
+ };
142
+ }
143
+
144
+ function bodyReq(method, headers, body) {
145
+ var req = new EventEmitter();
146
+ req.method = method || "GET";
147
+ req.url = "/";
148
+ req.headers = Object.assign({}, headers || {});
149
+ req.socket = { remoteAddress: "127.0.0.1" };
150
+ req.destroy = function () { /* mock — no-op */ };
151
+ setImmediate(function () {
152
+ if (Buffer.isBuffer(body)) req.emit("data", body);
153
+ else if (typeof body === "string") req.emit("data", Buffer.from(body));
154
+ req.emit("end");
155
+ });
156
+ return req;
157
+ }
158
+
159
+ function bodyRes() {
160
+ var res = new EventEmitter();
161
+ res.statusCode = null;
162
+ res.headersSent = false;
163
+ res._captured = "";
164
+ res._endedStatus = null;
165
+ res._headers = {};
166
+ res.writeHead = function (s, h) {
167
+ res.statusCode = s;
168
+ res._endedStatus = s;
169
+ res.headersSent = true;
170
+ res._headers = h || {};
171
+ };
172
+ res.end = function (body) { if (body) res._captured += body; res.emit("finish"); };
173
+ return res;
174
+ }
175
+
176
+ function streamingRes() {
177
+ var res = new EventEmitter();
178
+ res._chunks = [];
179
+ res._headers = {};
180
+ res._statusCode = 200;
181
+ res.headersSent = false;
182
+ res.writeHead = function (status, statusMsgOrHeaders, headersIfMsg) {
183
+ res._statusCode = status;
184
+ res.headersSent = true;
185
+ var h = null;
186
+ if (headersIfMsg && typeof headersIfMsg === "object") h = headersIfMsg;
187
+ else if (statusMsgOrHeaders && typeof statusMsgOrHeaders === "object" && !Array.isArray(statusMsgOrHeaders)) {
188
+ h = statusMsgOrHeaders;
189
+ }
190
+ if (h) {
191
+ var keys = Object.keys(h);
192
+ for (var i = 0; i < keys.length; i++) res._headers[keys[i].toLowerCase()] = h[keys[i]];
193
+ }
194
+ };
195
+ res.setHeader = function (k, v) { res._headers[k.toLowerCase()] = v; };
196
+ res.getHeader = function (k) { return res._headers[k.toLowerCase()]; };
197
+ res.removeHeader = function (k) { delete res._headers[k.toLowerCase()]; };
198
+ res.write = function (chunk) {
199
+ if (Buffer.isBuffer(chunk)) res._chunks.push(chunk);
200
+ else if (typeof chunk === "string") res._chunks.push(Buffer.from(chunk));
201
+ return true;
202
+ };
203
+ res.end = function (chunk) {
204
+ if (chunk != null) res.write(chunk);
205
+ res.emit("finish");
206
+ return res;
207
+ };
208
+ res._captured = function () { return Buffer.concat(res._chunks); };
209
+ return res;
210
+ }
211
+
212
+ // ---- fakeClock ----
213
+ //
214
+ // No framework primitive owns "controllable clock"; this IS that
215
+ // primitive now. The shape is `{ now, advance, set, ms }` so operators
216
+ // can pass `clk.now` as the `clock` opt to b.cache / b.api-key /
217
+ // b.permissions / b.scheduler / b.seeders / etc.
218
+
219
+ function fakeClock(initialMs) {
220
+ if (initialMs === undefined) initialMs = 1_000_000; // arbitrary positive default
221
+ if (typeof initialMs !== "number" || !isFinite(initialMs)) {
222
+ throw _err("BAD_INPUT", "fakeClock: initialMs must be a finite number, got " +
223
+ (typeof initialMs) + " " + JSON.stringify(initialMs));
224
+ }
225
+ var current = initialMs;
226
+ // Bound `now` so operators pass `clk.now` directly without losing `this`.
227
+ function now() { return current; }
228
+ function advance(ms) {
229
+ if (typeof ms !== "number" || !isFinite(ms)) {
230
+ throw _err("BAD_INPUT", "fakeClock.advance: ms must be a finite number");
231
+ }
232
+ current += ms;
233
+ }
234
+ function set(ms) {
235
+ if (typeof ms !== "number" || !isFinite(ms)) {
236
+ throw _err("BAD_INPUT", "fakeClock.set: ms must be a finite number");
237
+ }
238
+ current = ms;
239
+ }
240
+ return {
241
+ now: now,
242
+ advance: advance,
243
+ set: set,
244
+ get ms() { return current; },
245
+ };
246
+ }
247
+
248
+ // ---- fakeHttpClient ----
249
+ //
250
+ // Drop-in replacement for b.httpClient. responder(req) returns the
251
+ // canned response object — sync OR async. `calls` is the captured
252
+ // request array.
253
+
254
+ function fakeHttpClient(responder) {
255
+ if (typeof responder !== "function") {
256
+ throw _err("BAD_INPUT", "fakeHttpClient: responder must be a function");
257
+ }
258
+ var calls = [];
259
+ return {
260
+ calls: calls,
261
+ request: function (req) {
262
+ calls.push(req);
263
+ return Promise.resolve(responder(req));
264
+ },
265
+ };
266
+ }
267
+
268
+ // ---- captureAudit ----
269
+ //
270
+ // Matches b.audit.safeEmit Tier-B drop-silent contract. captured holds
271
+ // every event pushed; clear() empties; byAction(name) filters.
272
+
273
+ function captureAudit() {
274
+ var captured = [];
275
+ return {
276
+ captured: captured,
277
+ safeEmit: function (event) {
278
+ // Tier B: drop-silent on caller-side bugs that throw inside the
279
+ // capture push (shouldn't happen with array.push, but matches the
280
+ // real safeEmit's defensive shape).
281
+ try { captured.push(event); }
282
+ catch (_e) { /* drop-silent */ }
283
+ },
284
+ clear: function () { captured.length = 0; },
285
+ byAction: function (action) {
286
+ return captured.filter(function (e) { return e && e.action === action; });
287
+ },
288
+ };
289
+ }
290
+
291
+ // ---- captureObservability ----
292
+ //
293
+ // Matches b.observability.tap + b.observability.event contracts. tap
294
+ // invokes fn synchronously (passes `null` as the span — no tracer
295
+ // active under capture) and returns fn's return value, sync OR promise.
296
+ // Both sides are captured.
297
+
298
+ function captureObservability() {
299
+ var captured = [];
300
+ function event(name, value, labels) {
301
+ if (typeof name !== "string" || name.length === 0) return; // drop-silent
302
+ captured.push({ kind: "event", name: name, value: value, labels: labels || {} });
303
+ }
304
+ function tap(name, attrs, fn) {
305
+ if (typeof attrs === "function") { fn = attrs; attrs = null; }
306
+ if (typeof name !== "string" || name.length === 0) {
307
+ throw new TypeError("captureObservability.tap: name must be a non-empty string");
308
+ }
309
+ if (typeof fn !== "function") {
310
+ throw new TypeError("captureObservability.tap: fn must be a function");
311
+ }
312
+ captured.push({ kind: "tap", name: name, attrs: attrs || {} });
313
+ var ret;
314
+ try { ret = fn(null); }
315
+ catch (e) {
316
+ captured.push({ kind: "tap.error", name: name, error: e });
317
+ throw e;
318
+ }
319
+ if (ret && typeof ret.then === "function") {
320
+ return ret.then(
321
+ function (v) { captured.push({ kind: "tap.end", name: name }); return v; },
322
+ function (e) { captured.push({ kind: "tap.error", name: name, error: e }); throw e; }
323
+ );
324
+ }
325
+ captured.push({ kind: "tap.end", name: name });
326
+ return ret;
327
+ }
328
+ return {
329
+ captured: captured,
330
+ event: event,
331
+ tap: tap,
332
+ clear: function () { captured.length = 0; },
333
+ byName: function (name) {
334
+ return captured.filter(function (e) { return e && e.name === name; });
335
+ },
336
+ };
337
+ }
338
+
339
+ // ---- captureMetricsTap ----
340
+ //
341
+ // Swaps b.metrics.tap with a capturing function. Operator calls
342
+ // .restore() in finally to revert. This is the existing framework-
343
+ // test pattern (used by cache.test.js, i18n.test.js, notify.test.js,
344
+ // observability.test.js, …) — codified here so the swap+restore
345
+ // sequence is no longer copy-pasted.
346
+
347
+ function captureMetricsTap() {
348
+ var m = metricsModule();
349
+ var original = m.tap;
350
+ var captured = [];
351
+ m.tap = function (name, value, labels) {
352
+ captured.push({ name: name, value: value, labels: labels || {} });
353
+ };
354
+ return {
355
+ captured: captured,
356
+ restore: function () { m.tap = original; },
357
+ clear: function () { captured.length = 0; },
358
+ byName: function (name) {
359
+ return captured.filter(function (e) { return e && e.name === name; });
360
+ },
361
+ };
362
+ }
363
+
364
+ // ---- runMiddleware ----
365
+ //
366
+ // Runs a 3-arg (req, res, next) middleware to either next() OR res.end()
367
+ // completion. b.safeAsync.withTimeout caps the wait so a buggy
368
+ // middleware that never settles fails the test fast.
369
+
370
+ async function runMiddleware(middleware, req, res, opts) {
371
+ if (typeof middleware !== "function") {
372
+ throw _err("BAD_INPUT", "runMiddleware: middleware must be a 3-arg (req, res, next) function");
373
+ }
374
+ opts = opts || {};
375
+ req = req || mockReq();
376
+ res = res || mockRes();
377
+ var timeoutMs = (opts.timeoutMs === undefined) ? DEFAULTS.runMiddlewareTimeoutMs : opts.timeoutMs;
378
+ if (timeoutMs !== 0 && !_isFiniteNonNegative(timeoutMs)) {
379
+ throw _err("BAD_INPUT", "runMiddleware: timeoutMs must be a non-negative finite number (0 disables)");
380
+ }
381
+
382
+ var run = new Promise(function (resolve) {
383
+ var settled = false;
384
+ function _settle(outcome) {
385
+ if (settled) return;
386
+ settled = true;
387
+ resolve(outcome);
388
+ }
389
+
390
+ // Wrap end() so we can detect middleware that responds without next.
391
+ var origEnd = res.end ? res.end.bind(res) : null;
392
+ if (origEnd) {
393
+ res.end = function () {
394
+ var ret = origEnd.apply(res, arguments);
395
+ _settle({ nextCalled: false, nextError: null, req: req, res: res, ended: true });
396
+ return ret;
397
+ };
398
+ }
399
+
400
+ function next(err) {
401
+ _settle({ nextCalled: true, nextError: err || null, req: req, res: res, ended: false });
402
+ }
403
+
404
+ try {
405
+ var maybePromise = middleware(req, res, next);
406
+ // If the middleware returns a promise that rejects, treat it as
407
+ // next(err). The handler primitive already does this, but we
408
+ // can't import it (circular concern); the test helper just maps
409
+ // synchronous AND rejected-promise throws onto next(err).
410
+ if (maybePromise && typeof maybePromise.then === "function") {
411
+ maybePromise.catch(function (e) {
412
+ _settle({ nextCalled: false, nextError: e, req: req, res: res, ended: false });
413
+ });
414
+ }
415
+ } catch (e) {
416
+ _settle({ nextCalled: false, nextError: e, req: req, res: res, ended: false });
417
+ }
418
+ });
419
+
420
+ if (timeoutMs > 0) {
421
+ return safeAsync.withTimeout(run, timeoutMs, { name: "runMiddleware" });
422
+ }
423
+ return run;
424
+ }
425
+
426
+ // ---- waitFor ----
427
+ //
428
+ // Polls predicate() until truthy or timeout. Uses b.safeAsync.sleep for
429
+ // the poll interval (NOT raw setTimeout) and b.safeAsync.withTimeout
430
+ // for the overall cap. Operator can pass `{ signal }` to abort.
431
+
432
+ async function waitFor(predicate, opts) {
433
+ if (typeof predicate !== "function") {
434
+ throw _err("BAD_INPUT", "waitFor: predicate must be a function returning truthy/falsy or Promise<bool>");
435
+ }
436
+ opts = opts || {};
437
+ var timeoutMs = (opts.timeoutMs === undefined) ? DEFAULTS.waitForTimeoutMs : opts.timeoutMs;
438
+ var intervalMs = (opts.intervalMs === undefined) ? DEFAULTS.waitForIntervalMs : opts.intervalMs;
439
+ if (!_isFiniteNonNegative(timeoutMs) || timeoutMs <= 0) {
440
+ throw _err("BAD_INPUT", "waitFor: timeoutMs must be a positive finite number");
441
+ }
442
+ if (!_isPositiveInt(intervalMs)) {
443
+ throw _err("BAD_INPUT", "waitFor: intervalMs must be a positive integer");
444
+ }
445
+
446
+ // Internal AbortController stops the polling loop the moment the
447
+ // timeout fires (or the operator's signal aborts). Without this, the
448
+ // loop's safeAsync.sleep timers would keep the event loop alive
449
+ // forever even after withTimeout rejected — Node would never exit.
450
+ var ac = new AbortController();
451
+ if (opts.signal) {
452
+ if (opts.signal.aborted) ac.abort();
453
+ else opts.signal.addEventListener("abort", function () { ac.abort(); }, { once: true });
454
+ }
455
+
456
+ // Polling loop runs inside withTimeout so the framework's timer-race
457
+ // semantics apply uniformly. The internal signal aborts the inner
458
+ // sleep when withTimeout rejects.
459
+ var loop = (async function () {
460
+
461
+ while (!ac.signal.aborted) {
462
+ var v = await predicate();
463
+ if (v) return v;
464
+ try { await safeAsync.sleep(intervalMs, { signal: ac.signal }); }
465
+ catch (_e) { return undefined; } // sleep aborted = loop exits cleanly
466
+ }
467
+ return undefined;
468
+
469
+ })();
470
+
471
+ try {
472
+ return await safeAsync.withTimeout(loop, timeoutMs, {
473
+ signal: opts.signal,
474
+ name: "waitFor",
475
+ });
476
+ } catch (e) {
477
+ // Always abort the loop so its sleep timers are released and the
478
+ // event loop can exit.
479
+ ac.abort();
480
+ if (e && e.code === "async/timeout") {
481
+ throw _err("TIMEOUT",
482
+ "waitFor: predicate did not become truthy within " + timeoutMs + "ms");
483
+ }
484
+ throw e;
485
+ } finally {
486
+ ac.abort(); // also clean up after success path
487
+ }
488
+ }
489
+
490
+ // ---- tempDir ----
491
+ //
492
+ // os.tmpdir()-rooted directory with cleanup(). Path-traversal-safe
493
+ // prefix (mirrors lib/static.js _resolveSafe containment). Cleanup is
494
+ // idempotent.
495
+
496
+ function tempDir(prefix) {
497
+ if (prefix === undefined || prefix === null) prefix = "blamejs-test";
498
+ if (typeof prefix !== "string" || prefix.length === 0) {
499
+ throw _err("BAD_INPUT", "tempDir: prefix must be a non-empty string");
500
+ }
501
+ // Reject path-traversal shapes — operators pass identifier-like
502
+ // strings, never path fragments.
503
+ if (prefix.indexOf("..") !== -1 || prefix.indexOf("/") !== -1 ||
504
+ prefix.indexOf("\\") !== -1 || prefix.indexOf("\0") !== -1) {
505
+ throw _err("BAD_INPUT",
506
+ "tempDir: prefix must not contain '..', '/', '\\', or null bytes; got " + JSON.stringify(prefix));
507
+ }
508
+ // Path containment check mirroring static.js _resolveSafe — verify
509
+ // the resolved tempdir is actually inside os.tmpdir() before fs.mkdir.
510
+ var root = nodePath.resolve(os.tmpdir());
511
+ var dirPath = fs.mkdtempSync(nodePath.join(root, prefix + "-"));
512
+ var resolved = nodePath.resolve(dirPath);
513
+ if (resolved !== root && !resolved.startsWith(root + nodePath.sep)) {
514
+ throw _err("BAD_STATE",
515
+ "tempDir: created path '" + resolved + "' escapes os.tmpdir() — refusing to use");
516
+ }
517
+ var cleanedUp = false;
518
+ return {
519
+ path: resolved,
520
+ cleanup: function () {
521
+ if (cleanedUp) return;
522
+ cleanedUp = true;
523
+ try { fs.rmSync(resolved, { recursive: true, force: true }); }
524
+ catch (_e) { /* best-effort on Windows locked files */ }
525
+ },
526
+ };
527
+ }
528
+
529
+ // ---- listenOnRandomPort ----
530
+ //
531
+ // Standalone — Node http.Server only, no framework primitive overlap.
532
+ // The helper IS the boilerplate.
533
+
534
+ function listenOnRandomPort(server, host) {
535
+ host = host || "127.0.0.1";
536
+ return new Promise(function (resolve, reject) {
537
+ server.once("error", reject);
538
+ server.listen(0, host, function () {
539
+ server.removeListener("error", reject);
540
+ resolve(server.address().port);
541
+ });
542
+ });
543
+ }
544
+
545
+ // ---- makeFakeOtelApi ----
546
+ //
547
+ // Standalone fake of @opentelemetry/api's minimal subset that
548
+ // b.tracing actually consumes. No framework primitive owns this.
549
+
550
+ function makeFakeOtelApi() {
551
+ var spans = [];
552
+ var activeSpan = null;
553
+ function makeSpan(name) {
554
+ return {
555
+ _name: name, _attrs: {}, _events: [], _exceptions: [], _ended: false, _status: null,
556
+ spanContext: function () {
557
+ return { traceId: "a".repeat(32), spanId: "b".repeat(16), traceFlags: 1, isRemote: false };
558
+ },
559
+ setAttribute: function (k, v) { this._attrs[k] = v; return this; },
560
+ setAttributes: function (a) { Object.assign(this._attrs, a || {}); return this; },
561
+ addEvent: function (n) { this._events.push(n); return this; },
562
+ recordException: function (e) { this._exceptions.push(e); return this; },
563
+ setStatus: function (st) { this._status = st; return this; },
564
+ updateName: function (n) { this._name = n; return this; },
565
+ end: function () { this._ended = true; if (activeSpan === this) activeSpan = null; },
566
+ };
567
+ }
568
+ return {
569
+ trace: {
570
+ getTracer: function () {
571
+ return {
572
+ startSpan: function (name, opts) {
573
+ var s = makeSpan(name);
574
+ if (opts && opts.attributes) Object.assign(s._attrs, opts.attributes);
575
+ spans.push(s);
576
+ activeSpan = s;
577
+ return s;
578
+ },
579
+ };
580
+ },
581
+ getActiveSpan: function () { return activeSpan; },
582
+ setSpan: function (_ctx, span) { return { _activeSpan: span }; },
583
+ },
584
+ context: {
585
+ active: function () { return { _stub: true }; },
586
+ with: function (ctx, fn) {
587
+ var prev = activeSpan;
588
+ if (ctx && ctx._activeSpan) activeSpan = ctx._activeSpan;
589
+ try { return fn(); } finally { activeSpan = prev; }
590
+ },
591
+ },
592
+ SpanKind: { INTERNAL: 0, SERVER: 1, CLIENT: 2, PRODUCER: 3, CONSUMER: 4 },
593
+ _spans: spans,
594
+ _activeSpan: function () { return activeSpan; },
595
+ };
596
+ }
597
+
598
+ module.exports = {
599
+ // HTTP fixtures
600
+ mockReq: mockReq,
601
+ mockRes: mockRes,
602
+ bodyReq: bodyReq,
603
+ bodyRes: bodyRes,
604
+ streamingRes: streamingRes,
605
+ // Time / network / fs fakes
606
+ fakeClock: fakeClock,
607
+ fakeHttpClient: fakeHttpClient,
608
+ tempDir: tempDir,
609
+ listenOnRandomPort: listenOnRandomPort,
610
+ makeFakeOtelApi: makeFakeOtelApi,
611
+ // Captures
612
+ captureAudit: captureAudit,
613
+ captureObservability: captureObservability,
614
+ captureMetricsTap: captureMetricsTap,
615
+ // Async test helpers
616
+ runMiddleware: runMiddleware,
617
+ waitFor: waitFor,
618
+ // Class + constants
619
+ TestingError: TestingError,
620
+ DEFAULTS: DEFAULTS,
621
+ };