tricache 1.0.1 → 1.0.2

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 (96) hide show
  1. package/README.md +36 -28
  2. package/dist/{cache-service-CREOp7MM.d.ts → cache-service-B108FzER.d.ts} +36 -4
  3. package/dist/cache-service-CWI4jkS7.d.cts +963 -0
  4. package/dist/{cache-service-MG7PN6MX.js → cache-service-GYPZFB7O.js} +2 -2
  5. package/dist/{chunk-IITRFWHY.js → chunk-EUKB7RKP.js} +21 -4
  6. package/dist/{chunk-2AJKEQMZ.js → chunk-H4GFLQ26.js} +7 -4
  7. package/dist/{chunk-7RV5ZVBB.js → chunk-JNSLMK4Q.js} +111 -29
  8. package/dist/chunk-OYDU3SMI.js +89 -0
  9. package/dist/{chunk-3I5L7K6I.js → chunk-VNRDL5RA.js} +102 -140
  10. package/dist/{chunk-JYQFQJNJ.js → chunk-WYF7NOAT.js} +1443 -609
  11. package/dist/cli.cjs +1367 -625
  12. package/dist/cli.d.cts +12 -0
  13. package/dist/cli.js +27 -6
  14. package/dist/dashboard/index.cjs +111 -29
  15. package/dist/dashboard/index.d.cts +185 -0
  16. package/dist/dashboard/index.d.ts +5 -3
  17. package/dist/dashboard/index.js +1 -1
  18. package/dist/drizzle/index.cjs +1370 -624
  19. package/dist/drizzle/index.d.cts +46 -0
  20. package/dist/drizzle/index.d.ts +2 -2
  21. package/dist/drizzle/index.js +1 -1
  22. package/dist/edge/index.cjs +227 -123
  23. package/dist/edge/index.d.cts +127 -0
  24. package/dist/edge/index.d.ts +3 -3
  25. package/dist/edge/index.js +201 -117
  26. package/dist/hono/index.cjs +1418 -644
  27. package/dist/hono/index.d.cts +93 -0
  28. package/dist/hono/index.d.ts +7 -5
  29. package/dist/hono/index.js +16 -9
  30. package/dist/{hono-DSV2ve66.d.ts → hono-3rDMYVtY.d.ts} +16 -3
  31. package/dist/hono-C886ok3X.d.cts +391 -0
  32. package/dist/http/index.cjs +1514 -679
  33. package/dist/http/index.d.cts +103 -0
  34. package/dist/http/index.d.ts +13 -5
  35. package/dist/http/index.js +92 -43
  36. package/dist/index.cjs +1671 -790
  37. package/dist/index.d.cts +1006 -0
  38. package/dist/index.d.ts +39 -8
  39. package/dist/index.js +8 -8
  40. package/dist/murmur3-CMGw9PbV.d.cts +98 -0
  41. package/dist/nestjs/index.cjs +1454 -649
  42. package/dist/nestjs/index.d.cts +285 -0
  43. package/dist/nestjs/index.d.ts +103 -30
  44. package/dist/nestjs/index.js +115 -32
  45. package/dist/next/index.cjs +1512 -718
  46. package/dist/next/index.d.cts +232 -0
  47. package/dist/next/index.d.ts +33 -11
  48. package/dist/next/index.js +172 -99
  49. package/dist/prisma/index.cjs +11 -1
  50. package/dist/prisma/index.d.cts +62 -0
  51. package/dist/prisma/index.d.ts +2 -2
  52. package/dist/prisma/index.js +11 -1
  53. package/dist/serialize-worker.d.cts +2 -0
  54. package/dist/{types-Dyip5wAl.d.ts → types-BA4pz1A0.d.cts} +24 -9
  55. package/dist/types-BA4pz1A0.d.ts +1519 -0
  56. package/dist/{utils-CEsU_Z0s.d.ts → utils-Bvzn-rKS.d.cts} +3 -1
  57. package/dist/utils-Bvzn-rKS.d.ts +29 -0
  58. package/package.json +96 -36
  59. package/src/adapters/auto-pipeliner.ts +107 -24
  60. package/src/adapters/node-redis.ts +106 -27
  61. package/src/cache-service.ts +802 -502
  62. package/src/cli.ts +24 -6
  63. package/src/cross-region.ts +21 -3
  64. package/src/dashboard/handler.ts +26 -6
  65. package/src/dashboard/html.ts +35 -10
  66. package/src/dashboard/index.ts +35 -13
  67. package/src/dashboard/types.ts +3 -1
  68. package/src/disk-tier.ts +171 -65
  69. package/src/edge/cache.ts +145 -97
  70. package/src/edge/hono.ts +23 -6
  71. package/src/edge/types.ts +2 -0
  72. package/src/hono/index.ts +19 -9
  73. package/src/http/express.ts +62 -17
  74. package/src/http/fastify.ts +35 -21
  75. package/src/http/utils.ts +54 -20
  76. package/src/ipc-telemetry.ts +35 -9
  77. package/src/nestjs/decorators.ts +1 -1
  78. package/src/nestjs/index.ts +2 -0
  79. package/src/nestjs/keyv-adapter.ts +68 -0
  80. package/src/nestjs/tricache.module.ts +13 -11
  81. package/src/nestjs/tricache.store.ts +51 -20
  82. package/src/nestjs/types.ts +29 -15
  83. package/src/next/cache-handler.ts +131 -53
  84. package/src/next/index.ts +1 -0
  85. package/src/next/types.ts +21 -0
  86. package/src/prisma/index.ts +12 -1
  87. package/src/smart-memory-cache.ts +63 -26
  88. package/src/types.ts +25 -2
  89. package/src/utils/cgroup.ts +12 -0
  90. package/src/utils/deadline.ts +14 -0
  91. package/src/utils/diagnostics.ts +27 -0
  92. package/src/utils/redis-slot.ts +13 -0
  93. package/src/wasm/bloom-filter-wasm.ts +9 -4
  94. package/src/worker-pool.ts +17 -8
  95. package/src/wtiny-lfu.ts +20 -6
  96. package/dist/chunk-BQRURGGD.js +0 -60
