@blamejs/core 0.4.13 → 0.4.15

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.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.4.x
10
10
 
11
+ - **0.4.14** (2026-04-30) — b.i18n: lazy locales + ordinal plurals + onMissingKey hook
12
+ - **0.4.13** (2026-04-30) — b.db: streaming query results
11
13
  - **0.4.12** (2026-04-30) — b.log: multi-sink output with per-sink level filtering
12
14
  - **0.4.11** (2026-04-30) — b.cache: bytes-cap eviction, sliding TTL, tag invalidation
13
15
  - **0.4.10** (2026-04-30) — bodyParser multipart: fileFilter + per-field maxBytes/mimeTypes
@@ -292,10 +292,198 @@ function _fromH2Headers(h2Headers) {
292
292
 
293
293
  // ---- request() ----
294
294
 
295
+ var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
296
+
297
+ // Build a multipart/form-data body from { fields, files } shape.
298
+ // Mirrors the wire format that lib/middleware/body-parser.js's multipart
299
+ // parser accepts so round-trip from one blamejs app's outbound to
300
+ // another's inbound is exact.
301
+ function _buildMultipartBody(spec) {
302
+ var nodeCrypto = require("node:crypto");
303
+ var boundary = "----blamejs-mp-" + nodeCrypto.randomBytes(16).toString("hex");
304
+ var CRLF = "\r\n";
305
+ var parts = [];
306
+
307
+ function _pushField(name, value) {
308
+ if (typeof name !== "string" || name.length === 0) {
309
+ throw new Error("multipart: field name must be a non-empty string");
310
+ }
311
+ var head = "--" + boundary + CRLF +
312
+ 'Content-Disposition: form-data; name="' + name + '"' + CRLF + CRLF;
313
+ parts.push(Buffer.from(head, "utf8"));
314
+ parts.push(Buffer.isBuffer(value) ? value : Buffer.from(String(value), "utf8"));
315
+ parts.push(Buffer.from(CRLF, "utf8"));
316
+ }
317
+
318
+ function _pushFile(file) {
319
+ if (!file || typeof file !== "object") throw new Error("multipart: file entries must be objects");
320
+ if (typeof file.field !== "string" || file.field.length === 0) {
321
+ throw new Error("multipart: file.field must be a non-empty string");
322
+ }
323
+ var filename = typeof file.filename === "string" && file.filename.length > 0
324
+ ? file.filename : "blob";
325
+ var mimeType = file.contentType || file.mimeType || "application/octet-stream";
326
+ var content = file.content;
327
+ if (typeof content === "string") content = Buffer.from(content, "utf8");
328
+ if (!Buffer.isBuffer(content)) {
329
+ throw new Error("multipart: file.content must be a Buffer or string");
330
+ }
331
+ var head = "--" + boundary + CRLF +
332
+ 'Content-Disposition: form-data; name="' + file.field + '"' +
333
+ '; filename="' + filename.replace(/"/g, "%22") + '"' + CRLF +
334
+ "Content-Type: " + mimeType + CRLF + CRLF;
335
+ parts.push(Buffer.from(head, "utf8"));
336
+ parts.push(content);
337
+ parts.push(Buffer.from(CRLF, "utf8"));
338
+ }
339
+
340
+ if (spec && spec.fields && typeof spec.fields === "object") {
341
+ var keys = Object.keys(spec.fields);
342
+ for (var i = 0; i < keys.length; i++) {
343
+ var k = keys[i];
344
+ var v = spec.fields[k];
345
+ if (Array.isArray(v)) {
346
+ for (var j = 0; j < v.length; j++) _pushField(k, v[j]);
347
+ } else {
348
+ _pushField(k, v);
349
+ }
350
+ }
351
+ }
352
+ if (spec && Array.isArray(spec.files)) {
353
+ for (var fi = 0; fi < spec.files.length; fi++) _pushFile(spec.files[fi]);
354
+ }
355
+ parts.push(Buffer.from("--" + boundary + "--" + CRLF, "utf8"));
356
+ return { boundary: boundary, body: Buffer.concat(parts) };
357
+ }
358
+
359
+ // Headers stripped on cross-origin redirect to defend against accidental
360
+ // credential exfiltration. Lower-case for header-map comparison.
361
+ var SENSITIVE_HEADERS_LC = ["authorization", "cookie", "proxy-authorization"];
362
+
363
+ function _stripCrossOriginAuth(headers) {
364
+ var out = {};
365
+ var keys = Object.keys(headers);
366
+ for (var i = 0; i < keys.length; i++) {
367
+ if (SENSITIVE_HEADERS_LC.indexOf(keys[i].toLowerCase()) !== -1) continue;
368
+ out[keys[i]] = headers[keys[i]];
369
+ }
370
+ return out;
371
+ }
372
+
295
373
  function request(opts) {
296
374
  if (!opts || !opts.url) {
297
375
  return Promise.reject(_makeError(opts && opts.errorClass, "BAD_ARG", "url is required", true));
298
376
  }
377
+
378
+ // Multipart shorthand: { multipart: { fields, files } } expands to
379
+ // body + Content-Type with the boundary parameter. Mutually exclusive
380
+ // with caller-supplied body / Content-Type.
381
+ if (opts.multipart) {
382
+ if (opts.body !== undefined) {
383
+ return Promise.reject(_makeError(opts.errorClass, "BAD_ARG",
384
+ "request: pass either { body } or { multipart }, not both", true));
385
+ }
386
+ var built;
387
+ try { built = _buildMultipartBody(opts.multipart); }
388
+ catch (e) {
389
+ return Promise.reject(_makeError(opts.errorClass, "BAD_ARG", e.message, true));
390
+ }
391
+ opts = Object.assign({}, opts, {
392
+ method: opts.method || "POST",
393
+ body: built.body,
394
+ headers: Object.assign({}, opts.headers || {}, {
395
+ "Content-Type": "multipart/form-data; boundary=" + built.boundary,
396
+ "Content-Length": String(built.body.length),
397
+ }),
398
+ multipart: undefined,
399
+ });
400
+ }
401
+
402
+ // maxRedirects:
403
+ // undefined → today's behavior (no follow). Caller inspects 3xx.
404
+ // null → today's behavior (explicit). Same as undefined.
405
+ // 0 → no follow, but 3xx returned to caller (alias of null).
406
+ // N → follow up to N hops; 3xx with no Location returned as-is.
407
+ var maxRedirects = (opts.maxRedirects === undefined || opts.maxRedirects === null)
408
+ ? null : opts.maxRedirects;
409
+ if (maxRedirects !== null) {
410
+ if (typeof maxRedirects !== "number" || !isFinite(maxRedirects) || maxRedirects < 0 ||
411
+ Math.floor(maxRedirects) !== maxRedirects) {
412
+ return Promise.reject(_makeError(opts.errorClass, "BAD_ARG",
413
+ "maxRedirects must be a non-negative integer or null", true));
414
+ }
415
+ }
416
+ if (maxRedirects === null || maxRedirects === 0) {
417
+ return _requestSingle(opts);
418
+ }
419
+
420
+ return _requestWithRedirects(opts, maxRedirects);
421
+ }
422
+
423
+ function _requestWithRedirects(opts, hopsLeft) {
424
+ var originalUrl = opts.url;
425
+ var originalOrigin = null;
426
+ try {
427
+ var u0 = new URL(opts.url);
428
+ originalOrigin = u0.protocol + "//" + u0.host;
429
+ } catch (_e) { /* request() will reject on next hop's parse */ }
430
+
431
+ var current = Object.assign({}, opts, { _resolveOnRedirect: true });
432
+ function _follow() {
433
+ return _requestSingle(current).then(function (res) {
434
+ if (!REDIRECT_STATUSES.has(res.statusCode) || hopsLeft <= 0) return res;
435
+ var loc = res.headers && (res.headers.location || res.headers.Location);
436
+ if (!loc) return res; // 3xx with no Location — operator handles
437
+ hopsLeft -= 1;
438
+
439
+ // Resolve relative Location against the just-fetched URL (the URL
440
+ // of the request that produced the redirect, which may itself be a
441
+ // post-redirect URL).
442
+ var nextUrl;
443
+ try { nextUrl = new URL(loc, current.url).toString(); }
444
+ catch (_e) {
445
+ return Promise.reject(_makeError(opts.errorClass, "BAD_REDIRECT",
446
+ "Location header invalid URL: " + loc, true));
447
+ }
448
+
449
+ // Cross-origin auth-header strip.
450
+ var nextHeaders = current.headers || {};
451
+ var nextOrigin;
452
+ try {
453
+ var nu = new URL(nextUrl);
454
+ nextOrigin = nu.protocol + "//" + nu.host;
455
+ } catch (_e) { /* request() will reject when it tries to parse */ }
456
+ if (originalOrigin && nextOrigin && nextOrigin !== originalOrigin) {
457
+ nextHeaders = _stripCrossOriginAuth(nextHeaders);
458
+ }
459
+
460
+ // 303 → always GET; body dropped. 301/302 → historical clients
461
+ // also coerce non-GET bodies (we follow that convention). 307/308
462
+ // → preserve method + body.
463
+ var nextMethod = current.method || "GET";
464
+ var nextBody = current.body;
465
+ if (res.statusCode === 303 ||
466
+ ((res.statusCode === 301 || res.statusCode === 302) &&
467
+ nextMethod !== "GET" && nextMethod !== "HEAD")) {
468
+ nextMethod = "GET";
469
+ nextBody = undefined;
470
+ }
471
+
472
+ current = Object.assign({}, current, {
473
+ url: nextUrl,
474
+ method: nextMethod,
475
+ body: nextBody,
476
+ headers: nextHeaders,
477
+ _resolveOnRedirect: true,
478
+ });
479
+ return _follow();
480
+ });
481
+ }
482
+ void originalUrl;
483
+ return _follow();
484
+ }
485
+
486
+ function _requestSingle(opts) {
299
487
  // Validate scheme + shape via url-safe. Default is HTTPS-only — the
300
488
  // framework refuses to silently drop bytes on the wire as cleartext.
301
489
  // Callers with cleartext endpoints (h2c, internal services, test
@@ -410,6 +598,12 @@ function _requestH1(transport, u, opts) {
410
598
  });
411
599
  if (res.statusCode >= 200 && res.statusCode < 300) {
412
600
  _resolve({ statusCode: res.statusCode, headers: res.headers, body: buf });
601
+ } else if (opts._resolveOnRedirect && REDIRECT_STATUSES.has(res.statusCode)) {
602
+ // Redirect-following layer needs the response object intact so
603
+ // it can inspect Location and re-issue. The caller-facing
604
+ // request() never sets _resolveOnRedirect — operator code that
605
+ // didn't ask for redirect-following keeps seeing 3xx as errors.
606
+ _resolve({ statusCode: res.statusCode, headers: res.headers, body: buf });
413
607
  } else {
414
608
  var msg = "HTTP " + res.statusCode + ": " + buf.toString("utf8").slice(0, 500);
415
609
  _reject(_makeError(opts.errorClass, "HTTP_ERROR", msg,
package/lib/i18n.js CHANGED
@@ -385,12 +385,32 @@ function create(opts) {
385
385
  opts = opts || {};
386
386
  validateOpts(opts, [
387
387
  "defaultLocale", "locales", "fallbackLocale",
388
- "translations", "dir",
389
- "interpolation", "missingKey", "rtlLanguages",
388
+ "translations", "dir", "eagerLocales", "lazyLoad",
389
+ "interpolation", "missingKey", "onMissingKey", "rtlLanguages",
390
390
  "observability", "clock",
391
391
  ], "b.i18n");
392
392
  _validateCreateOpts(opts);
393
393
 
394
+ if (opts.lazyLoad === true && opts.translations) {
395
+ throw _err("BAD_OPT", "i18n.create: lazyLoad: true requires dir-based loading; " +
396
+ "translations: { ... } is inline-only and already complete at create time");
397
+ }
398
+ if (opts.eagerLocales !== undefined) {
399
+ if (!Array.isArray(opts.eagerLocales)) {
400
+ throw _err("BAD_OPT", "i18n.create: eagerLocales must be an array of BCP 47 tags");
401
+ }
402
+ for (var ei = 0; ei < opts.eagerLocales.length; ei++) {
403
+ _validateLocale("i18n.create: eagerLocales[" + ei + "]", opts.eagerLocales[ei]);
404
+ if (opts.locales.indexOf(opts.eagerLocales[ei]) === -1) {
405
+ throw _err("BAD_OPT", "i18n.create: eagerLocales[" + ei + "] '" +
406
+ opts.eagerLocales[ei] + "' must be in locales array");
407
+ }
408
+ }
409
+ }
410
+ if (opts.onMissingKey !== undefined && typeof opts.onMissingKey !== "function") {
411
+ throw _err("BAD_OPT", "i18n.create: onMissingKey must be a function (key, locale)");
412
+ }
413
+
394
414
  var defaultLocale = opts.defaultLocale;
395
415
  var locales = opts.locales.slice();
396
416
  var fallbackLocale = (opts.fallbackLocale === null) ? null
@@ -401,22 +421,54 @@ function create(opts) {
401
421
  var operatorObs = opts.observability || null;
402
422
 
403
423
  // Translations: either inline object or loaded from dir at create.
424
+ // With lazyLoad, only eager locales hit disk now; the rest load on
425
+ // first lookup that resolves to them.
404
426
  var translations;
427
+ var lazyLoadEnabled = false;
428
+ var lazyLoadDir = null;
429
+ var loadedSet = new Set();
405
430
  if (opts.dir) {
406
- translations = _loadFromDir(opts.dir, locales);
431
+ if (opts.lazyLoad === true) {
432
+ lazyLoadEnabled = true;
433
+ lazyLoadDir = opts.dir;
434
+ var eager = Array.isArray(opts.eagerLocales) && opts.eagerLocales.length > 0
435
+ ? opts.eagerLocales
436
+ : [defaultLocale];
437
+ translations = _loadFromDir(opts.dir, eager);
438
+ for (var ei2 = 0; ei2 < eager.length; ei2++) loadedSet.add(eager[ei2]);
439
+ } else {
440
+ translations = _loadFromDir(opts.dir, locales);
441
+ for (var ei3 = 0; ei3 < locales.length; ei3++) loadedSet.add(locales[ei3]);
442
+ }
407
443
  } else if (opts.translations) {
408
444
  translations = opts.translations;
445
+ for (var ei4 = 0; ei4 < locales.length; ei4++) {
446
+ if (translations[locales[ei4]]) loadedSet.add(locales[ei4]);
447
+ }
409
448
  } else {
410
449
  translations = {};
411
450
  }
451
+ var onMissingKey = opts.onMissingKey || null;
412
452
  // Validate translation trees up-front so plural-shape errors surface
413
- // at boot, not at the first request that hits the broken key.
453
+ // at boot, not at the first request that hits the broken key. Lazy
454
+ // locales validate on first load.
414
455
  for (var li = 0; li < locales.length; li++) {
415
456
  var loc = locales[li];
416
457
  if (translations[loc]) {
417
458
  _validateTranslationTree(loc, translations[loc], "");
418
459
  }
419
460
  }
461
+
462
+ function _ensureLocaleLoaded(locale) {
463
+ if (loadedSet.has(locale)) return;
464
+ if (!lazyLoadEnabled || !lazyLoadDir) return; // not configured for lazy
465
+ if (!localesSet.has(locale)) return; // unknown locale; lookup falls through
466
+ var loaded = _loadFromDir(lazyLoadDir, [locale]);
467
+ translations[locale] = loaded[locale];
468
+ _validateTranslationTree(locale, translations[locale], "");
469
+ loadedSet.add(locale);
470
+ _emitObs("i18n.lazyLoad", { locale: locale });
471
+ }
420
472
  var localesSet = new Set(locales);
421
473
  var currentLocale = defaultLocale;
422
474
 
@@ -493,6 +545,7 @@ function create(opts) {
493
545
  var chain = _localeChain(locale);
494
546
  for (var i = 0; i < chain.length; i++) {
495
547
  var loc = chain[i];
548
+ _ensureLocaleLoaded(loc);
496
549
  if (!translations[loc]) continue;
497
550
  var v = _resolveKey(translations[loc], key);
498
551
  if (v !== undefined) {
@@ -502,8 +555,20 @@ function create(opts) {
502
555
  return null;
503
556
  }
504
557
 
505
- function _selectPlural(node, count, locale) {
506
- var rules = _pluralRulesFor(locale);
558
+ // Ordinal-plural rules cache — separate from cardinal because Intl.PluralRules
559
+ // is type-fixed at construction.
560
+ var ordinalRulesByLocale = {};
561
+ function _ordinalRulesFor(locale) {
562
+ var r = ordinalRulesByLocale[locale];
563
+ if (!r) {
564
+ r = new Intl.PluralRules(locale, { type: "ordinal" });
565
+ ordinalRulesByLocale[locale] = r;
566
+ }
567
+ return r;
568
+ }
569
+
570
+ function _selectPlural(node, count, locale, ordinal) {
571
+ var rules = ordinal ? _ordinalRulesFor(locale) : _pluralRulesFor(locale);
507
572
  var category = rules.select(count);
508
573
  if (typeof node[category] === "string") return node[category];
509
574
  // Fallback within the entry: "other" was validated mandatory at load.
@@ -520,6 +585,10 @@ function create(opts) {
520
585
 
521
586
  if (!found) {
522
587
  _emitObs("i18n.missing", { locale: locale, key: key });
588
+ if (onMissingKey) {
589
+ try { onMissingKey(key, locale); }
590
+ catch (_e) { /* hook is best-effort; never break the request */ }
591
+ }
523
592
  if (callerOpts.default !== undefined) return callerOpts.default;
524
593
  if (typeof missingKeyPolicy === "function") {
525
594
  return missingKeyPolicy(key, locale);
@@ -540,7 +609,7 @@ function create(opts) {
540
609
  raw = found.value;
541
610
  } else if (_isPluralShape(found.value)) {
542
611
  var count = (vars && typeof vars.count === "number") ? vars.count : 0;
543
- raw = _selectPlural(found.value, count, found.foundIn);
612
+ raw = _selectPlural(found.value, count, found.foundIn, callerOpts.ordinal === true);
544
613
  } else {
545
614
  // Operator stored a nested tree at this key but called t() against
546
615
  // the namespace. Return the key-path as a missing-key signal.
@@ -560,6 +629,20 @@ function create(opts) {
560
629
  return t(key, merged, callerOpts);
561
630
  }
562
631
 
632
+ // to — ordinal-plural counterpart of tn. Selects from the entry using
633
+ // Intl.PluralRules({ type: "ordinal" }), so English keys
634
+ // { one: "{count}st", two: "{count}nd", few: "{count}rd", other: "{count}th" }
635
+ // resolve as "1st", "2nd", "3rd", "4th", "21st", etc.
636
+ function to(key, count, vars, callerOpts) {
637
+ if (typeof count !== "number" || !isFinite(count)) {
638
+ throw _err("BAD_INPUT", "i18n.to: count must be a finite number, got " +
639
+ (typeof count) + " " + JSON.stringify(count));
640
+ }
641
+ var merged = vars ? Object.assign({}, vars, { count: count }) : { count: count };
642
+ var withOrdinal = Object.assign({}, callerOpts || {}, { ordinal: true });
643
+ return t(key, merged, withOrdinal);
644
+ }
645
+
563
646
  function has(key, callerOpts) {
564
647
  callerOpts = callerOpts || {};
565
648
  if (typeof key !== "string" || key.length === 0) return false;
@@ -727,6 +810,11 @@ function create(opts) {
727
810
  if (c.locale === undefined) c.locale = resolvedLocale;
728
811
  return tn(key, count, vars, c);
729
812
  }
813
+ function reqTo(key, count, vars, callerOpts) {
814
+ var c = callerOpts ? Object.assign({}, callerOpts) : {};
815
+ if (c.locale === undefined) c.locale = resolvedLocale;
816
+ return to(key, count, vars, c);
817
+ }
730
818
  function reqDir() {
731
819
  return dir({ locale: resolvedLocale });
732
820
  }
@@ -734,12 +822,14 @@ function create(opts) {
734
822
  req.locale = resolvedLocale;
735
823
  req.t = reqT;
736
824
  req.tn = reqTn;
825
+ req.to = reqTo;
737
826
  req.dir = reqDir;
738
827
  if (res && typeof res === "object") {
739
828
  if (!res.locals) res.locals = {};
740
829
  res.locals.locale = resolvedLocale;
741
830
  res.locals.t = reqT;
742
831
  res.locals.tn = reqTn;
832
+ res.locals.to = reqTo;
743
833
  res.locals.dir = reqDir();
744
834
  }
745
835
  } catch (_e) {
@@ -753,6 +843,7 @@ function create(opts) {
753
843
  return {
754
844
  t: t,
755
845
  tn: tn,
846
+ to: to,
756
847
  has: has,
757
848
  formatNumber: formatNumber,
758
849
  formatDate: formatDate,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",