@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
@@ -0,0 +1,350 @@
1
+ "use strict";
2
+ /**
3
+ * Async handler primitive — buffered emit + resilient drain.
4
+ *
5
+ * The framework has many "fire something off, don't block the request"
6
+ * surfaces: audit emissions from middleware/log-stream/external-db
7
+ * hooks, webhook deliveries, log lines being shipped to an external
8
+ * sink. Without a shared primitive, each surface tends toward a
9
+ * fire-and-forget Promise pattern, which has well-known failure modes:
10
+ *
11
+ * - Errors disappear silently
12
+ * - Promises leak across test/shutdown boundaries
13
+ * - In cyclic dispatchers (storage emits about its own writes), the
14
+ * pattern is the only thing preventing infinite recursion, but at
15
+ * the cost of introducing a race
16
+ * - "Did the work complete?" is unanswerable
17
+ *
18
+ * AsyncHandler replaces the pattern with a uniform contract that bakes
19
+ * resilience in by default — operators don't opt in to robustness; it
20
+ * is the framework's posture and surfaces only what the operator
21
+ * actively configures (DLQ destination, retry policy adjustments, etc).
22
+ *
23
+ * Public API:
24
+ *
25
+ * handler.emit(item) sync; buffers; never throws (errors go
26
+ * to onError); never returns a Promise
27
+ * handler.drain(opts?) async; flushes buffer to storage with
28
+ * retry + circuit breaker + DLQ;
29
+ * resolves when current backlog is done
30
+ * or breaker is open. opts.signal aborts.
31
+ * handler.shutdown(opts?) async; final drain with timeout (default
32
+ * 30s); subsequent emit() drops with
33
+ * onError notification
34
+ * handler.getStats() snapshot of operational metrics
35
+ *
36
+ * Resilience layers (all on by default):
37
+ *
38
+ * Retry — batches that fail flush() are retried with exponential
39
+ * backoff + jitter (safeAsync.asyncRetry). Default 3 attempts.
40
+ * Transient external-db hiccups recover automatically.
41
+ *
42
+ * Circuit breaker — if `failureThreshold` consecutive batches fail
43
+ * after retry exhaustion, the breaker OPENS. Subsequent
44
+ * emit() calls fast-fail (item goes to DLQ via onError);
45
+ * drain() returns immediately with a CIRCUIT_OPEN reason.
46
+ * After `cooldownMs` the breaker enters HALF_OPEN and one
47
+ * probe batch is allowed; success closes it, failure
48
+ * re-opens with another cooldown. Bounded recovery.
49
+ *
50
+ * Dead-letter queue — items that fail every retry land in DLQ via
51
+ * the operator-supplied `deadLetter(items, error)` callback.
52
+ * If no DLQ is configured, items go to onError with a
53
+ * handler/dropped error. The DLQ is fire-and-forget from
54
+ * the handler's perspective — the operator can write to a
55
+ * file, an external queue, an audit row, anywhere durable.
56
+ *
57
+ * Backpressure — buffer capped at `maxBufferSize` (default 10000);
58
+ * emit() over the cap goes to onError + DLQ. Operators
59
+ * sizing for high-throughput audit emit larger; default is
60
+ * sized for "audit emissions piggyback on request handling."
61
+ *
62
+ * AbortSignal — drain(opts?) accepts opts.signal; aborting cancels
63
+ * the in-flight drain (current batch finishes; remaining
64
+ * items stay in buffer for next drain).
65
+ *
66
+ * Bounded shutdown — shutdown(opts?) drains with a timeout (default
67
+ * 30s). Items that don't flush in time go to DLQ or
68
+ * onError; the call resolves so process exit isn't blocked.
69
+ *
70
+ * Recursion safety: when a handler is flushing, downstream code MAY
71
+ * emit MORE items into the same handler (e.g. audit.flush writes to
72
+ * external-db, which would normally audit-emit). Those additional
73
+ * items land in the buffer for the NEXT cycle (NOT the current batch),
74
+ * keeping batch sizes bounded. The flush function can mark its own
75
+ * writes with a sentinel (e.g. `{ skipAudit: true }`) so downstream
76
+ * emitters know to skip — caller-controlled, not handler concern.
77
+ *
78
+ * Metrics (handler.getStats()):
79
+ * bufferSize, totalEmitted, totalFlushed, totalRetried,
80
+ * totalDeadLettered, lastFlushDurationMs, breakerState.
81
+ * Operators wire these to their monitoring; the handler does not
82
+ * ship metrics anywhere on its own.
83
+ */
84
+
85
+ var safeAsync = require("./safe-async");
86
+ var C = require("./constants");
87
+ var validateOpts = require("./validate-opts");
88
+ var { HandlerError } = require("./framework-error");
89
+ var { boot } = require("./log");
90
+
91
+ var DEFAULTS = {
92
+ maxBatch: 100,
93
+ maxAgeMs: C.TIME.seconds(1),
94
+ maxBufferSize: 10000,
95
+ shutdownTimeoutMs: C.TIME.seconds(30),
96
+ retry: {
97
+ maxAttempts: 3,
98
+ baseDelayMs: 100,
99
+ maxDelayMs: C.TIME.seconds(5),
100
+ jitterFactor: 0.5,
101
+ },
102
+ breaker: {
103
+ failureThreshold: 5,
104
+ cooldownMs: C.TIME.seconds(30),
105
+ successThreshold: 1,
106
+ },
107
+ };
108
+
109
+ var _err = HandlerError.factory;
110
+
111
+ function create(opts) {
112
+ opts = opts || {};
113
+ validateOpts(opts, [
114
+ "name", "flush",
115
+ "maxBatch", "maxAgeMs", "maxBufferSize", "shutdownTimeoutMs",
116
+ "retry", "breaker",
117
+ "deadLetter", "onError",
118
+ ], "b.handlers");
119
+ if (typeof opts.flush !== "function") {
120
+ throw _err("handlers/invalid", "create requires { flush } async function");
121
+ }
122
+
123
+ var name = opts.name || "anonymous";
124
+ var flush = opts.flush;
125
+ var maxBatch = (opts.maxBatch != null) ? opts.maxBatch : DEFAULTS.maxBatch;
126
+ var maxAgeMs = (opts.maxAgeMs != null) ? opts.maxAgeMs : DEFAULTS.maxAgeMs;
127
+ var maxBufferSize = (opts.maxBufferSize != null) ? opts.maxBufferSize : DEFAULTS.maxBufferSize;
128
+ var shutdownTimeoutMs = (opts.shutdownTimeoutMs != null) ? opts.shutdownTimeoutMs : DEFAULTS.shutdownTimeoutMs;
129
+ // Handler retry: any thrown error from operator-supplied flush() is
130
+ // retried until exhaustion. The default isRetryable classifier is
131
+ // network-shaped and would skip generic Errors; override to retry-
132
+ // anything since flush failures are caller-defined, not network errors.
133
+ var retryConfig = Object.assign(
134
+ { isRetryable: function () { return true; } },
135
+ DEFAULTS.retry,
136
+ opts.retry || {}
137
+ );
138
+ var breakerConfig = Object.assign({}, DEFAULTS.breaker, opts.breaker || {});
139
+ var deadLetter = (typeof opts.deadLetter === "function") ? opts.deadLetter : null;
140
+ var handlerLog = boot("handlers/" + name);
141
+ var onError = (typeof opts.onError === "function") ? opts.onError : function (err) {
142
+ handlerLog.error(err && err.message ? err.message : String(err));
143
+ };
144
+
145
+ // Buffer + drain coordination.
146
+ var _buffer = [];
147
+ var _drainPromise = null;
148
+ var _ageTimer = null;
149
+ var _oldestEnqueueAt = null;
150
+ var _shutdown = false;
151
+ var _drainMutex = new safeAsync.Mutex();
152
+ var _breaker = new safeAsync.CircuitBreaker("handler:" + name, breakerConfig);
153
+
154
+ // Metrics.
155
+ var _totalEmitted = 0;
156
+ var _totalFlushed = 0;
157
+ var _totalRetried = 0;
158
+ var _totalDeadLettered = 0;
159
+ var _lastFlushDurationMs = 0;
160
+
161
+ function _scheduleAgeFlush() {
162
+ if (_ageTimer) return;
163
+ _ageTimer = setTimeout(function () {
164
+ _ageTimer = null;
165
+ drain().catch(function (e) { onError(e, []); });
166
+ }, maxAgeMs);
167
+ if (typeof _ageTimer.unref === "function") _ageTimer.unref();
168
+ }
169
+
170
+ function _cancelAgeFlush() {
171
+ if (_ageTimer) { clearTimeout(_ageTimer); _ageTimer = null; }
172
+ }
173
+
174
+ function _toDeadLetter(items, err) {
175
+ _totalDeadLettered += items.length;
176
+ if (deadLetter) {
177
+ try { deadLetter(items, err); }
178
+ catch (dlqErr) { onError(_err("handlers/dlq-failed",
179
+ "DLQ callback for handler '" + name + "' threw", dlqErr), items); }
180
+ } else {
181
+ onError(_err("handlers/dropped",
182
+ items.length + " item(s) dropped from handler '" + name + "' after retry exhaustion: " +
183
+ (err && err.message ? err.message : String(err)), err), items);
184
+ }
185
+ }
186
+
187
+ function emit(item) {
188
+ if (_shutdown) {
189
+ onError(_err("handlers/shutdown",
190
+ "emit on shut-down handler '" + name + "' — item dropped"), [item]);
191
+ _toDeadLetter([item], _err("handlers/shutdown", "handler is shutting down"));
192
+ return;
193
+ }
194
+ if (_buffer.length >= maxBufferSize) {
195
+ var dropErr = _err("handlers/buffer-full",
196
+ "buffer for handler '" + name + "' exceeded maxBufferSize=" +
197
+ maxBufferSize + " — flush is too slow / failing");
198
+ onError(dropErr, [item]);
199
+ _toDeadLetter([item], dropErr);
200
+ return;
201
+ }
202
+ _totalEmitted += 1;
203
+ _buffer.push(item);
204
+ if (_oldestEnqueueAt === null) _oldestEnqueueAt = Date.now();
205
+
206
+ if (_buffer.length >= maxBatch) {
207
+ _cancelAgeFlush();
208
+ drain().catch(function (e) { onError(e, []); });
209
+ } else {
210
+ _scheduleAgeFlush();
211
+ }
212
+ }
213
+
214
+ // Drain the buffer with retry + breaker + DLQ. Items emitted DURING
215
+ // a drain land in the buffer for the NEXT drain cycle (NOT the
216
+ // current call) — see the recursion-safety note in this module's
217
+ // header. Without this bound, a handler whose flush() emits MORE
218
+ // items into the same handler (cluster-mode audit: writing an
219
+ // audit row goes through externalDb.query, which emits a
220
+ // system.externaldb.query audit event back into the buffer)
221
+ // produces an unbounded loop where the buffer refills as fast as
222
+ // it drains.
223
+ //
224
+ // Implementation: snapshot _buffer.length at start; process exactly
225
+ // that many items (in batches of maxBatch). Items emitted during
226
+ // the drain accrue at the tail of _buffer and are visible to the
227
+ // next drain() call. Concurrent drain() calls share the in-flight
228
+ // Promise.
229
+ function drain(drainOpts) {
230
+ if (_drainPromise) return _drainPromise;
231
+ drainOpts = drainOpts || {};
232
+ var signal = drainOpts.signal || null;
233
+
234
+ _drainPromise = _drainMutex.runExclusive(async function () {
235
+ _cancelAgeFlush();
236
+ var remaining = _buffer.length;
237
+ while (remaining > 0) {
238
+ if (signal && signal.aborted) break;
239
+ var take = Math.min(maxBatch, remaining);
240
+ var batch = _buffer.splice(0, take);
241
+ remaining -= batch.length;
242
+ _oldestEnqueueAt = _buffer.length > 0 ? Date.now() : null;
243
+
244
+ var t0 = Date.now();
245
+ try {
246
+ await _breaker.wrap(async function () {
247
+ // Retry the entire batch on transient failures. Each retry
248
+ // re-enters the operator's flush() with the same items; the
249
+ // operator's flush() should be idempotent within a batch
250
+ // (or accept the duplicate-write trade-off).
251
+ //
252
+ // The operator flush() receives an isShutdown() probe in its
253
+ // second arg so it can early-exit between items if the
254
+ // handler was shut down mid-batch (e.g. by a test reset).
255
+ // Without that check, an in-flight flush keeps processing
256
+ // batch[i++] items even after shutdown — and audit's
257
+ // flush in particular writes those into whatever database
258
+ // is currently bound, leaking rows into the next test's db.
259
+ var attempts = 0;
260
+ await safeAsync.asyncRetry(async function () {
261
+ if (attempts > 0) _totalRetried += 1;
262
+ attempts += 1;
263
+ await flush(batch, { isShutdown: function () { return _shutdown; } });
264
+ }, retryConfig);
265
+ });
266
+ _totalFlushed += batch.length;
267
+ } catch (e) {
268
+ // Retry exhausted OR breaker open. Items go to DLQ; loop
269
+ // continues so other batches still attempt — unless the
270
+ // breaker is open, in which case the next iteration's
271
+ // _breaker.wrap will fail-fast immediately.
272
+ _toDeadLetter(batch, e);
273
+ if (e && e.code === "CIRCUIT_OPEN") {
274
+ // Stop the drain; remaining buffered items will be tried
275
+ // again on the next emit() / drain() call.
276
+ break;
277
+ }
278
+ }
279
+ _lastFlushDurationMs = Date.now() - t0;
280
+ }
281
+ }).then(function (v) { _drainPromise = null; return v; },
282
+ function (e) { _drainPromise = null; throw e; });
283
+ return _drainPromise;
284
+ }
285
+
286
+ async function shutdown(shutdownOpts) {
287
+ shutdownOpts = shutdownOpts || {};
288
+ var timeoutMs = (shutdownOpts.timeoutMs != null) ? shutdownOpts.timeoutMs : shutdownTimeoutMs;
289
+ _shutdown = true;
290
+ _cancelAgeFlush();
291
+ try {
292
+ await safeAsync.withTimeout(drain(), timeoutMs, { name: "handler:" + name + ".shutdown" });
293
+ } catch (e) {
294
+ // Timeout or breaker fail — DLQ whatever's left, then return.
295
+ var leftover = _buffer.splice(0);
296
+ if (leftover.length > 0) {
297
+ _toDeadLetter(leftover, e);
298
+ }
299
+ }
300
+ }
301
+
302
+ // Synchronous "stop and drop" — for test resets and other cases
303
+ // where draining buffered items would write to a stale or changing
304
+ // backing store. Sets the shutdown flag, cancels the age timer, and
305
+ // drops every buffered item to the DLQ. After this returns, no
306
+ // setTimeout from this handler can fire and emit() drops every
307
+ // future item with handlers/shutdown.
308
+ function shutdownSync(reason) {
309
+ _shutdown = true;
310
+ _cancelAgeFlush();
311
+ var dropped = _buffer.splice(0);
312
+ if (dropped.length > 0) {
313
+ _toDeadLetter(
314
+ dropped,
315
+ _err("handlers/shutdown-drop",
316
+ "handler '" + name + "' shut down with " + dropped.length +
317
+ " buffered item(s); items dropped: " + (reason || "no-drain shutdown"))
318
+ );
319
+ }
320
+ }
321
+
322
+ function getStats() {
323
+ return {
324
+ bufferSize: _buffer.length,
325
+ totalEmitted: _totalEmitted,
326
+ totalFlushed: _totalFlushed,
327
+ totalRetried: _totalRetried,
328
+ totalDeadLettered: _totalDeadLettered,
329
+ lastFlushDurationMs: _lastFlushDurationMs,
330
+ breakerState: _breaker.getState ? _breaker.getState() : null,
331
+ isShutdown: _shutdown,
332
+ };
333
+ }
334
+
335
+ function size() { return _buffer.length; }
336
+
337
+ return {
338
+ name: name,
339
+ emit: emit,
340
+ drain: drain,
341
+ shutdown: shutdown,
342
+ shutdownSync: shutdownSync,
343
+ getStats: getStats,
344
+ size: size,
345
+ };
346
+ }
347
+
348
+ module.exports = {
349
+ create: create,
350
+ };
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ /**
3
+ * html-balance — minimal HTML structural sanity check.
4
+ *
5
+ * Scans an HTML fragment looking for unbalanced container tags
6
+ * (unclosed `<div>`, mismatched `<table>`/`</tr>`, etc.). Returns
7
+ * `null` when balanced; an object `{ code, message, line, column }`
8
+ * when not. The intent is operator-side feedback at save time —
9
+ * "you forgot to close this tag" — not security validation.
10
+ *
11
+ * What this catches:
12
+ * - container tag opened but never closed at the same nesting depth
13
+ * - close tag with no matching open
14
+ * - close tag mismatched with the most recent open tag
15
+ * - unterminated comment `<!-- ... ` (no `-->`)
16
+ *
17
+ * What this does NOT catch:
18
+ * - bad attribute syntax (browsers are tolerant)
19
+ * - unknown tag names (custom elements / shadow DOM)
20
+ * - script content (skipped between `<script>` / `</script>`)
21
+ * - style content (skipped between `<style>` / `</style>`)
22
+ * - XSS or sanitization concerns — that's a separate primitive
23
+ *
24
+ * Usage:
25
+ *
26
+ * var problem = b.htmlBalance.check(operatorSubmittedHtml);
27
+ * if (problem) return res.status(400).render({ error: problem.message });
28
+ */
29
+
30
+ // Tags that are NEVER closed (HTML5 void elements).
31
+ var VOID_TAGS = Object.freeze({
32
+ area: 1, base: 1, br: 1, col: 1, embed: 1, hr: 1, img: 1, input: 1,
33
+ link: 1, meta: 1, param: 1, source: 1, track: 1, wbr: 1,
34
+ });
35
+
36
+ // Tags whose content is treated as raw text (skipped by this checker).
37
+ var RAW_TEXT_TAGS = Object.freeze({ script: 1, style: 1, textarea: 1, title: 1 });
38
+
39
+ function _posToLineColumn(src, pos) {
40
+ var line = 1, col = 1;
41
+ for (var i = 0; i < pos && i < src.length; i++) {
42
+ if (src.charCodeAt(i) === 10) { line++; col = 1; }
43
+ else col++;
44
+ }
45
+ return { line: line, column: col };
46
+ }
47
+
48
+ function check(html) {
49
+ if (typeof html !== "string" || html.length === 0) return null;
50
+ var stack = []; // [{ tag, openPos }]
51
+ var i = 0;
52
+ var len = html.length;
53
+
54
+ while (i < len) {
55
+ // Comment skip: <!-- ... -->
56
+ if (html.charCodeAt(i) === 0x3C /* < */ &&
57
+ html.charCodeAt(i + 1) === 0x21 /* ! */ &&
58
+ html.charCodeAt(i + 2) === 0x2D &&
59
+ html.charCodeAt(i + 3) === 0x2D) {
60
+ var endComment = html.indexOf("-->", i + 4);
61
+ if (endComment === -1) {
62
+ var pos = _posToLineColumn(html, i);
63
+ return {
64
+ code: "html/unterminated-comment",
65
+ message: "unterminated <!-- comment (no closing -->) at line " +
66
+ pos.line + " col " + pos.column,
67
+ line: pos.line,
68
+ column: pos.column,
69
+ };
70
+ }
71
+ i = endComment + 3;
72
+ continue;
73
+ }
74
+
75
+ // CDATA / doctype / processing-instructions are passed over.
76
+ if (html.charCodeAt(i) === 0x3C /* < */ &&
77
+ html.charCodeAt(i + 1) === 0x21 /* ! */) {
78
+ var gt = html.indexOf(">", i);
79
+ if (gt === -1) break;
80
+ i = gt + 1;
81
+ continue;
82
+ }
83
+
84
+ // Tag scan: `<` starts an element open or close.
85
+ if (html.charCodeAt(i) === 0x3C /* < */) {
86
+ var isClose = html.charCodeAt(i + 1) === 0x2F /* / */;
87
+ var nameStart = i + (isClose ? 2 : 1);
88
+ // Tag name: ASCII letters, digits, hyphen.
89
+ var nameEnd = nameStart;
90
+ while (nameEnd < len) {
91
+ var c = html.charCodeAt(nameEnd);
92
+ if ((c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A) ||
93
+ (c >= 0x30 && c <= 0x39) || c === 0x2D /* - */) nameEnd++;
94
+ else break;
95
+ }
96
+ if (nameEnd === nameStart) {
97
+ // Looks like a stray `<` not starting a tag — skip past it.
98
+ i++;
99
+ continue;
100
+ }
101
+ var tag = html.slice(nameStart, nameEnd).toLowerCase();
102
+ // Find the matching `>` for this tag (skip over quoted attribute values).
103
+ var j = nameEnd;
104
+ var inQuote = 0;
105
+ while (j < len) {
106
+ var ch = html.charCodeAt(j);
107
+ if (inQuote) {
108
+ if (ch === inQuote) inQuote = 0;
109
+ } else if (ch === 0x22 /* " */ || ch === 0x27 /* ' */) {
110
+ inQuote = ch;
111
+ } else if (ch === 0x3E /* > */) {
112
+ break;
113
+ }
114
+ j++;
115
+ }
116
+ if (j >= len) {
117
+ var p = _posToLineColumn(html, i);
118
+ return {
119
+ code: "html/unterminated-tag",
120
+ message: "unterminated tag '<" + (isClose ? "/" : "") + tag +
121
+ "' (no closing >) at line " + p.line + " col " + p.column,
122
+ line: p.line,
123
+ column: p.column,
124
+ };
125
+ }
126
+ // Self-closing: `<foo />` or `<foo/>` or HTML5 void elements.
127
+ var selfClose = html.charCodeAt(j - 1) === 0x2F /* / */;
128
+ if (isClose) {
129
+ if (VOID_TAGS[tag]) {
130
+ // Stray closer for a void tag — surface as error.
131
+ var pcv = _posToLineColumn(html, i);
132
+ return {
133
+ code: "html/void-close",
134
+ message: "closing tag </" + tag + "> for a void element at line " +
135
+ pcv.line + " col " + pcv.column,
136
+ line: pcv.line,
137
+ column: pcv.column,
138
+ };
139
+ }
140
+ var top = stack[stack.length - 1];
141
+ if (!top) {
142
+ var pco = _posToLineColumn(html, i);
143
+ return {
144
+ code: "html/orphan-close",
145
+ message: "</" + tag + "> with no matching open tag at line " +
146
+ pco.line + " col " + pco.column,
147
+ line: pco.line,
148
+ column: pco.column,
149
+ };
150
+ }
151
+ if (top.tag !== tag) {
152
+ var pcm = _posToLineColumn(html, i);
153
+ var pop = _posToLineColumn(html, top.openPos);
154
+ return {
155
+ code: "html/mismatched-close",
156
+ message: "</" + tag + "> at line " + pcm.line + " col " + pcm.column +
157
+ " does not match open <" + top.tag + "> at line " + pop.line +
158
+ " col " + pop.column,
159
+ line: pcm.line,
160
+ column: pcm.column,
161
+ };
162
+ }
163
+ stack.pop();
164
+ } else {
165
+ // Open tag (or self-closing).
166
+ if (selfClose || VOID_TAGS[tag]) {
167
+ // No push.
168
+ } else if (RAW_TEXT_TAGS[tag]) {
169
+ // Skip raw-text content AND its closing tag entirely. Inside
170
+ // <script>/<style>/<textarea>/<title> the `<` characters are
171
+ // text, not markup — re-entering the tag scanner on
172
+ // `</script>` would otherwise treat it as an orphan close.
173
+ var rawClose = "</" + tag;
174
+ var found = -1;
175
+ var search = j + 1;
176
+ var lower = html.toLowerCase();
177
+ while (search < len) {
178
+ var idx = lower.indexOf(rawClose, search);
179
+ if (idx === -1) break;
180
+ var afterIdx = idx + rawClose.length;
181
+ var ac = html.charCodeAt(afterIdx);
182
+ if (afterIdx >= len || ac === 0x3E || ac <= 0x20) {
183
+ found = idx;
184
+ break;
185
+ }
186
+ search = idx + 1;
187
+ }
188
+ if (found === -1) {
189
+ var pcr = _posToLineColumn(html, i);
190
+ return {
191
+ code: "html/unclosed-raw-text",
192
+ message: "unclosed <" + tag + "> raw-text element at line " +
193
+ pcr.line + " col " + pcr.column,
194
+ line: pcr.line,
195
+ column: pcr.column,
196
+ };
197
+ }
198
+ // Advance past the closing `>` of the close tag.
199
+ var closeGt = html.indexOf(">", found);
200
+ if (closeGt === -1) closeGt = len - 1;
201
+ i = closeGt + 1;
202
+ continue;
203
+ } else {
204
+ stack.push({ tag: tag, openPos: i });
205
+ }
206
+ }
207
+ i = j + 1;
208
+ continue;
209
+ }
210
+ i++;
211
+ }
212
+
213
+ if (stack.length > 0) {
214
+ var leftover = stack[stack.length - 1];
215
+ var pl = _posToLineColumn(html, leftover.openPos);
216
+ return {
217
+ code: "html/unclosed-tag",
218
+ message: "unclosed <" + leftover.tag + "> at line " + pl.line +
219
+ " col " + pl.column + " (no matching </" + leftover.tag + ">)",
220
+ line: pl.line,
221
+ column: pl.column,
222
+ };
223
+ }
224
+ return null;
225
+ }
226
+
227
+ module.exports = { check: check };