@blamejs/core 0.7.18 → 0.7.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
package/lib/bundler.js CHANGED
@@ -1,441 +1,441 @@
1
- "use strict";
2
- /**
3
- * bundler — content-hashed asset pipeline + manifest, with optional
4
- * operator-supplied ESM engine for module-graph bundling, tree-shaking,
5
- * minification, and source maps.
6
- *
7
- * What this primitive does:
8
- * - Reads each named entry from disk (or runs it through an
9
- * operator-supplied engine first for module-graph builds)
10
- * - Computes a content hash (SHA3-512, first 16 hex chars)
11
- * - Writes the entry to outdir/<name>.<hash>.<ext> for cache-busting
12
- * - Emits manifest.json mapping logical name → hashed filename
13
- * - Optionally watches entries and rebuilds on change
14
- *
15
- * Engine surface (new in v0.6.44):
16
- *
17
- * var bundler = b.bundler.create({
18
- * entries: { app: "./src/app.js" },
19
- * outdir: "./public/dist",
20
- * engine: engineInstance, // optional — defaults to passthrough
21
- * });
22
- *
23
- * `engineInstance` implements:
24
- *
25
- * {
26
- * name: string, // logged on build
27
- * transform: async (entryPath, contentBuf) => {
28
- * content: Buffer | string, // post-transform output
29
- * sourceMap: string | Buffer | null, // optional .map sibling
30
- * imports?: [string], // optional — for graph-aware watch
31
- * },
32
- * }
33
- *
34
- * The default engine is `b.bundler.engine.passthrough` — reads the file
35
- * verbatim, no transform. This is what every existing `b.bundler.create`
36
- * call gets without setting `engine`.
37
- *
38
- * For ESM module-graph bundling + tree-shake + minify + sourcemaps,
39
- * operators supply esbuild themselves (devDependency or operator-side
40
- * vendored) and adapt it via:
41
- *
42
- * var esbuild = require("esbuild");
43
- * var bundler = b.bundler.create({
44
- * entries: { app: "./src/app.js" },
45
- * outdir: "./public/dist",
46
- * engine: b.bundler.engine.fromEsbuild(esbuild, {
47
- * bundle: true,
48
- * format: "esm",
49
- * target: ["chrome120", "firefox120", "safari17"],
50
- * minify: true,
51
- * sourcemap: true,
52
- * }),
53
- * });
54
- *
55
- * The framework intentionally does NOT vendor `esbuild-wasm` itself
56
- * (the wasm blob is ~10 MB — bigger than every other vendored dep
57
- * combined; it would 3-5x the @blamejs/core npm tarball for a build-
58
- * time tool most operators only need at deploy time anyway). Treating
59
- * esbuild as an operator-supplied driver follows the same pattern as
60
- * `b.externalDb` and `b.mtlsCa.create({ engine })`: the framework owns
61
- * the integration seam, the operator brings the heavy machinery.
62
- *
63
- * Out of scope (true even with the engine surface):
64
- * - A bespoke bundler bundled INSIDE the framework. The engine
65
- * surface IS the answer; operators wanting esbuild / rollup /
66
- * swc / vite wire them through it.
67
- *
68
- * Operator with no engine + multi-file ESM source: pre-concat manually
69
- * and point bundler at the result.
70
- *
71
- * Manifest format (manifest.json under outdir):
72
- * { "app": "app.4a8c2f1d9e3b7062.js", "styles": "styles.b29f1e7c.css" }
73
- *
74
- * Integrates with lib/static.js: serve `outdir` as a static directory;
75
- * lib/static.js's hashed-path detection sets long-cache headers on
76
- * files that look hashed, and integrity() reads the manifest to
77
- * generate Subresource Integrity attributes.
78
- */
79
-
80
- var path = require("path");
81
- var fs = require("fs");
82
- var crypto = require("./crypto");
83
- var atomicFile = require("./atomic-file");
84
- var logModule = require("./log");
85
- var nb = require("./numeric-bounds");
86
- var safeJson = require("./safe-json");
87
- var validateOpts = require("./validate-opts");
88
- var { defineClass } = require("./framework-error");
89
-
90
- var BundlerError = defineClass("BundlerError", { alwaysPermanent: true });
91
- var bootLog = logModule.boot("bundler");
92
-
93
- // Default content-hash length: 16 hex chars (8 bytes of SHA3-512). Long
94
- // enough that collision probability is negligible for asset cache busting,
95
- // short enough to keep generated filenames readable.
96
- var DEFAULT_HASH_LEN = 0x10;
97
- var MIN_HASH_LEN = 0x4;
98
- var MAX_HASH_LEN = 0x40;
99
- var DEFAULT_GRACE_MS = 100;
100
-
101
- function _hashContent(buf, hexLen) {
102
- // SHA3-512 → take the first hexLen hex chars. Same family as the
103
- // framework's other content fingerprints (no SHA-256 for new code).
104
- return crypto.sha3Hash(buf).slice(0, hexLen);
105
- }
106
-
107
- function _hashedName(baseName, hash, ext) {
108
- return baseName + "." + hash + ext;
109
- }
110
-
111
- // outDir mode is 0o755 (world-readable) because the bundler emits
112
- // assets a public HTTP server reads. Other framework dirs default to
113
- // 0o700 via atomicFile.ensureDir.
114
- function _ensureOutDir(p) {
115
- try { atomicFile.ensureDir(p, 0o755); }
116
- catch (e) {
117
- if (e && e.code !== "EEXIST") {
118
- throw new BundlerError("bundler/mkdir-failed",
119
- "could not create outdir '" + p + "': " + ((e && e.message) || String(e)));
120
- }
121
- }
122
- }
123
-
124
- function _validateEntries(entries) {
125
- if (!entries || typeof entries !== "object" || Array.isArray(entries)) {
126
- throw new BundlerError("bundler/no-entries",
127
- "bundler.create requires opts.entries (a { name: path } map)");
128
- }
129
- var names = Object.keys(entries);
130
- if (names.length === 0) {
131
- throw new BundlerError("bundler/no-entries",
132
- "bundler.create: opts.entries map must have at least one entry");
133
- }
134
- // Reject names with path separators or '..' so operator-supplied
135
- // logical names can't escape the outdir on write.
136
- for (var i = 0; i < names.length; i++) {
137
- var n = names[i];
138
- if (typeof n !== "string" || n.length === 0 ||
139
- /[\\/]/.test(n) || n === ".." || n === ".") {
140
- throw new BundlerError("bundler/bad-entry-name",
141
- "entry name '" + n + "' must be a non-empty string without path separators");
142
- }
143
- var p = entries[n];
144
- if (typeof p !== "string" || p.length === 0) {
145
- throw new BundlerError("bundler/bad-entry-path",
146
- "entry '" + n + "' must map to a non-empty source path");
147
- }
148
- }
149
- }
150
-
151
- // ---- Engine surface ----
152
- //
153
- // Engines transform an entry's content before the cache-busting / hash
154
- // step. The default `passthrough` engine reads the file verbatim — same
155
- // behavior every pre-v0.6.44 caller got. Operators wanting ESM
156
- // module-graph bundling supply esbuild (or any compatible tool) and
157
- // adapt it via `engine.fromEsbuild(esbuild, opts)`.
158
- var engine = {
159
- passthrough: {
160
- name: "passthrough",
161
- transform: async function (_entryPath, contentBuf) {
162
- return { content: contentBuf, sourceMap: null };
163
- },
164
- },
165
-
166
- fromEsbuild: function (esbuild, esbuildOpts) {
167
- if (!esbuild || typeof esbuild.build !== "function") {
168
- throw new BundlerError("bundler/bad-engine",
169
- "engine.fromEsbuild: pass the esbuild module (require('esbuild')); " +
170
- "got " + typeof esbuild);
171
- }
172
- var baseOpts = Object.assign({
173
- bundle: true,
174
- write: false,
175
- format: "esm",
176
- platform: "browser",
177
- logLevel: "silent",
178
- }, esbuildOpts || {});
179
- return {
180
- name: "esbuild",
181
- transform: async function (entryPath, _contentBuf) {
182
- var rv = await esbuild.build(Object.assign({}, baseOpts, {
183
- entryPoints: [entryPath],
184
- }));
185
- // esbuild { write: false } returns { outputFiles: [{ path, contents }, ...] }.
186
- // For a single entry without sourcemaps we get one file; with
187
- // sourcemap we get the .js + .js.map. Match by extension.
188
- var outFiles = (rv && rv.outputFiles) || [];
189
- var jsLike = null;
190
- var map = null;
191
- for (var i = 0; i < outFiles.length; i++) {
192
- var f = outFiles[i];
193
- if (/\.map$/.test(f.path)) map = f.text;
194
- else jsLike = f;
195
- }
196
- if (!jsLike) {
197
- throw new BundlerError("bundler/engine-empty",
198
- "esbuild engine returned no output for " + entryPath);
199
- }
200
- return {
201
- content: Buffer.from(jsLike.contents),
202
- sourceMap: map,
203
- };
204
- },
205
- };
206
- },
207
- };
208
-
209
- function _validateEngine(eng) {
210
- if (eng == null) return engine.passthrough;
211
- if (typeof eng !== "object") {
212
- throw new BundlerError("bundler/bad-engine",
213
- "opts.engine must be an object with { name, transform }, got " + typeof eng);
214
- }
215
- if (typeof eng.transform !== "function") {
216
- throw new BundlerError("bundler/bad-engine",
217
- "opts.engine.transform must be a function (entryPath, contentBuf) → " +
218
- "{ content, sourceMap? }");
219
- }
220
- if (typeof eng.name !== "string" || eng.name.length === 0) {
221
- throw new BundlerError("bundler/bad-engine",
222
- "opts.engine.name must be a non-empty string");
223
- }
224
- return eng;
225
- }
226
-
227
- function create(opts) {
228
- opts = opts || {};
229
- validateOpts(opts, [
230
- "entries", "outdir", "cwd", "engine",
231
- "manifest", "hash", "hashLen", "graceMs", "log",
232
- "_watch", "_setTimeout", "_clearTimeout",
233
- ], "b.bundler");
234
- _validateEntries(opts.entries);
235
- validateOpts.requireNonEmptyString(opts.outdir, "bundler.create: opts.outdir", BundlerError, "bundler/no-outdir");
236
- var engineImpl = _validateEngine(opts.engine);
237
-
238
- var entries = Object.assign({}, opts.entries);
239
- var cwd = opts.cwd || process.cwd();
240
- var outdir = path.isAbsolute(opts.outdir) ? opts.outdir : path.resolve(cwd, opts.outdir);
241
- var manifestName = (opts.manifest === false || opts.manifest === null)
242
- ? null
243
- : (typeof opts.manifest === "string" && opts.manifest.length > 0
244
- ? opts.manifest
245
- : "manifest.json");
246
- var hashOn = opts.hash !== false;
247
- var hashLen = DEFAULT_HASH_LEN;
248
- if (opts.hashLen !== undefined) {
249
- if (!nb.isPositiveFiniteInt(opts.hashLen) ||
250
- opts.hashLen < MIN_HASH_LEN || opts.hashLen > MAX_HASH_LEN) {
251
- throw new BundlerError("bundler/bad-hash-len",
252
- "bundler.create: opts.hashLen must be a positive finite integer " +
253
- "between " + MIN_HASH_LEN + " and " + MAX_HASH_LEN +
254
- "; got " + nb.shape(opts.hashLen));
255
- }
256
- hashLen = opts.hashLen;
257
- }
258
- var log = opts.log || null;
259
-
260
- // Test seam: tests pass a fake watcher so we don't actually fs.watch
261
- var watchFn = opts._watch || function (dirOrFile, wopts, listener) {
262
- return fs.watch(dirOrFile, wopts, listener);
263
- };
264
- var setTimeoutFn = opts._setTimeout || setTimeout;
265
- var clearTimeoutFn = opts._clearTimeout || clearTimeout;
266
- nb.requireNonNegativeFiniteIntIfPresent(opts.graceMs,
267
- "bundler.create: opts.graceMs", BundlerError, "bundler/bad-grace-ms");
268
- var graceMs = opts.graceMs !== undefined ? opts.graceMs : DEFAULT_GRACE_MS;
269
-
270
- var watchers = [];
271
- var debounceTimer = null;
272
- var watching = false;
273
-
274
- function _resolveEntry(p) {
275
- return path.isAbsolute(p) ? p : path.resolve(cwd, p);
276
- }
277
-
278
- var _logVia = logModule.makeViaOrFallback(log, bootLog);
279
-
280
- async function build() {
281
- var t0 = Date.now();
282
- _ensureOutDir(outdir);
283
-
284
- var outputs = [];
285
- var manifest = {};
286
- var names = Object.keys(entries);
287
-
288
- for (var i = 0; i < names.length; i++) {
289
- var name = names[i];
290
- var entryPath = _resolveEntry(entries[name]);
291
- var ext = path.extname(entryPath);
292
- var raw;
293
- try { raw = fs.readFileSync(entryPath); }
294
- catch (e) {
295
- throw new BundlerError("bundler/read-failed",
296
- "could not read entry '" + name + "' at " + entryPath +
297
- ": " + ((e && e.message) || String(e)));
298
- }
299
- var transformed;
300
- try { transformed = await engineImpl.transform(entryPath, raw); }
301
- catch (e) {
302
- throw new BundlerError("bundler/engine-failed",
303
- "engine '" + engineImpl.name + "' failed on entry '" + name +
304
- "': " + ((e && e.message) || String(e)));
305
- }
306
- var content = transformed && transformed.content != null ? transformed.content : raw;
307
- if (typeof content === "string") content = Buffer.from(content, "utf8");
308
- else if (!Buffer.isBuffer(content)) {
309
- throw new BundlerError("bundler/engine-bad-output",
310
- "engine '" + engineImpl.name + "' returned non-Buffer / non-string content for '" +
311
- name + "'");
312
- }
313
- var sourceMap = transformed && transformed.sourceMap;
314
- var hash = hashOn ? _hashContent(content, hashLen) : null;
315
- var outName = hashOn ? _hashedName(name, hash, ext) : (name + ext);
316
- var outPath = path.join(outdir, outName);
317
- // atomic-file write so a concurrent reader (the http server
318
- // serving outdir) never sees a partial file
319
- atomicFile.writeSync(outPath, content, { mode: 0o644 });
320
- // Sibling .map when the engine produced one. Source maps go
321
- // unhashed (browsers fetch <hashed.js>.map) — write them
322
- // alongside as <hashedOutName>.map.
323
- var sourceMapPath = null;
324
- if (sourceMap) {
325
- sourceMapPath = outPath + ".map";
326
- var mapBuf = Buffer.isBuffer(sourceMap) ? sourceMap : Buffer.from(String(sourceMap), "utf8");
327
- atomicFile.writeSync(sourceMapPath, mapBuf, { mode: 0o644 });
328
- }
329
- outputs.push({
330
- name: name,
331
- entry: entryPath,
332
- path: outPath,
333
- hash: hash,
334
- bytes: content.length,
335
- ext: ext,
336
- sourceMapPath: sourceMapPath,
337
- });
338
- manifest[name] = outName;
339
- }
340
-
341
- var manifestPath = null;
342
- if (manifestName) {
343
- manifestPath = path.join(outdir, manifestName);
344
- atomicFile.writeSync(
345
- manifestPath,
346
- safeJson.stringify(manifest, null, 2) + "\n",
347
- { mode: 0o644 }
348
- );
349
- }
350
-
351
- var result = {
352
- outputs: outputs,
353
- manifestPath: manifestPath,
354
- manifest: manifest,
355
- durationMs: Date.now() - t0,
356
- };
357
- _logVia("info", "build complete",
358
- { entries: outputs.length, durationMs: result.durationMs });
359
- return result;
360
- }
361
-
362
- function _scheduleRebuild(reason, callback) {
363
- if (debounceTimer) {
364
- try { clearTimeoutFn(debounceTimer); } catch (_e) { /* timer already cleared */ }
365
- }
366
- debounceTimer = setTimeoutFn(function () {
367
- debounceTimer = null;
368
- _logVia("info", "rebuilding", { reason: reason });
369
- build().then(
370
- function (r) { if (callback) try { callback(null, r); } catch (_e) { /* operator callback threw — logged elsewhere if material */ } },
371
- function (e) {
372
- _logVia("error", "rebuild failed", { error: (e && e.message) || String(e) });
373
- if (callback) try { callback(e, null); } catch (_e) { /* operator callback threw — already logged */ }
374
- }
375
- );
376
- }, graceMs);
377
- if (debounceTimer && typeof debounceTimer.unref === "function") debounceTimer.unref();
378
- }
379
-
380
- function watch(callback) {
381
- if (watching) return;
382
- watching = true;
383
- var names = Object.keys(entries);
384
- for (var i = 0; i < names.length; i++) {
385
- (function (name) {
386
- var entryPath = _resolveEntry(entries[name]);
387
- // Watch the entry's directory (single-file watches are flaky
388
- // across editors that write-then-rename). Filter events to the
389
- // entry's basename only.
390
- var dir = path.dirname(entryPath);
391
- var base = path.basename(entryPath);
392
- var w;
393
- try {
394
- w = watchFn(dir, { persistent: false }, function (eventType, filename) {
395
- if (filename && String(filename) === base) {
396
- _scheduleRebuild(name, callback);
397
- }
398
- });
399
- } catch (e) {
400
- _logVia("warn", "could not watch " + dir,
401
- { error: (e && e.message) || String(e) });
402
- return;
403
- }
404
- if (w && typeof w.on === "function") {
405
- w.on("error", function (err) {
406
- _logVia("warn", "watcher error",
407
- { dir: dir, error: (err && err.message) || String(err) });
408
- });
409
- }
410
- watchers.push(w);
411
- })(names[i]);
412
- }
413
- }
414
-
415
- async function close() {
416
- watching = false;
417
- if (debounceTimer) {
418
- try { clearTimeoutFn(debounceTimer); } catch (_e) { /* timer already cleared */ }
419
- debounceTimer = null;
420
- }
421
- for (var i = 0; i < watchers.length; i++) {
422
- try { if (watchers[i] && typeof watchers[i].close === "function") watchers[i].close(); }
423
- catch (_e) { /* close best-effort */ }
424
- }
425
- watchers = [];
426
- }
427
-
428
- return {
429
- build: build,
430
- watch: watch,
431
- close: close,
432
- entries: entries,
433
- outdir: outdir,
434
- };
435
- }
436
-
437
- module.exports = {
438
- create: create,
439
- engine: engine,
440
- BundlerError: BundlerError,
441
- };
1
+ "use strict";
2
+ /**
3
+ * bundler — content-hashed asset pipeline + manifest, with optional
4
+ * operator-supplied ESM engine for module-graph bundling, tree-shaking,
5
+ * minification, and source maps.
6
+ *
7
+ * What this primitive does:
8
+ * - Reads each named entry from disk (or runs it through an
9
+ * operator-supplied engine first for module-graph builds)
10
+ * - Computes a content hash (SHA3-512, first 16 hex chars)
11
+ * - Writes the entry to outdir/<name>.<hash>.<ext> for cache-busting
12
+ * - Emits manifest.json mapping logical name → hashed filename
13
+ * - Optionally watches entries and rebuilds on change
14
+ *
15
+ * Engine surface (new in v0.6.44):
16
+ *
17
+ * var bundler = b.bundler.create({
18
+ * entries: { app: "./src/app.js" },
19
+ * outdir: "./public/dist",
20
+ * engine: engineInstance, // optional — defaults to passthrough
21
+ * });
22
+ *
23
+ * `engineInstance` implements:
24
+ *
25
+ * {
26
+ * name: string, // logged on build
27
+ * transform: async (entryPath, contentBuf) => {
28
+ * content: Buffer | string, // post-transform output
29
+ * sourceMap: string | Buffer | null, // optional .map sibling
30
+ * imports?: [string], // optional — for graph-aware watch
31
+ * },
32
+ * }
33
+ *
34
+ * The default engine is `b.bundler.engine.passthrough` — reads the file
35
+ * verbatim, no transform. This is what every existing `b.bundler.create`
36
+ * call gets without setting `engine`.
37
+ *
38
+ * For ESM module-graph bundling + tree-shake + minify + sourcemaps,
39
+ * operators supply esbuild themselves (devDependency or operator-side
40
+ * vendored) and adapt it via:
41
+ *
42
+ * var esbuild = require("esbuild");
43
+ * var bundler = b.bundler.create({
44
+ * entries: { app: "./src/app.js" },
45
+ * outdir: "./public/dist",
46
+ * engine: b.bundler.engine.fromEsbuild(esbuild, {
47
+ * bundle: true,
48
+ * format: "esm",
49
+ * target: ["chrome120", "firefox120", "safari17"],
50
+ * minify: true,
51
+ * sourcemap: true,
52
+ * }),
53
+ * });
54
+ *
55
+ * The framework intentionally does NOT vendor `esbuild-wasm` itself
56
+ * (the wasm blob is ~10 MB — bigger than every other vendored dep
57
+ * combined; it would 3-5x the @blamejs/core npm tarball for a build-
58
+ * time tool most operators only need at deploy time anyway). Treating
59
+ * esbuild as an operator-supplied driver follows the same pattern as
60
+ * `b.externalDb` and `b.mtlsCa.create({ engine })`: the framework owns
61
+ * the integration seam, the operator brings the heavy machinery.
62
+ *
63
+ * Out of scope (true even with the engine surface):
64
+ * - A bespoke bundler bundled INSIDE the framework. The engine
65
+ * surface IS the answer; operators wanting esbuild / rollup /
66
+ * swc / vite wire them through it.
67
+ *
68
+ * Operator with no engine + multi-file ESM source: pre-concat manually
69
+ * and point bundler at the result.
70
+ *
71
+ * Manifest format (manifest.json under outdir):
72
+ * { "app": "app.4a8c2f1d9e3b7062.js", "styles": "styles.b29f1e7c.css" }
73
+ *
74
+ * Integrates with lib/static.js: serve `outdir` as a static directory;
75
+ * lib/static.js's hashed-path detection sets long-cache headers on
76
+ * files that look hashed, and integrity() reads the manifest to
77
+ * generate Subresource Integrity attributes.
78
+ */
79
+
80
+ var path = require("path");
81
+ var fs = require("fs");
82
+ var crypto = require("./crypto");
83
+ var atomicFile = require("./atomic-file");
84
+ var logModule = require("./log");
85
+ var nb = require("./numeric-bounds");
86
+ var safeJson = require("./safe-json");
87
+ var validateOpts = require("./validate-opts");
88
+ var { defineClass } = require("./framework-error");
89
+
90
+ var BundlerError = defineClass("BundlerError", { alwaysPermanent: true });
91
+ var bootLog = logModule.boot("bundler");
92
+
93
+ // Default content-hash length: 16 hex chars (8 bytes of SHA3-512). Long
94
+ // enough that collision probability is negligible for asset cache busting,
95
+ // short enough to keep generated filenames readable.
96
+ var DEFAULT_HASH_LEN = 0x10;
97
+ var MIN_HASH_LEN = 0x4;
98
+ var MAX_HASH_LEN = 0x40;
99
+ var DEFAULT_GRACE_MS = 100;
100
+
101
+ function _hashContent(buf, hexLen) {
102
+ // SHA3-512 → take the first hexLen hex chars. Same family as the
103
+ // framework's other content fingerprints (no SHA-256 for new code).
104
+ return crypto.sha3Hash(buf).slice(0, hexLen);
105
+ }
106
+
107
+ function _hashedName(baseName, hash, ext) {
108
+ return baseName + "." + hash + ext;
109
+ }
110
+
111
+ // outDir mode is 0o755 (world-readable) because the bundler emits
112
+ // assets a public HTTP server reads. Other framework dirs default to
113
+ // 0o700 via atomicFile.ensureDir.
114
+ function _ensureOutDir(p) {
115
+ try { atomicFile.ensureDir(p, 0o755); }
116
+ catch (e) {
117
+ if (e && e.code !== "EEXIST") {
118
+ throw new BundlerError("bundler/mkdir-failed",
119
+ "could not create outdir '" + p + "': " + ((e && e.message) || String(e)));
120
+ }
121
+ }
122
+ }
123
+
124
+ function _validateEntries(entries) {
125
+ if (!entries || typeof entries !== "object" || Array.isArray(entries)) {
126
+ throw new BundlerError("bundler/no-entries",
127
+ "bundler.create requires opts.entries (a { name: path } map)");
128
+ }
129
+ var names = Object.keys(entries);
130
+ if (names.length === 0) {
131
+ throw new BundlerError("bundler/no-entries",
132
+ "bundler.create: opts.entries map must have at least one entry");
133
+ }
134
+ // Reject names with path separators or '..' so operator-supplied
135
+ // logical names can't escape the outdir on write.
136
+ for (var i = 0; i < names.length; i++) {
137
+ var n = names[i];
138
+ if (typeof n !== "string" || n.length === 0 ||
139
+ /[\\/]/.test(n) || n === ".." || n === ".") {
140
+ throw new BundlerError("bundler/bad-entry-name",
141
+ "entry name '" + n + "' must be a non-empty string without path separators");
142
+ }
143
+ var p = entries[n];
144
+ if (typeof p !== "string" || p.length === 0) {
145
+ throw new BundlerError("bundler/bad-entry-path",
146
+ "entry '" + n + "' must map to a non-empty source path");
147
+ }
148
+ }
149
+ }
150
+
151
+ // ---- Engine surface ----
152
+ //
153
+ // Engines transform an entry's content before the cache-busting / hash
154
+ // step. The default `passthrough` engine reads the file verbatim — same
155
+ // behavior every pre-v0.6.44 caller got. Operators wanting ESM
156
+ // module-graph bundling supply esbuild (or any compatible tool) and
157
+ // adapt it via `engine.fromEsbuild(esbuild, opts)`.
158
+ var engine = {
159
+ passthrough: {
160
+ name: "passthrough",
161
+ transform: async function (_entryPath, contentBuf) {
162
+ return { content: contentBuf, sourceMap: null };
163
+ },
164
+ },
165
+
166
+ fromEsbuild: function (esbuild, esbuildOpts) {
167
+ if (!esbuild || typeof esbuild.build !== "function") {
168
+ throw new BundlerError("bundler/bad-engine",
169
+ "engine.fromEsbuild: pass the esbuild module (require('esbuild')); " +
170
+ "got " + typeof esbuild);
171
+ }
172
+ var baseOpts = Object.assign({
173
+ bundle: true,
174
+ write: false,
175
+ format: "esm",
176
+ platform: "browser",
177
+ logLevel: "silent",
178
+ }, esbuildOpts || {});
179
+ return {
180
+ name: "esbuild",
181
+ transform: async function (entryPath, _contentBuf) {
182
+ var rv = await esbuild.build(Object.assign({}, baseOpts, {
183
+ entryPoints: [entryPath],
184
+ }));
185
+ // esbuild { write: false } returns { outputFiles: [{ path, contents }, ...] }.
186
+ // For a single entry without sourcemaps we get one file; with
187
+ // sourcemap we get the .js + .js.map. Match by extension.
188
+ var outFiles = (rv && rv.outputFiles) || [];
189
+ var jsLike = null;
190
+ var map = null;
191
+ for (var i = 0; i < outFiles.length; i++) {
192
+ var f = outFiles[i];
193
+ if (/\.map$/.test(f.path)) map = f.text;
194
+ else jsLike = f;
195
+ }
196
+ if (!jsLike) {
197
+ throw new BundlerError("bundler/engine-empty",
198
+ "esbuild engine returned no output for " + entryPath);
199
+ }
200
+ return {
201
+ content: Buffer.from(jsLike.contents),
202
+ sourceMap: map,
203
+ };
204
+ },
205
+ };
206
+ },
207
+ };
208
+
209
+ function _validateEngine(eng) {
210
+ if (eng == null) return engine.passthrough;
211
+ if (typeof eng !== "object") {
212
+ throw new BundlerError("bundler/bad-engine",
213
+ "opts.engine must be an object with { name, transform }, got " + typeof eng);
214
+ }
215
+ if (typeof eng.transform !== "function") {
216
+ throw new BundlerError("bundler/bad-engine",
217
+ "opts.engine.transform must be a function (entryPath, contentBuf) → " +
218
+ "{ content, sourceMap? }");
219
+ }
220
+ if (typeof eng.name !== "string" || eng.name.length === 0) {
221
+ throw new BundlerError("bundler/bad-engine",
222
+ "opts.engine.name must be a non-empty string");
223
+ }
224
+ return eng;
225
+ }
226
+
227
+ function create(opts) {
228
+ opts = opts || {};
229
+ validateOpts(opts, [
230
+ "entries", "outdir", "cwd", "engine",
231
+ "manifest", "hash", "hashLen", "graceMs", "log",
232
+ "_watch", "_setTimeout", "_clearTimeout",
233
+ ], "b.bundler");
234
+ _validateEntries(opts.entries);
235
+ validateOpts.requireNonEmptyString(opts.outdir, "bundler.create: opts.outdir", BundlerError, "bundler/no-outdir");
236
+ var engineImpl = _validateEngine(opts.engine);
237
+
238
+ var entries = Object.assign({}, opts.entries);
239
+ var cwd = opts.cwd || process.cwd();
240
+ var outdir = path.isAbsolute(opts.outdir) ? opts.outdir : path.resolve(cwd, opts.outdir);
241
+ var manifestName = (opts.manifest === false || opts.manifest === null)
242
+ ? null
243
+ : (typeof opts.manifest === "string" && opts.manifest.length > 0
244
+ ? opts.manifest
245
+ : "manifest.json");
246
+ var hashOn = opts.hash !== false;
247
+ var hashLen = DEFAULT_HASH_LEN;
248
+ if (opts.hashLen !== undefined) {
249
+ if (!nb.isPositiveFiniteInt(opts.hashLen) ||
250
+ opts.hashLen < MIN_HASH_LEN || opts.hashLen > MAX_HASH_LEN) {
251
+ throw new BundlerError("bundler/bad-hash-len",
252
+ "bundler.create: opts.hashLen must be a positive finite integer " +
253
+ "between " + MIN_HASH_LEN + " and " + MAX_HASH_LEN +
254
+ "; got " + nb.shape(opts.hashLen));
255
+ }
256
+ hashLen = opts.hashLen;
257
+ }
258
+ var log = opts.log || null;
259
+
260
+ // Test seam: tests pass a fake watcher so we don't actually fs.watch
261
+ var watchFn = opts._watch || function (dirOrFile, wopts, listener) {
262
+ return fs.watch(dirOrFile, wopts, listener);
263
+ };
264
+ var setTimeoutFn = opts._setTimeout || setTimeout;
265
+ var clearTimeoutFn = opts._clearTimeout || clearTimeout;
266
+ nb.requireNonNegativeFiniteIntIfPresent(opts.graceMs,
267
+ "bundler.create: opts.graceMs", BundlerError, "bundler/bad-grace-ms");
268
+ var graceMs = opts.graceMs !== undefined ? opts.graceMs : DEFAULT_GRACE_MS;
269
+
270
+ var watchers = [];
271
+ var debounceTimer = null;
272
+ var watching = false;
273
+
274
+ function _resolveEntry(p) {
275
+ return path.isAbsolute(p) ? p : path.resolve(cwd, p);
276
+ }
277
+
278
+ var _logVia = logModule.makeViaOrFallback(log, bootLog);
279
+
280
+ async function build() {
281
+ var t0 = Date.now();
282
+ _ensureOutDir(outdir);
283
+
284
+ var outputs = [];
285
+ var manifest = {};
286
+ var names = Object.keys(entries);
287
+
288
+ for (var i = 0; i < names.length; i++) {
289
+ var name = names[i];
290
+ var entryPath = _resolveEntry(entries[name]);
291
+ var ext = path.extname(entryPath);
292
+ var raw;
293
+ try { raw = fs.readFileSync(entryPath); }
294
+ catch (e) {
295
+ throw new BundlerError("bundler/read-failed",
296
+ "could not read entry '" + name + "' at " + entryPath +
297
+ ": " + ((e && e.message) || String(e)));
298
+ }
299
+ var transformed;
300
+ try { transformed = await engineImpl.transform(entryPath, raw); }
301
+ catch (e) {
302
+ throw new BundlerError("bundler/engine-failed",
303
+ "engine '" + engineImpl.name + "' failed on entry '" + name +
304
+ "': " + ((e && e.message) || String(e)));
305
+ }
306
+ var content = transformed && transformed.content != null ? transformed.content : raw;
307
+ if (typeof content === "string") content = Buffer.from(content, "utf8");
308
+ else if (!Buffer.isBuffer(content)) {
309
+ throw new BundlerError("bundler/engine-bad-output",
310
+ "engine '" + engineImpl.name + "' returned non-Buffer / non-string content for '" +
311
+ name + "'");
312
+ }
313
+ var sourceMap = transformed && transformed.sourceMap;
314
+ var hash = hashOn ? _hashContent(content, hashLen) : null;
315
+ var outName = hashOn ? _hashedName(name, hash, ext) : (name + ext);
316
+ var outPath = path.join(outdir, outName);
317
+ // atomic-file write so a concurrent reader (the http server
318
+ // serving outdir) never sees a partial file
319
+ atomicFile.writeSync(outPath, content, { mode: 0o644 });
320
+ // Sibling .map when the engine produced one. Source maps go
321
+ // unhashed (browsers fetch <hashed.js>.map) — write them
322
+ // alongside as <hashedOutName>.map.
323
+ var sourceMapPath = null;
324
+ if (sourceMap) {
325
+ sourceMapPath = outPath + ".map";
326
+ var mapBuf = Buffer.isBuffer(sourceMap) ? sourceMap : Buffer.from(String(sourceMap), "utf8");
327
+ atomicFile.writeSync(sourceMapPath, mapBuf, { mode: 0o644 });
328
+ }
329
+ outputs.push({
330
+ name: name,
331
+ entry: entryPath,
332
+ path: outPath,
333
+ hash: hash,
334
+ bytes: content.length,
335
+ ext: ext,
336
+ sourceMapPath: sourceMapPath,
337
+ });
338
+ manifest[name] = outName;
339
+ }
340
+
341
+ var manifestPath = null;
342
+ if (manifestName) {
343
+ manifestPath = path.join(outdir, manifestName);
344
+ atomicFile.writeSync(
345
+ manifestPath,
346
+ safeJson.stringify(manifest, null, 2) + "\n",
347
+ { mode: 0o644 }
348
+ );
349
+ }
350
+
351
+ var result = {
352
+ outputs: outputs,
353
+ manifestPath: manifestPath,
354
+ manifest: manifest,
355
+ durationMs: Date.now() - t0,
356
+ };
357
+ _logVia("info", "build complete",
358
+ { entries: outputs.length, durationMs: result.durationMs });
359
+ return result;
360
+ }
361
+
362
+ function _scheduleRebuild(reason, callback) {
363
+ if (debounceTimer) {
364
+ try { clearTimeoutFn(debounceTimer); } catch (_e) { /* timer already cleared */ }
365
+ }
366
+ debounceTimer = setTimeoutFn(function () {
367
+ debounceTimer = null;
368
+ _logVia("info", "rebuilding", { reason: reason });
369
+ build().then(
370
+ function (r) { if (callback) try { callback(null, r); } catch (_e) { /* operator callback threw — logged elsewhere if material */ } },
371
+ function (e) {
372
+ _logVia("error", "rebuild failed", { error: (e && e.message) || String(e) });
373
+ if (callback) try { callback(e, null); } catch (_e) { /* operator callback threw — already logged */ }
374
+ }
375
+ );
376
+ }, graceMs);
377
+ if (debounceTimer && typeof debounceTimer.unref === "function") debounceTimer.unref();
378
+ }
379
+
380
+ function watch(callback) {
381
+ if (watching) return;
382
+ watching = true;
383
+ var names = Object.keys(entries);
384
+ for (var i = 0; i < names.length; i++) {
385
+ (function (name) {
386
+ var entryPath = _resolveEntry(entries[name]);
387
+ // Watch the entry's directory (single-file watches are flaky
388
+ // across editors that write-then-rename). Filter events to the
389
+ // entry's basename only.
390
+ var dir = path.dirname(entryPath);
391
+ var base = path.basename(entryPath);
392
+ var w;
393
+ try {
394
+ w = watchFn(dir, { persistent: false }, function (eventType, filename) {
395
+ if (filename && String(filename) === base) {
396
+ _scheduleRebuild(name, callback);
397
+ }
398
+ });
399
+ } catch (e) {
400
+ _logVia("warn", "could not watch " + dir,
401
+ { error: (e && e.message) || String(e) });
402
+ return;
403
+ }
404
+ if (w && typeof w.on === "function") {
405
+ w.on("error", function (err) {
406
+ _logVia("warn", "watcher error",
407
+ { dir: dir, error: (err && err.message) || String(err) });
408
+ });
409
+ }
410
+ watchers.push(w);
411
+ })(names[i]);
412
+ }
413
+ }
414
+
415
+ async function close() {
416
+ watching = false;
417
+ if (debounceTimer) {
418
+ try { clearTimeoutFn(debounceTimer); } catch (_e) { /* timer already cleared */ }
419
+ debounceTimer = null;
420
+ }
421
+ for (var i = 0; i < watchers.length; i++) {
422
+ try { if (watchers[i] && typeof watchers[i].close === "function") watchers[i].close(); }
423
+ catch (_e) { /* close best-effort */ }
424
+ }
425
+ watchers = [];
426
+ }
427
+
428
+ return {
429
+ build: build,
430
+ watch: watch,
431
+ close: close,
432
+ entries: entries,
433
+ outdir: outdir,
434
+ };
435
+ }
436
+
437
+ module.exports = {
438
+ create: create,
439
+ engine: engine,
440
+ BundlerError: BundlerError,
441
+ };