package/dist/cli.d.cts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * TriCache CLI — Developer & Troubleshooting Inspector
3
+ *
4
+ * Usage:
5
+ * npx tricache top [--socket <path>] [--pid <pid>] [--interval <ms>] [--once]
6
+ * npx tricache inspect [--redis redis://localhost:6379] [--namespace <ns>]
7
+ * npx tricache ping [--redis redis://localhost:6379]
8
+ * npx tricache clear [--redis redis://localhost:6379] [--namespace <ns>] [--prefix <prefix>]
9
+ */
10
+ declare function runCli(args?: string[]): Promise<void>;
11
+
12
+ export { runCli };
package/dist/cli.js CHANGED
@@ -4,13 +4,14 @@ import {
4
4
  findActiveSockets,
5
5
  renderTopDashboard,
6
6
  resolveIpcSocketPath
7
- } from "./chunk-JYQFQJNJ.js";
7
+ } from "./chunk-WYF7NOAT.js";
8
8
  import "./chunk-UBWLPKTI.js";
9
- import "./chunk-2AJKEQMZ.js";
9
+ import "./chunk-H4GFLQ26.js";
10
10
 
11
11
  // src/cli.ts
12
12
  import { readFileSync } from "fs";
13
13
  import { parseArgs } from "util";
14
+ import { Redis } from "ioredis";
14
15
  async function runCli(args = process.argv.slice(2)) {
15
16
  const options = {
16
17
  redis: { type: "string", short: "r" },
@@ -47,7 +48,7 @@ async function runCli(args = process.argv.slice(2)) {
47
48
  return;
48
49
  }
49
50
  if (values.version || command === "version") {
50
- let version = "1.0.1";
51
+ let version = "1.0.2";
51
52
  try {
52
53
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
53
54
  if (pkg?.version) version = pkg.version;
@@ -150,16 +151,35 @@ Press "q" or Ctrl+C to exit
150
151
  return;
151
152
  }
152
153
  const redisStr = typeof values.redis === "string" ? values.redis : void 0;
153
- const redisHost = redisStr ? redisStr.replace(/^redis:\/\//, "").split(":")[0] : void 0;
154
- const redisPort = typeof values.port === "string" ? parseInt(values.port, 10) : redisStr && redisStr.includes(":") ? parseInt(redisStr.split(":")[1], 10) : 6379;
154
+ let redisHost;
155
+ let redisPort = 6379;
156
+ let redisClient;
157
+ if (redisStr) {
158
+ try {
159
+ const url = new URL(redisStr.includes("://") ? redisStr : `redis://${redisStr}`);
160
+ if (url.protocol !== "redis:" && url.protocol !== "rediss:") throw new Error("Unsupported Redis URL scheme");
161
+ redisPort = Number(typeof values.port === "string" ? values.port : url.port || 6379);
162
+ if (!Number.isInteger(redisPort) || redisPort < 1 || redisPort > 65535) throw new Error("Invalid Redis port");
163
+ url.port = String(redisPort);
164
+ redisHost = url.hostname;
165
+ redisClient = new Redis(url.toString(), { lazyConnect: true, commandTimeout: 2500, maxRetriesPerRequest: 1 });
166
+ redisClient.on("error", () => {
167
+ });
168
+ } catch {
169
+ console.error("Invalid Redis host, URL, or port");
170
+ process.exitCode = 1;
171
+ return;
172
+ }
173
+ }
155
174
  const namespace = typeof values.namespace === "string" ? values.namespace : void 0;
156
175
  const diskCacheDir = typeof values.disk === "string" ? values.disk : void 0;
157
176
  const cache = new CacheService({
158
177
  redisHost,
159
178
  redisPort,
179
+ redisClient,
160
180
  namespace,
161
181
  diskCacheDir,
162
- disableRedis: !redisHost
182
+ disableRedis: !redisClient
163
183
  });
164
184
  try {
165
185
  if (command === "inspect") {
@@ -211,6 +231,7 @@ Press "q" or Ctrl+C to exit
211
231
  }
212
232
  } finally {
213
233
  await cache.destroy();
234
+ redisClient?.disconnect();
214
235
  }
215
236
  }
216
237
  function printHelp() {
@@ -329,7 +329,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
329
329
  <span class="pulse-dot"></span>
330
330
  <span id="stream-text">SSE Live</span>
331
331
  </div>
332
- <select id="peer-select" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
332
+ <select id="peer-select" aria-label="Switch cache instance" class="peer-select" style="display:none;" onchange="if(this.value) window.location.href=this.value;">
333
333
  <option value="">Switch Pod...</option>
334
334
  </select>
335
335
  </div>
@@ -389,9 +389,10 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
389
389
 
390
390
  <!-- Invalidate Modal -->
391
391
  <div class="dialog-overlay" id="invalidate-modal">
392
- <div class="dialog">
393
- <h3>Invalidate Tag</h3>
392
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="invalidate-title">
393
+ <h3 id="invalidate-title">Invalidate Tag</h3>
394
394
  <p>Increments generational tag version across local tiers and broadcast backplane.</p>
395
+ <label for="tag-input">Tag name or pattern</label>
395
396
  <input type="text" id="tag-input" placeholder="e.g. products, tenant-123" />
396
397
  <div class="dialog-actions">
397
398
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -402,8 +403,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
402
403
 
403
404
  <!-- Clear Modal -->
404
405
  <div class="dialog-overlay" id="clear-modal">
405
- <div class="dialog">
406
- <h3>Clear Cache</h3>
406
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="clear-title">
407
+ <h3 id="clear-title">Clear Cache</h3>
407
408
  <p>Evict all cached keys from the local L1 memory and NVMe disk tiers.</p>
408
409
  <div class="dialog-actions">
409
410
  <button class="btn" onclick="closeModals()">Cancel</button>
@@ -412,12 +413,20 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
412
413
  </div>
413
414
  </div>
414
415
 
415
- <div id="toast"></div>
416
+ <div id="toast" role="status" aria-live="polite"></div>
416
417
 
417
418
  <script>
418
419
  (function() {
419
420
  let isReadOnly = false;
420
421
  let sseFailed = false;
422
+ let previousFocus = null;
423
+ const token = new URLSearchParams(window.location.search).get('token');
424
+ const basePath = window.location.pathname.replace(/\\/index\\.html$/, '').replace(/\\/+$/, '');
425
+ function apiURL(path) {
426
+ const url = new URL(basePath + '/' + path, window.location.origin);
427
+ if (token) url.searchParams.set('token', token);
428
+ return url.toString();
429
+ }
421
430
 
422
431
  function showToast(msg, duration = 3000) {
423
432
  const t = document.getElementById('toast');
@@ -524,7 +533,8 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
524
533
  }
525
534
 
526
535
  window.fetchMetricsSnapshot = function() {
527
- fetch('api/metrics')
536
+ fetch(apiURL('api/metrics'))
537
+ .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r; })
528
538
  .then(r => r.json())
529
539
  .then(data => updateUI(data))
530
540
  .catch(err => showToast('Failed to fetch snapshot: ' + err.message));
@@ -535,7 +545,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
535
545
  fallbackPolling();
536
546
  return;
537
547
  }
538
- const sse = new EventSource('api/stream');
548
+ const sse = new EventSource(apiURL('api/stream'));
539
549
  sse.onmessage = function(e) {
540
550
  try {
541
551
  const data = JSON.parse(e.data);
@@ -560,22 +570,37 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
560
570
 
561
571
  window.openInvalidateModal = function() {
562
572
  if (isReadOnly) return;
573
+ previousFocus = document.activeElement;
563
574
  document.getElementById('invalidate-modal').classList.add('active');
564
575
  document.getElementById('tag-input').focus();
565
576
  };
566
577
  window.openClearModal = function() {
567
578
  if (isReadOnly) return;
579
+ previousFocus = document.activeElement;
568
580
  document.getElementById('clear-modal').classList.add('active');
581
+ document.querySelector('#clear-modal button').focus();
569
582
  };
570
583
  window.closeModals = function() {
571
584
  document.getElementById('invalidate-modal').classList.remove('active');
572
585
  document.getElementById('clear-modal').classList.remove('active');
586
+ if (previousFocus) previousFocus.focus();
573
587
  };
588
+ document.addEventListener('keydown', function(event) {
589
+ const modal = document.querySelector('.dialog-overlay.active');
590
+ if (!modal) return;
591
+ if (event.key === 'Escape') { event.preventDefault(); closeModals(); }
592
+ if (event.key === 'Tab') {
593
+ const controls = modal.querySelectorAll('button, input, select, [tabindex="0"]');
594
+ const first = controls[0], last = controls[controls.length - 1];
595
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
596
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
597
+ }
598
+ });
574
599
 
575
600
  window.submitTagInvalidation = function() {
576
601
  const tag = document.getElementById('tag-input').value.trim();
577
602
  if (!tag) return;
578
- fetch('api/actions/invalidate-tag', {
603
+ fetch(apiURL('api/actions/invalidate-tag'), {
579
604
  method: 'POST',
580
605
  headers: {
581
606
  'Content-Type': 'application/json',
@@ -598,7 +623,7 @@ var DASHBOARD_HTML = `<!DOCTYPE html>
598
623
  };
599
624
 
600
625
  window.submitClear = function() {
601
- fetch('api/actions/clear', {
626
+ fetch(apiURL('api/actions/clear'), {
602
627
  method: 'POST',
603
628
  headers: {
604
629
  'Content-Type': 'application/json',
@@ -638,7 +663,7 @@ var SECURITY_HEADERS = {
638
663
  "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'",
639
664
  "X-Frame-Options": "DENY",
640
665
  "X-Content-Type-Options": "nosniff",
641
- "Referrer-Policy": "same-origin",
666
+ "Referrer-Policy": "no-referrer",
642
667
  "Cache-Control": "no-store, no-cache, must-revalidate"
643
668
  };
644
669
  function resolveInstanceId(custom) {
@@ -657,7 +682,7 @@ function buildMetricsPayload(options) {
657
682
  title: options.title || "TriCache Observability",
658
683
  instanceId: resolveInstanceId(options.instanceId),
659
684
  nodeVersion: process.version,
660
- readOnly: !!options.readOnly,
685
+ readOnly: options.readOnly ?? true,
661
686
  peerInstances: options.peerInstances || [],
662
687
  metrics: {
663
688
  ...metrics,
@@ -763,6 +788,7 @@ async function handleDashboardRequest(req, options) {
763
788
  }
764
789
  ticker = setInterval(() => {
765
790
  try {
791
+ if ((controller.desiredSize ?? 0) <= 0) return;
766
792
  const data = buildMetricsPayload(options);
767
793
  controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}
768
794
 
@@ -785,7 +811,7 @@ async function handleDashboardRequest(req, options) {
785
811
  controller.close();
786
812
  } catch {
787
813
  }
788
- });
814
+ }, { once: true });
789
815
  }
790
816
  },
791
817
  cancel() {
@@ -817,7 +843,7 @@ async function handleDashboardRequest(req, options) {
817
843
  }
818
844
  if (pathname === "/api/actions/invalidate-tag" && req.method === "POST") {
819
845
  const clientIp = req.headers.get("x-forwarded-for") || void 0;
820
- if (options.readOnly) {
846
+ if (options.readOnly ?? true) {
821
847
  return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
822
848
  status: 403,
823
849
  headers: { "Content-Type": "application/json" }
@@ -830,7 +856,28 @@ async function handleDashboardRequest(req, options) {
830
856
  });
831
857
  }
832
858
  try {
833
- const body = await req.json();
859
+ const maxBytes = options.maxRequestBytes ?? 65536;
860
+ if (Number(req.headers.get("content-length")) > maxBytes) return new Response(JSON.stringify({ error: "Request body too large" }), { status: 413 });
861
+ const reader = req.body?.getReader();
862
+ const chunks = [];
863
+ let bytes = 0;
864
+ if (reader) {
865
+ try {
866
+ while (true) {
867
+ const chunk = await reader.read();
868
+ if (chunk.done) break;
869
+ bytes += chunk.value.length;
870
+ if (bytes > maxBytes) {
871
+ await reader.cancel();
872
+ return new Response(JSON.stringify({ error: "Request body too large" }), { status: 413 });
873
+ }
874
+ chunks.push(chunk.value);
875
+ }
876
+ } finally {
877
+ reader.releaseLock();
878
+ }
879
+ }
880
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
834
881
  const tag = body?.tag?.trim();
835
882
  if (!tag) {
836
883
  return new Response(JSON.stringify({ ok: false, error: "Tag parameter is required" }), {
@@ -869,7 +916,7 @@ async function handleDashboardRequest(req, options) {
869
916
  }
870
917
  if (pathname === "/api/actions/clear" && req.method === "POST") {
871
918
  const clientIp = req.headers.get("x-forwarded-for") || void 0;
872
- if (options.readOnly) {
919
+ if (options.readOnly ?? true) {
873
920
  return new Response(JSON.stringify({ ok: false, error: "Dashboard is in read-only mode" }), {
874
921
  status: 403,
875
922
  headers: { "Content-Type": "application/json" }
@@ -938,7 +985,7 @@ async function handleDashboardRequest(req, options) {
938
985
  }
939
986
 
940
987
  // src/dashboard/index.ts
941
- async function nodeToWebRequest(req) {
988
+ async function nodeToWebRequest(req, res, maxBytes) {
942
989
  const protocol = req.socket.encrypted ? "https" : "http";
943
990
  const host = req.headers.host || "localhost";
944
991
  const url = new URL(req.url || "/", `${protocol}://${host}`);
@@ -954,19 +1001,23 @@ async function nodeToWebRequest(req) {
954
1001
  let body = null;
955
1002
  if (req.method !== "GET" && req.method !== "HEAD") {
956
1003
  const chunks = [];
957
- for await (const chunk of req) {
958
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
1004
+ let size = 0;
1005
+ const parsed = req.body;
1006
+ if (req.readableEnded && parsed !== void 0) chunks.push(Buffer.from(JSON.stringify(parsed)));
1007
+ else for await (const chunk of req) {
1008
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
1009
+ size += bytes.length;
1010
+ if (size > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
1011
+ chunks.push(bytes);
959
1012
  }
960
1013
  if (chunks.length > 0) {
961
1014
  body = Buffer.concat(chunks);
1015
+ if (body.length > maxBytes) throw Object.assign(new Error("Request body exceeds dashboard limit"), { status: 413 });
962
1016
  }
963
1017
  }
964
1018
  const controller = new AbortController();
965
- req.on("close", () => {
966
- if (req.destroyed || !req.complete) {
967
- controller.abort();
968
- }
969
- });
1019
+ req.once("aborted", () => controller.abort());
1020
+ res.once("close", () => controller.abort());
970
1021
  const init = {
971
1022
  method: req.method,
972
1023
  headers,
@@ -988,24 +1039,54 @@ async function pipeWebResponseToNode(webRes, nodeRes) {
988
1039
  return;
989
1040
  }
990
1041
  const reader = webRes.body.getReader();
1042
+ const cancel = () => {
1043
+ void reader.cancel().catch(() => {
1044
+ });
1045
+ };
1046
+ nodeRes.once("close", cancel);
991
1047
  try {
992
1048
  while (true) {
993
1049
  const { done, value } = await reader.read();
994
1050
  if (done) break;
995
- nodeRes.write(value);
1051
+ if (nodeRes.destroyed) break;
1052
+ if (!nodeRes.write(value)) await new Promise((resolve, reject) => {
1053
+ const cleanup = () => {
1054
+ nodeRes.off("drain", onDrain);
1055
+ nodeRes.off("close", onClose);
1056
+ };
1057
+ const onDrain = () => {
1058
+ cleanup();
1059
+ resolve();
1060
+ };
1061
+ const onClose = () => {
1062
+ cleanup();
1063
+ reject(new Error("Dashboard response closed"));
1064
+ };
1065
+ nodeRes.once("drain", onDrain);
1066
+ nodeRes.once("close", onClose);
1067
+ });
996
1068
  }
997
1069
  } finally {
998
- nodeRes.end();
1070
+ nodeRes.off("close", cancel);
1071
+ await reader.cancel().catch(() => {
1072
+ });
1073
+ reader.releaseLock();
1074
+ if (!nodeRes.destroyed) nodeRes.end();
999
1075
  }
1000
1076
  }
1001
1077
  function tricacheDashboard(options) {
1002
1078
  return async (req, res, next) => {
1003
1079
  try {
1004
- const webReq = await nodeToWebRequest(req);
1080
+ const webReq = await nodeToWebRequest(req, res, options.maxRequestBytes ?? 65536);
1005
1081
  const webRes = await handleDashboardRequest(webReq, options);
1006
1082
  await pipeWebResponseToNode(webRes, res);
1007
1083
  } catch (err) {
1008
- if (typeof next === "function") {
1084
+ if (res.destroyed) return;
1085
+ if (err.status === 413) {
1086
+ res.statusCode = 413;
1087
+ res.setHeader("Connection", "close");
1088
+ res.end(JSON.stringify({ error: "Request body too large" }));
1089
+ } else if (typeof next === "function") {
1009
1090
  next(err);
1010
1091
  } else {
1011
1092
  res.statusCode = 500;
@@ -1024,7 +1105,7 @@ function createNextDashboardHandlers(options) {
1024
1105
  };
1025
1106
  }
1026
1107
  async function startDashboardServer(options) {
1027
- const port = options.port || 9090;
1108
+ const port = options.port ?? 9090;
1028
1109
  const host = options.host || "127.0.0.1";
1029
1110
  const middleware = tricacheDashboard(options);
1030
1111
  const server = import_node_http.default.createServer((req, res) => {
@@ -1048,6 +1129,7 @@ async function startDashboardServer(options) {
1048
1129
  host,
1049
1130
  close: () => new Promise((resolve, reject) => {
1050
1131
  server.close((err) => err ? reject(err) : resolve());
1132
+ server.closeAllConnections();
1051
1133
  })
1052
1134
  };
1053
1135
  }
@@ -0,0 +1,185 @@
1
+ import http, { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { C as CacheService } from '../cache-service-CWI4jkS7.cjs';
3
+ import '../types-BA4pz1A0.cjs';
4
+ import 'crypto';
5
+
6
+ interface DashboardPeerInstance {
7
+ name: string;
8
+ url: string;
9
+ }
10
+ interface DashboardActionEvent {
11
+ action: 'clear' | 'invalidate-tag';
12
+ target?: string;
13
+ user?: string;
14
+ ip?: string;
15
+ timestamp: number;
16
+ success: boolean;
17
+ error?: string;
18
+ }
19
+ interface DashboardOptions {
20
+ /**
21
+ * TriCache instance to monitor and manage.
22
+ */
23
+ cache: CacheService;
24
+ /**
25
+ * Base mounting path for the dashboard (e.g. '/cache/dashboard' or '/admin/cache').
26
+ * Used for generating relative links and API request paths.
27
+ * @default ''
28
+ */
29
+ basePath?: string;
30
+ /**
31
+ * Custom title displayed in the browser tab and dashboard header.
32
+ * @default 'TriCache Observability'
33
+ */
34
+ title?: string;
35
+ /**
36
+ * Identifier for the local container/pod/process.
37
+ * Defaults to process.env.POD_NAME, process.env.HOSTNAME, or os.hostname().
38
+ */
39
+ instanceId?: string;
40
+ /**
41
+ * Optional list of sibling peer instance URLs for pod switching in multi-pod clusters.
42
+ */
43
+ peerInstances?: DashboardPeerInstance[];
44
+ /**
45
+ * HTTP Basic Authentication credentials.
46
+ * Evaluated using timing-safe comparison (crypto.timingSafeEqual with SHA-256).
47
+ */
48
+ auth?: {
49
+ username: string;
50
+ password: string;
51
+ };
52
+ /**
53
+ * Bearer token or URL token query parameter ('?token=...') for API authentication.
54
+ * Evaluated using timing-safe comparison.
55
+ */
56
+ authSecret?: string;
57
+ /**
58
+ * Enforces read-only mode: disables and blocks all mutating operations
59
+ * (e.g. invalidate tag, clear cache tier). Mutating endpoints return 403 Forbidden.
60
+ * @default true
61
+ */
62
+ readOnly?: boolean;
63
+ /**
64
+ * Server-Sent Events (SSE) metric stream push interval in milliseconds.
65
+ * @default 2000
66
+ */
67
+ streamIntervalMs?: number;
68
+ /** Maximum administrative request body size. Default: 64 KiB. */
69
+ maxRequestBytes?: number;
70
+ /**
71
+ * Enterprise audit logging hook invoked when an administrative action is attempted.
72
+ * Allows piping security/audit events to Datadog, CloudWatch, Splunk, etc.
73
+ */
74
+ onAction?: (event: DashboardActionEvent) => void;
75
+ }
76
+ interface StandaloneDashboardOptions extends DashboardOptions {
77
+ /**
78
+ * Port to listen on.
79
+ * @default 9090
80
+ */
81
+ port?: number;
82
+ /**
83
+ * Host / IP interface to bind. Defaults to '127.0.0.1' for security.
84
+ * Use '0.0.0.0' only inside private VPCs or behind authenticated reverse proxies.
85
+ * @default '127.0.0.1'
86
+ */
87
+ host?: string;
88
+ }
89
+
90
+ /**
91
+ * Timing-safe string comparison routine using SHA-256 digests to neutralize
92
+ * both length-leakage side-channels and buffer-length mismatch exceptions.
93
+ */
94
+ declare function safeCompare(a: string, b: string): boolean;
95
+ /**
96
+ * Resolve local instance/pod identifier from options or environment.
97
+ */
98
+ declare function resolveInstanceId(custom?: string): string;
99
+ /**
100
+ * Build the JSON snapshot payload for /api/metrics and SSE stream events.
101
+ */
102
+ declare function buildMetricsPayload(options: DashboardOptions): Record<string, unknown>;
103
+ /**
104
+ * Framework-agnostic Web Standards request handler for the TriCache dashboard.
105
+ * Accepts a Web Standard Request and returns a Web Standard Response.
106
+ */
107
+ declare function handleDashboardRequest(req: Request, options: DashboardOptions): Promise<Response>;
108
+
109
+ /**
110
+ * Embedded Single-Page Observability Dashboard for TriCache.
111
+ *
112
+ * Design features:
113
+ * - 100% self-contained & air-gapped (zero external CDN or font dependencies)
114
+ * - Modern dark glassmorphic UI with high contrast and smooth micro-animations
115
+ * - Server-Sent Events (SSE) live streaming with auto-reconnect and polling fallback
116
+ * - Pod vs. Fleet cluster awareness indicators
117
+ * - Immutable HTML pre-compressed with Gzip at module initialization
118
+ */
119
+ declare const DASHBOARD_HTML: string;
120
+ /**
121
+ * Pre-compressed Gzip binary representation of the immutable dashboard HTML.
122
+ * Served directly with Content-Encoding: gzip to minimize latency and CPU overhead.
123
+ */
124
+ declare const DASHBOARD_GZIP_BUFFER: Buffer;
125
+
126
+ /**
127
+ * Connect/Express/Fastify middleware adapter for the TriCache observability dashboard.
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * import { tricacheDashboard } from 'tricache/dashboard';
132
+ *
133
+ * app.use('/admin/cache', tricacheDashboard({
134
+ * cache,
135
+ * auth: { username: 'admin', password: process.env.DASHBOARD_PASSWORD },
136
+ * readOnly: process.env.NODE_ENV === 'production',
137
+ * }));
138
+ * ```
139
+ */
140
+ declare function tricacheDashboard(options: DashboardOptions): (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => Promise<void>;
141
+ /**
142
+ * Next.js App Router route handlers for the TriCache dashboard.
143
+ *
144
+ * @example
145
+ * ```typescript
146
+ * // app/admin/cache/[...slug]/route.ts
147
+ * import { createNextDashboardHandlers } from 'tricache/dashboard';
148
+ * import { cache } from '@/lib/cache';
149
+ *
150
+ * export const { GET, POST } = createNextDashboardHandlers({
151
+ * cache,
152
+ * basePath: '/admin/cache',
153
+ * readOnly: true,
154
+ * });
155
+ * ```
156
+ */
157
+ declare function createNextDashboardHandlers(options: DashboardOptions): {
158
+ GET: (req: Request) => Promise<Response>;
159
+ POST: (req: Request) => Promise<Response>;
160
+ };
161
+ /**
162
+ * Starts a standalone, dedicated HTTP management server for the TriCache dashboard.
163
+ * Ideal for microservices, background workers, and Kubernetes pods via `kubectl port-forward`.
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * import { startDashboardServer } from 'tricache/dashboard';
168
+ *
169
+ * const mgmt = await startDashboardServer({
170
+ * cache,
171
+ * port: 9090,
172
+ * host: '127.0.0.1',
173
+ * authSecret: process.env.MANAGEMENT_SECRET,
174
+ * });
175
+ * console.log(`Observability dashboard running at http://localhost:${mgmt.port}`);
176
+ * ```
177
+ */
178
+ declare function startDashboardServer(options: StandaloneDashboardOptions): Promise<{
179
+ server: http.Server;
180
+ port: number;
181
+ host: string;
182
+ close: () => Promise<void>;
183
+ }>;
184
+
185
+ export { DASHBOARD_GZIP_BUFFER, DASHBOARD_HTML, type DashboardActionEvent, type DashboardOptions, type DashboardPeerInstance, type StandaloneDashboardOptions, buildMetricsPayload, createNextDashboardHandlers, handleDashboardRequest, resolveInstanceId, safeCompare, startDashboardServer, tricacheDashboard };
@@ -1,6 +1,6 @@
1
1
  import http, { IncomingMessage, ServerResponse } from 'node:http';
2
- import { C as CacheService } from '../cache-service-CREOp7MM.js';
3
- import '../types-Dyip5wAl.js';
2
+ import { C as CacheService } from '../cache-service-B108FzER.js';
3
+ import '../types-BA4pz1A0.js';
4
4
  import 'crypto';
5
5
 
6
6
  interface DashboardPeerInstance {
@@ -57,7 +57,7 @@ interface DashboardOptions {
57
57
  /**
58
58
  * Enforces read-only mode: disables and blocks all mutating operations
59
59
  * (e.g. invalidate tag, clear cache tier). Mutating endpoints return 403 Forbidden.
60
- * @default false
60
+ * @default true
61
61
  */
62
62
  readOnly?: boolean;
63
63
  /**
@@ -65,6 +65,8 @@ interface DashboardOptions {
65
65
  * @default 2000
66
66
  */
67
67
  streamIntervalMs?: number;
68
+ /** Maximum administrative request body size. Default: 64 KiB. */
69
+ maxRequestBytes?: number;
68
70
  /**
69
71
  * Enterprise audit logging hook invoked when an administrative action is attempted.
70
72
  * Allows piping security/audit events to Datadog, CloudWatch, Splunk, etc.
@@ -8,7 +8,7 @@ import {
8
8
  safeCompare,
9
9
  startDashboardServer,
10
10
  tricacheDashboard
11
- } from "../chunk-7RV5ZVBB.js";
11
+ } from "../chunk-JNSLMK4Q.js";
12
12
  export {
13
13
  DASHBOARD_GZIP_BUFFER,
14
14
  DASHBOARD_HTML,