express-file-cluster 0.11.0 → 0.12.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 (139) hide show
  1. package/dist/auth/index.cjs +8 -7
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +7 -5
  6. package/dist/{chunk-JBOMTZT5.js → chunk-3JQWQF2M.js} +3 -3
  7. package/dist/chunk-3ROVNEDR.js +20 -0
  8. package/dist/chunk-3ROVNEDR.js.map +1 -0
  9. package/dist/{chunk-WHBSVYUY.cjs → chunk-4FQP6QX3.cjs} +3 -3
  10. package/dist/{chunk-WHBSVYUY.cjs.map → chunk-4FQP6QX3.cjs.map} +1 -1
  11. package/dist/chunk-546TNO2V.js +226 -0
  12. package/dist/chunk-546TNO2V.js.map +1 -0
  13. package/dist/{chunk-EJDZZ4KX.js → chunk-74R37C4I.js} +48 -21
  14. package/dist/chunk-74R37C4I.js.map +1 -0
  15. package/dist/{chunk-H2PVWCWC.cjs → chunk-A2QGDWCG.cjs} +15 -8
  16. package/dist/chunk-A2QGDWCG.cjs.map +1 -0
  17. package/dist/{chunk-DGYPIIJE.cjs → chunk-AG7PVYPE.cjs} +90 -64
  18. package/dist/chunk-AG7PVYPE.cjs.map +1 -0
  19. package/dist/{chunk-O2E7H2XA.js → chunk-BCSJOPYH.js} +2 -2
  20. package/dist/{chunk-OM2XJJWX.js → chunk-EBJELA7T.js} +30 -25
  21. package/dist/chunk-EBJELA7T.js.map +1 -0
  22. package/dist/{chunk-IEF6AEK3.cjs → chunk-H6MHRHUP.cjs} +104 -50
  23. package/dist/chunk-H6MHRHUP.cjs.map +1 -0
  24. package/dist/chunk-I2IVJURJ.cjs +20 -0
  25. package/dist/chunk-I2IVJURJ.cjs.map +1 -0
  26. package/dist/{chunk-6WTMRZS7.cjs → chunk-IG3V2IOK.cjs} +57 -30
  27. package/dist/chunk-IG3V2IOK.cjs.map +1 -0
  28. package/dist/chunk-JAPZYQVJ.cjs +143 -0
  29. package/dist/chunk-JAPZYQVJ.cjs.map +1 -0
  30. package/dist/{chunk-QSIP7YLW.cjs → chunk-JHCXIYJH.cjs} +25 -48
  31. package/dist/chunk-JHCXIYJH.cjs.map +1 -0
  32. package/dist/{chunk-GWMW6XY7.cjs → chunk-JVB5NLEM.cjs} +15 -13
  33. package/dist/chunk-JVB5NLEM.cjs.map +1 -0
  34. package/dist/chunk-PUM5ZDAH.js +140 -0
  35. package/dist/chunk-PUM5ZDAH.js.map +1 -0
  36. package/dist/{chunk-CGY7JU4Y.cjs → chunk-PUYBKDYD.cjs} +11 -2
  37. package/dist/chunk-PUYBKDYD.cjs.map +1 -0
  38. package/dist/{chunk-336IU55W.js → chunk-QLM3JEER.js} +5 -3
  39. package/dist/{chunk-336IU55W.js.map → chunk-QLM3JEER.js.map} +1 -1
  40. package/dist/{chunk-SOU3PBJC.cjs → chunk-SV4C4HWP.cjs} +89 -89
  41. package/dist/{chunk-SOU3PBJC.cjs.map → chunk-SV4C4HWP.cjs.map} +1 -1
  42. package/dist/{chunk-2IDRC7RK.js → chunk-UJ2ISRLP.js} +11 -34
  43. package/dist/chunk-UJ2ISRLP.js.map +1 -0
  44. package/dist/chunk-URKE3OXN.cjs +226 -0
  45. package/dist/chunk-URKE3OXN.cjs.map +1 -0
  46. package/dist/{chunk-DTMDJGRW.cjs → chunk-VLGN3XUM.cjs} +40 -35
  47. package/dist/chunk-VLGN3XUM.cjs.map +1 -0
  48. package/dist/{chunk-R6GPQZLI.js → chunk-X2B7WBKH.js} +88 -34
  49. package/dist/chunk-X2B7WBKH.js.map +1 -0
  50. package/dist/chunk-Y7I2633P.js +12 -0
  51. package/dist/chunk-Y7I2633P.js.map +1 -0
  52. package/dist/{chunk-B6MB6HEG.js → chunk-ZBQUYFI3.js} +14 -7
  53. package/dist/chunk-ZBQUYFI3.js.map +1 -0
  54. package/dist/{chunk-LECHRAU3.js → chunk-ZU2GK5WY.js} +84 -58
  55. package/dist/chunk-ZU2GK5WY.js.map +1 -0
  56. package/dist/cli/db-runner.cjs +26 -25
  57. package/dist/cli/db-runner.cjs.map +1 -1
  58. package/dist/cli/db-runner.js +5 -3
  59. package/dist/cli/db-runner.js.map +1 -1
  60. package/dist/cli/index.cjs +20 -16
  61. package/dist/cli/index.cjs.map +1 -1
  62. package/dist/cli/index.js +13 -8
  63. package/dist/cli/index.js.map +1 -1
  64. package/dist/docs/api-reference/auth.md +2 -0
  65. package/dist/docs/api-reference/ignite.md +4 -0
  66. package/dist/docs/api-reference/tasks.md +6 -2
  67. package/dist/docs/api-reference/testing.md +2 -0
  68. package/dist/docs/api-reference/tracing.md +18 -0
  69. package/dist/docs/cli/add.md +1 -1
  70. package/dist/docs/cli/diagnostics.md +1 -1
  71. package/dist/docs/cli/index.md +1 -1
  72. package/dist/docs/core-concepts/background-tasks.md +7 -1
  73. package/dist/docs/core-concepts/file-based-routing.md +4 -0
  74. package/dist/docs/core-concepts/middleware.md +2 -0
  75. package/dist/docs/guides/caching.md +12 -0
  76. package/dist/docs/guides/error-handling.md +2 -0
  77. package/dist/docs/guides/feature-matrix.md +7 -0
  78. package/dist/docs/guides/logging.md +2 -0
  79. package/dist/docs/guides/tracing.md +64 -0
  80. package/dist/docs/index.md +2 -1
  81. package/dist/docs/skills/SKILL.md +5 -3
  82. package/dist/docs/skills/api-surface.md +8 -0
  83. package/dist/docs/skills/auth-internals.md +4 -2
  84. package/dist/docs/skills/pre-flight.md +4 -0
  85. package/dist/docs/skills/routing-rules.md +3 -1
  86. package/dist/docs/skills/tasks-internals.md +12 -4
  87. package/dist/docs/skills/what-not-to-invent.md +2 -0
  88. package/dist/index.cjs +167 -71
  89. package/dist/index.cjs.map +1 -1
  90. package/dist/index.d.cts +5 -14
  91. package/dist/index.d.ts +5 -14
  92. package/dist/index.js +124 -27
  93. package/dist/index.js.map +1 -1
  94. package/dist/pgboss-backend-5DXF4G22.js +16 -0
  95. package/dist/pgboss-backend-KRTFHRNZ.cjs +16 -0
  96. package/dist/pgboss-backend-KRTFHRNZ.cjs.map +1 -0
  97. package/dist/registry/index.json +1 -1
  98. package/dist/tasks/index.cjs +3 -3
  99. package/dist/tasks/index.d.cts +2 -2
  100. package/dist/tasks/index.d.ts +2 -2
  101. package/dist/tasks/index.js +2 -1
  102. package/dist/testing.cjs +16 -14
  103. package/dist/testing.cjs.map +1 -1
  104. package/dist/testing.d.cts +2 -1
  105. package/dist/testing.d.ts +2 -1
  106. package/dist/testing.js +10 -7
  107. package/dist/testing.js.map +1 -1
  108. package/dist/thread-runner.cjs +5 -4
  109. package/dist/thread-runner.cjs.map +1 -1
  110. package/dist/thread-runner.d.cts +1 -1
  111. package/dist/thread-runner.d.ts +1 -1
  112. package/dist/thread-runner.js +4 -2
  113. package/dist/{types-D3QmZgeX.d.ts → types-Bgeqpm-n.d.cts} +12 -1
  114. package/dist/{types-D3QmZgeX.d.cts → types-Bgeqpm-n.d.ts} +12 -1
  115. package/package.json +7 -3
  116. package/dist/chunk-2IDRC7RK.js.map +0 -1
  117. package/dist/chunk-3SWI46YK.js +0 -74
  118. package/dist/chunk-3SWI46YK.js.map +0 -1
  119. package/dist/chunk-6WTMRZS7.cjs.map +0 -1
  120. package/dist/chunk-B6MB6HEG.js.map +0 -1
  121. package/dist/chunk-CGY7JU4Y.cjs.map +0 -1
  122. package/dist/chunk-DGYPIIJE.cjs.map +0 -1
  123. package/dist/chunk-DTMDJGRW.cjs.map +0 -1
  124. package/dist/chunk-EJDZZ4KX.js.map +0 -1
  125. package/dist/chunk-GWMW6XY7.cjs.map +0 -1
  126. package/dist/chunk-H2PVWCWC.cjs.map +0 -1
  127. package/dist/chunk-IEF6AEK3.cjs.map +0 -1
  128. package/dist/chunk-LECHRAU3.js.map +0 -1
  129. package/dist/chunk-OM2XJJWX.js.map +0 -1
  130. package/dist/chunk-QSIP7YLW.cjs.map +0 -1
  131. package/dist/chunk-R6GPQZLI.js.map +0 -1
  132. package/dist/chunk-RPL2IFWK.cjs +0 -77
  133. package/dist/chunk-RPL2IFWK.cjs.map +0 -1
  134. package/dist/pgboss-backend-PQW6I3VF.js +0 -14
  135. package/dist/pgboss-backend-QVXISTLP.cjs +0 -15
  136. package/dist/pgboss-backend-QVXISTLP.cjs.map +0 -1
  137. /package/dist/{chunk-JBOMTZT5.js.map → chunk-3JQWQF2M.js.map} +0 -0
  138. /package/dist/{chunk-O2E7H2XA.js.map → chunk-BCSJOPYH.js.map} +0 -0
  139. /package/dist/{pgboss-backend-PQW6I3VF.js.map → pgboss-backend-5DXF4G22.js.map} +0 -0
package/dist/index.cjs CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkDGYPIIJEcjs = require('./chunk-DGYPIIJE.cjs');
9
+ var _chunkAG7PVYPEcjs = require('./chunk-AG7PVYPE.cjs');
10
10
 
11
11
 
12
12
 
@@ -15,16 +15,17 @@ var _chunkDGYPIIJEcjs = require('./chunk-DGYPIIJE.cjs');
15
15
 
16
16
 
17
17
 
18
- var _chunkIEF6AEK3cjs = require('./chunk-IEF6AEK3.cjs');
18
+ var _chunkH6MHRHUPcjs = require('./chunk-H6MHRHUP.cjs');
19
19
 
20
20
 
21
- var _chunkWHBSVYUYcjs = require('./chunk-WHBSVYUY.cjs');
21
+ var _chunkI2IVJURJcjs = require('./chunk-I2IVJURJ.cjs');
22
22
 
23
23
 
24
+ var _chunk4FQP6QX3cjs = require('./chunk-4FQP6QX3.cjs');
24
25
 
25
- var _chunkDTMDJGRWcjs = require('./chunk-DTMDJGRW.cjs');
26
26
 
27
27
 
28
+ var _chunkVLGN3XUMcjs = require('./chunk-VLGN3XUM.cjs');
28
29
 
29
30
 
30
31
 
@@ -32,12 +33,14 @@ var _chunkDTMDJGRWcjs = require('./chunk-DTMDJGRW.cjs');
32
33
 
33
34
 
34
35
 
35
- var _chunkSOU3PBJCcjs = require('./chunk-SOU3PBJC.cjs');
36
36
 
37
37
 
38
+ var _chunkSV4C4HWPcjs = require('./chunk-SV4C4HWP.cjs');
38
39
 
39
40
 
40
- var _chunkGWMW6XY7cjs = require('./chunk-GWMW6XY7.cjs');
41
+
42
+
43
+ var _chunkJVB5NLEMcjs = require('./chunk-JVB5NLEM.cjs');
41
44
 
42
45
 
43
46
 
@@ -45,24 +48,46 @@ var _chunkAGOYTFROcjs = require('./chunk-AGOYTFRO.cjs');
45
48
 
46
49
 
47
50
 
48
- var _chunk6WTMRZS7cjs = require('./chunk-6WTMRZS7.cjs');
49
- require('./chunk-RPL2IFWK.cjs');
51
+ var _chunkIG3V2IOKcjs = require('./chunk-IG3V2IOK.cjs');
52
+ require('./chunk-JAPZYQVJ.cjs');
53
+
54
+
55
+
56
+ var _chunkA2QGDWCGcjs = require('./chunk-A2QGDWCG.cjs');
50
57
 
51
58
 
52
59
 
53
- var _chunkH2PVWCWCcjs = require('./chunk-H2PVWCWC.cjs');
54
60
 
55
61
 
56
62
 
57
63
 
58
64
 
59
65
 
66
+ var _chunkJHCXIYJHcjs = require('./chunk-JHCXIYJH.cjs');
60
67
 
61
68
 
62
69
 
63
70
 
64
- var _chunkQSIP7YLWcjs = require('./chunk-QSIP7YLW.cjs');
65
- require('./chunk-CGY7JU4Y.cjs');
71
+ var _chunkURKE3OXNcjs = require('./chunk-URKE3OXN.cjs');
72
+ require('./chunk-PUYBKDYD.cjs');
73
+
74
+ // src/shutdown.ts
75
+ async function drainServices(options) {
76
+ const errors = [];
77
+ const outcomes = await Promise.allSettled([
78
+ ...options.transports,
79
+ ...options.tasks.map((close) => Promise.resolve().then(close))
80
+ ]);
81
+ for (const outcome of outcomes) if (outcome.status === "rejected") errors.push(outcome.reason);
82
+ for (const close of [options.cache, options.tracing]) {
83
+ try {
84
+ await close();
85
+ } catch (error) {
86
+ errors.push(error);
87
+ }
88
+ }
89
+ if (errors.length) throw new AggregateError(errors, "Service shutdown failed");
90
+ }
66
91
 
67
92
  // src/index.ts
68
93
  var _http = require('http'); var _http2 = _interopRequireDefault(_http);
@@ -80,7 +105,7 @@ function workerCount() {
80
105
  }
81
106
  function shutdownMaster() {
82
107
  isShuttingDown = true;
83
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers\u2026`);
108
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers\u2026`);
84
109
  if (workerCount() === 0) process.exit(0);
85
110
  for (const worker of Object.values(_nullishCoalesce(_cluster2.default.workers, () => ( {})))) {
86
111
  _optionalChain([worker, 'optionalAccess', _ => _.process, 'access', _2 => _2.kill, 'call', _3 => _3("SIGTERM")]);
@@ -88,7 +113,7 @@ function shutdownMaster() {
88
113
  }
89
114
  function runMaster(options = {}) {
90
115
  const count = _nullishCoalesce(options.workers, () => ( 1));
91
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`Primary ${process.pid} starting ${count} workers`);
116
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).info(`Primary ${process.pid} starting ${count} workers`);
92
117
  for (let i = 0; i < count; i++) {
93
118
  _cluster2.default.fork();
94
119
  }
@@ -98,14 +123,14 @@ function runMaster(options = {}) {
98
123
  _cluster2.default.on("exit", (worker, code, signal) => {
99
124
  const exitCode = _nullishCoalesce(code, () => ( (signal ? -1 : 0)));
100
125
  if (isShuttingDown) {
101
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`Worker ${worker.id} gracefully exited`);
126
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).info(`Worker ${worker.id} gracefully exited`);
102
127
  if (workerCount() === 0) {
103
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info("All workers exited. Primary exiting.");
128
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).info("All workers exited. Primary exiting.");
104
129
  process.exit(0);
105
130
  }
106
131
  return;
107
132
  }
108
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn(`Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
133
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).warn(`Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
109
134
  _optionalChain([options, 'access', _6 => _6.onWorkerCrash, 'optionalCall', _7 => _7(worker.id, exitCode)]);
110
135
  _cluster2.default.fork();
111
136
  });
@@ -116,7 +141,7 @@ function runMaster(options = {}) {
116
141
 
117
142
  async function scanTasks(tasksDir) {
118
143
  if (!_fs2.default.existsSync(tasksDir)) return;
119
- const files = _fs2.default.readdirSync(tasksDir).filter((f) => /\.(ts|js|mts|mjs)$/.test(f));
144
+ const files = _chunkI2IVJURJcjs.listTaskFiles.call(void 0, tasksDir);
120
145
  for (const file of files) {
121
146
  const filePath = _path2.default.join(tasksDir, file);
122
147
  const taskName = _path2.default.basename(file, _path2.default.extname(file));
@@ -124,13 +149,13 @@ async function scanTasks(tasksDir) {
124
149
  const mod = await Promise.resolve().then(() => _interopRequireWildcard(require(filePath)));
125
150
  const def = mod["default"];
126
151
  if (!def || typeof def.handler !== "function") {
127
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn(`Task file ${file} has no valid default export \u2014 skipping`);
152
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).warn(`Task file ${file} has no valid default export \u2014 skipping`);
128
153
  continue;
129
154
  }
130
- _chunkH2PVWCWCcjs.registerTask.call(void 0, taskName, { ...def, filePath });
131
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).debug(`Registered task: ${taskName}`);
155
+ _chunkA2QGDWCGcjs.registerTask.call(void 0, taskName, { ...def, filePath });
156
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).debug(`Registered task: ${taskName}`);
132
157
  } catch (err) {
133
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn({ err }, `Failed to load task ${file}`);
158
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).warn({ err }, `Failed to load task ${file}`);
134
159
  }
135
160
  }
136
161
  }
@@ -736,18 +761,19 @@ function generateDashboard(routes, basePath, port, projectName, projectVersion)
736
761
  // src/rate-limit.ts
737
762
  var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
738
763
  function parseWindow(window) {
739
- if (typeof window === "number") {
740
- if (window > 0) return window;
741
- } else {
742
- const m = /^(\d+(?:\.\d+)?)\s*(s|m|h|d)$/.exec(window.trim());
743
- if (m) return Number(m[1]) * UNITS[m[2]];
764
+ let seconds = typeof window === "number" ? window : NaN;
765
+ if (typeof window === "string") {
766
+ const match = /^(\d+(?:\.\d+)?)\s*(s|m|h|d)$/.exec(window.trim());
767
+ if (match) seconds = Number(match[1]) * UNITS[match[2]];
744
768
  }
769
+ if (Number.isFinite(seconds) && seconds * 1e3 >= 1 && seconds * 1e3 <= Number.MAX_SAFE_INTEGER)
770
+ return seconds;
745
771
  throw new Error(`[EFC] rateLimit: window must be seconds or like '15m' \u2014 got ${String(window)}`);
746
772
  }
747
773
  var lastCacheError = 0;
748
774
  function rateLimit(options) {
749
775
  const windowSeconds = parseWindow(options.window);
750
- if (!Number.isInteger(options.max) || options.max < 1) {
776
+ if (!Number.isSafeInteger(options.max) || options.max < 1) {
751
777
  throw new Error("[EFC] rateLimit: max must be a positive integer");
752
778
  }
753
779
  const keyOf = _nullishCoalesce(options.key, () => ( ((req) => _nullishCoalesce(req.ip, () => ( req.socket.remoteAddress)))));
@@ -757,7 +783,7 @@ function rateLimit(options) {
757
783
  void (async () => {
758
784
  const who = keyOf(req);
759
785
  if (who === void 0) return next();
760
- if (!_chunkIEF6AEK3cjs.isCacheConfigured.call(void 0, )) {
786
+ if (!_chunkH6MHRHUPcjs.isCacheConfigured.call(void 0, )) {
761
787
  throw new Error("[EFC] rateLimit needs a cache \u2014 pass cache: { backend } to ignite()");
762
788
  }
763
789
  const bucket = _nullishCoalesce(options.name, () => ( req.baseUrl + (_nullishCoalesce(_optionalChain([req, 'access', _8 => _8.route, 'optionalAccess', _9 => _9.path]), () => ( req.path)))));
@@ -767,11 +793,14 @@ function rateLimit(options) {
767
793
  const resetMs = (slot + 1) * windowMs - now;
768
794
  let count;
769
795
  try {
770
- count = (await _chunkIEF6AEK3cjs.rawIncr.call(void 0, `rl:${bucket}:${who}:${slot}`, Math.ceil(resetMs / 1e3) + 1)).value;
796
+ count = (await _chunkH6MHRHUPcjs.rawIncr.call(void 0,
797
+ `rl:${JSON.stringify([String(bucket), who, slot])}`,
798
+ Math.ceil(resetMs / 1e3) + 1
799
+ )).value;
771
800
  } catch (err) {
772
801
  if (Date.now() - lastCacheError > 3e4) {
773
802
  lastCacheError = Date.now();
774
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error(
803
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).error(
775
804
  { err },
776
805
  `rateLimit: cache unavailable \u2014 ${options.onCacheError === "reject" ? "rejecting with 503" : "allowing requests"}`
777
806
  );
@@ -799,32 +828,85 @@ function rateLimit(options) {
799
828
  }
800
829
 
801
830
  // src/cache/response.ts
831
+ var _crypto = require('crypto');
802
832
  var RESPONSE_PREFIX = "res:";
833
+ var representationHeaders = [
834
+ "content-type",
835
+ "cache-control",
836
+ "vary",
837
+ "content-language",
838
+ "content-disposition",
839
+ "etag",
840
+ "last-modified"
841
+ ];
842
+ var variant = (req, names) => _crypto.createHash.call(void 0, "sha256").update(JSON.stringify(names.map((name) => [name, _nullishCoalesce(req.get(name), () => ( null))]))).digest("hex");
803
843
  function cacheResponse(options) {
804
844
  const opts = typeof options === "number" ? { ttl: options } : options;
805
845
  return (req, res, next) => {
806
846
  if (req.method !== "GET" && req.method !== "HEAD") return next();
807
847
  let scope = "";
808
848
  if (opts.perUser) {
809
- const user = _chunkQSIP7YLWcjs.getCurrentUser.call(void 0, );
849
+ const user = _chunkURKE3OXNcjs.getCurrentUser.call(void 0, );
810
850
  const id = _nullishCoalesce(_optionalChain([user, 'optionalAccess', _10 => _10["sub"]]), () => ( _optionalChain([user, 'optionalAccess', _11 => _11["id"]])));
811
- if (id === void 0) return next();
812
- scope = `u:${String(id)}:`;
851
+ if (typeof id !== "string" && (typeof id !== "number" || !Number.isFinite(id))) return next();
852
+ scope = `u:${JSON.stringify([id])}:`;
813
853
  }
814
- const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);
854
+ const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl) + "\0" + req.method;
815
855
  void (async () => {
816
- const hit = await _chunkIEF6AEK3cjs.cache.get(key);
817
- if (hit) {
856
+ const hit = await _chunkH6MHRHUPcjs.cache.get(key);
857
+ if (hit && typeof hit.json === "string" && Array.isArray(hit.vary) && hit.variant === variant(req, hit.vary)) {
858
+ res.set(hit.headers);
818
859
  res.setHeader("X-Cache", "HIT");
819
- res.status(hit.status).json(hit.body);
860
+ res.status(hit.status).send(hit.json);
820
861
  return;
821
862
  }
822
863
  res.setHeader("X-Cache", "MISS");
864
+ let captured = false;
865
+ let snapshot = "";
823
866
  const json = res.json.bind(res);
824
867
  res.json = (body) => {
825
- if (res.statusCode === 200) void _chunkIEF6AEK3cjs.cache.set(key, { status: 200, body }, { ttl: opts.ttl });
826
- return json(body);
868
+ const send = res.send;
869
+ const eligible = !res.headersSent && res.statusCode === 200;
870
+ res.send = (rendered) => {
871
+ if (eligible && typeof rendered === "string") {
872
+ try {
873
+ JSON.parse(rendered);
874
+ snapshot = rendered;
875
+ captured = true;
876
+ } catch (e) {
877
+ }
878
+ }
879
+ return send.call(res, rendered);
880
+ };
881
+ try {
882
+ return json(body);
883
+ } finally {
884
+ res.send = send;
885
+ }
827
886
  };
887
+ res.once("finish", () => {
888
+ if (!captured || res.statusCode !== 200 || res.getHeader("set-cookie") !== void 0)
889
+ return;
890
+ const control = String(_nullishCoalesce(res.getHeader("cache-control"), () => ( "")));
891
+ if (/(?:^|,)\s*(?:no-store|no-cache)(?:\s|,|=|$)/i.test(control) || !opts.perUser && /(?:^|,)\s*private(?:\s|,|=|$)/i.test(control))
892
+ return;
893
+ const vary = String(_nullishCoalesce(res.getHeader("vary"), () => ( ""))).split(",").map((name) => name.trim().toLowerCase()).filter(Boolean);
894
+ if (vary.includes("*")) return;
895
+ const headers = {};
896
+ for (const name of representationHeaders) {
897
+ const value = res.getHeader(name);
898
+ if (value !== void 0)
899
+ headers[name] = Array.isArray(value) ? value.join(", ") : String(value);
900
+ }
901
+ const stored = {
902
+ status: 200,
903
+ json: snapshot,
904
+ headers,
905
+ vary,
906
+ variant: variant(req, vary)
907
+ };
908
+ void _chunkH6MHRHUPcjs.cache.set(key, stored, { ttl: opts.ttl }).catch((error) => _chunkJHCXIYJHcjs.getLogger.call(void 0, ).debug({ err: error }, "Response cache write failed"));
909
+ });
828
910
  next();
829
911
  })().catch(next);
830
912
  };
@@ -881,7 +963,7 @@ async function ignite(config) {
881
963
  const raw = _fs2.default.readFileSync(_path2.default.join(process.cwd(), "package.json"), "utf8");
882
964
  const pkg = JSON.parse(raw);
883
965
  return { name: _nullishCoalesce(pkg.name, () => ( "API")), version: _nullishCoalesce(pkg.version, () => ( "")) };
884
- } catch (e) {
966
+ } catch (e2) {
885
967
  return { name: "API", version: "" };
886
968
  }
887
969
  }
@@ -891,21 +973,22 @@ async function ignite(config) {
891
973
  const jwtSecret = config.jwtSecret;
892
974
  const authStrategy = _nullishCoalesce(config.authStrategy, () => ( "http-only"));
893
975
  const clusterEnabled = _nullishCoalesce(config.cluster, () => ( process.env["NODE_ENV"] === "production"));
894
- _chunkQSIP7YLWcjs.configureLogger.call(void 0, config.logging);
976
+ _chunkJHCXIYJHcjs.configureLogger.call(void 0, config.logging);
895
977
  if (!["http-only", "bearer", "localStorage"].includes(authStrategy) && (!clusterEnabled || _cluster2.default.isPrimary)) {
896
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn(
978
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).warn(
897
979
  `[EFC] Unknown authStrategy "${String(authStrategy)}" \u2014 treated as 'bearer'. Use 'http-only' or 'bearer'; this will be an error in 1.0.`
898
980
  );
899
981
  }
900
982
  if (jwtSecret && Buffer.byteLength(jwtSecret) < 32 && process.env["NODE_ENV"] === "production" && (!clusterEnabled || _cluster2.default.isPrimary)) {
901
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).warn(
983
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).warn(
902
984
  `[EFC] jwtSecret is ${Buffer.byteLength(jwtSecret)} bytes \u2014 use at least 32 random bytes in production (openssl rand -hex 64).`
903
985
  );
904
986
  }
905
- _chunkQSIP7YLWcjs.configureQueryLog.call(void 0, config.logging);
987
+ _chunkJHCXIYJHcjs.configureQueryLog.call(void 0, config.logging);
988
+ _chunkURKE3OXNcjs.configureTracing.call(void 0, config.tracing);
906
989
  if (clusterEnabled && _cluster2.default.isPrimary) {
907
990
  if (config.cache && config.cache.backend === "memory") {
908
- _chunkIEF6AEK3cjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
991
+ _chunkH6MHRHUPcjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
909
992
  }
910
993
  runMaster({
911
994
  workers: _nullishCoalesce(workers, () => ( _os2.default.cpus().length)),
@@ -914,35 +997,35 @@ async function ignite(config) {
914
997
  });
915
998
  return;
916
999
  }
917
- const app = _chunkDGYPIIJEcjs.createHttpApp.call(void 0, config);
918
- if (database) _chunkGWMW6XY7cjs.setDbEngine.call(void 0, database);
919
- _chunkGWMW6XY7cjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
1000
+ const app = _chunkAG7PVYPEcjs.createHttpApp.call(void 0, config);
1001
+ if (database) _chunkJVB5NLEMcjs.setDbEngine.call(void 0, database);
1002
+ _chunkJVB5NLEMcjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
920
1003
  const poolWorkers = clusterEnabled ? _nullishCoalesce(workers, () => ( _os2.default.cpus().length)) : 1;
921
1004
  const reportsPools = !clusterEnabled || _optionalChain([_cluster2.default, 'access', _12 => _12.worker, 'optionalAccess', _13 => _13.id]) === 1;
922
1005
  if (database === "mongodb" && databaseUrl) {
923
- const conn = await _chunkSOU3PBJCcjs.connectMongo.call(void 0, databaseUrl, config.databasePool);
924
- _chunkSOU3PBJCcjs.setDbClient.call(void 0, conn);
1006
+ const conn = await _chunkSV4C4HWPcjs.connectMongo.call(void 0, databaseUrl, config.databasePool);
1007
+ _chunkSV4C4HWPcjs.setDbClient.call(void 0, conn);
925
1008
  if (reportsPools) {
926
1009
  const max = _nullishCoalesce(_optionalChain([config, 'access', _14 => _14.databasePool, 'optionalAccess', _15 => _15.max]), () => ( 100));
927
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(
1010
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).info(
928
1011
  `MongoDB connections: up to ${poolWorkers * max} from this machine (${poolWorkers} worker(s) \xD7 maxPoolSize ${max})`
929
1012
  );
930
1013
  }
931
1014
  } else if (database === "postgresql" && databaseUrl) {
932
- const pool = await _chunkQSIP7YLWcjs.connectPostgres.call(void 0, databaseUrl, config.databasePool);
933
- _chunkSOU3PBJCcjs.setDbClient.call(void 0, pool);
1015
+ const pool = await _chunkJHCXIYJHcjs.connectPostgres.call(void 0, databaseUrl, config.databasePool);
1016
+ _chunkSV4C4HWPcjs.setDbClient.call(void 0, pool);
934
1017
  if (reportsPools) {
935
1018
  const max = _nullishCoalesce(_optionalChain([config, 'access', _16 => _16.databasePool, 'optionalAccess', _17 => _17.max]), () => ( 10));
936
1019
  const boss = config.tasks && config.tasks.backend === "pg-boss" && !config.tasks.connectionString ? 10 : 0;
937
1020
  const breakdown = `${poolWorkers} worker(s) \xD7 (pool ${max}${boss ? ` + pg-boss ${boss}` : ""})`;
938
- await _chunkQSIP7YLWcjs.checkConnectionBudget.call(void 0, poolWorkers * (max + boss), breakdown);
1021
+ await _chunkJHCXIYJHcjs.checkConnectionBudget.call(void 0, poolWorkers * (max + boss), breakdown);
939
1022
  }
940
1023
  }
941
1024
  if (config.cache) {
942
- await _chunkIEF6AEK3cjs.configureCache.call(void 0, config.cache);
1025
+ await _chunkH6MHRHUPcjs.configureCache.call(void 0, config.cache);
943
1026
  }
944
1027
  if (jwtSecret) {
945
- _chunkIEF6AEK3cjs.configureAuth.call(void 0, {
1028
+ _chunkH6MHRHUPcjs.configureAuth.call(void 0, {
946
1029
  secret: jwtSecret,
947
1030
  strategy: authStrategy,
948
1031
  expiresIn: _nullishCoalesce(config.jwtExpiresIn, () => ( "7d")),
@@ -954,7 +1037,8 @@ async function ignite(config) {
954
1037
  }
955
1038
  if (config.tasks) {
956
1039
  if (config.tasks.backend === "bullmq") {
957
- await _chunkDTMDJGRWcjs.initBullMQ.call(void 0, {
1040
+ await _chunkVLGN3XUMcjs.initBullMQ.call(void 0, {
1041
+ tracing: !!config.tracing && (config.tracing === true || config.tracing.tasks !== false),
958
1042
  redisUrl: _nullishCoalesce(config.tasks.redisUrl, () => ( "redis://localhost:6379")),
959
1043
  concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5)),
960
1044
  enqueueTimeout: _nullishCoalesce(config.tasks.enqueueTimeout, () => ( 5e3)),
@@ -967,7 +1051,8 @@ async function ignite(config) {
967
1051
  '[EFC] tasks.backend "pg-boss" needs tasks.connectionString or databaseUrl'
968
1052
  );
969
1053
  }
970
- await _chunk6WTMRZS7cjs.initPgBoss.call(void 0, {
1054
+ await _chunkIG3V2IOKcjs.initPgBoss.call(void 0, {
1055
+ tracing: !!config.tracing && (config.tracing === true || config.tracing.tasks !== false),
971
1056
  connectionString,
972
1057
  concurrency: _nullishCoalesce(config.tasks.concurrency, () => ( 5)),
973
1058
  enqueueTimeout: _nullishCoalesce(config.tasks.enqueueTimeout, () => ( 5e3)),
@@ -976,13 +1061,13 @@ async function ignite(config) {
976
1061
  });
977
1062
  }
978
1063
  }
979
- const routes = _chunkWHBSVYUYcjs.scanDir.call(void 0, apiDir);
1064
+ const routes = _chunk4FQP6QX3cjs.scanDir.call(void 0, apiDir);
980
1065
  const apiRouter = _express2.default.Router();
981
- const mounted = await _chunkDGYPIIJEcjs.mountRoutes.call(void 0, apiRouter, routes);
1066
+ const mounted = await _chunkAG7PVYPEcjs.mountRoutes.call(void 0, apiRouter, routes);
982
1067
  if (config.openapi) {
983
1068
  const meta = readProjectMeta();
984
1069
  const options = config.openapi === true ? {} : config.openapi;
985
- await _chunkDGYPIIJEcjs.mountOpenAPI.call(void 0, app, mounted, {
1070
+ await _chunkAG7PVYPEcjs.mountOpenAPI.call(void 0, app, mounted, {
986
1071
  info: { title: meta.name, version: meta.version },
987
1072
  ...options,
988
1073
  basePath
@@ -996,15 +1081,15 @@ async function ignite(config) {
996
1081
  res.send(generateDashboard(mounted, basePath, port, name, version));
997
1082
  });
998
1083
  }
999
- _chunkDGYPIIJEcjs.mountErrorHandler.call(void 0, app, onError);
1084
+ _chunkAG7PVYPEcjs.mountErrorHandler.call(void 0, app, onError);
1000
1085
  return new Promise((resolve, reject) => {
1001
1086
  const server = _http2.default.createServer(app);
1002
1087
  if (config.websocket !== false && mounted.some((route) => route.websocket))
1003
- _chunkDGYPIIJEcjs.attachWebSockets.call(void 0, server, app, config.websocket);
1088
+ _chunkAG7PVYPEcjs.attachWebSockets.call(void 0, server, app, config.websocket);
1004
1089
  server.once("listening", () => {
1005
1090
  const wid = _nullishCoalesce(_optionalChain([_cluster2.default, 'access', _18 => _18.worker, 'optionalAccess', _19 => _19.id]), () => ( "primary"));
1006
1091
  const addr = server.address();
1007
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _20 => _20.port]), () => ( port))}`);
1092
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).info(`Worker ${wid} listening on :${_nullishCoalesce(_optionalChain([addr, 'optionalAccess', _20 => _20.port]), () => ( port))}`);
1008
1093
  resolve(server);
1009
1094
  });
1010
1095
  server.once("error", reject);
@@ -1016,22 +1101,33 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1016
1101
  const shutdown = (signal) => {
1017
1102
  if (shuttingDown) return;
1018
1103
  shuttingDown = true;
1019
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info(`${signal} received \u2014 closing server gracefully\u2026`);
1104
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).info(`${signal} received \u2014 closing server gracefully\u2026`);
1020
1105
  if (server) {
1021
- const websocketDrain = _chunkDGYPIIJEcjs.closeWebSockets.call(void 0, server, Math.max(1, Math.min(1e3, timeoutMs / 2)));
1106
+ const websocketDrain = _chunkAG7PVYPEcjs.closeWebSockets.call(void 0, server, Math.max(1, Math.min(1e3, timeoutMs / 2)));
1022
1107
  server.closeIdleConnections();
1023
1108
  server.close(() => {
1024
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).info("Server closed");
1025
- Promise.all([websocketDrain, _chunkDTMDJGRWcjs.closeBullMQ.call(void 0, ), _chunk6WTMRZS7cjs.closePgBoss.call(void 0, ), _chunkIEF6AEK3cjs.closeCache.call(void 0, )]).catch((err) => _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error({ err }, "Task backend close failed")).finally(() => process.exit(0));
1109
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).info("Server closed");
1110
+ drainServices({
1111
+ transports: [websocketDrain],
1112
+ tasks: [_chunkVLGN3XUMcjs.closeBullMQ, _chunkIG3V2IOKcjs.closePgBoss],
1113
+ cache: _chunkH6MHRHUPcjs.closeCache,
1114
+ tracing: _chunkURKE3OXNcjs.shutdownTracing
1115
+ }).then(
1116
+ () => process.exit(0),
1117
+ (err) => {
1118
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).error({ err }, "Service shutdown failed");
1119
+ process.exit(1);
1120
+ }
1121
+ );
1026
1122
  });
1027
1123
  setTimeout(() => {
1028
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error("Forced exit after timeout");
1124
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).error("Forced exit after timeout");
1029
1125
  process.exit(1);
1030
1126
  }, timeoutMs).unref();
1031
1127
  } else {
1032
1128
  shutdownMaster();
1033
1129
  setTimeout(() => {
1034
- _chunkQSIP7YLWcjs.getLogger.call(void 0, ).error("Workers did not exit in time \u2014 forcing primary exit");
1130
+ _chunkJHCXIYJHcjs.getLogger.call(void 0, ).error("Workers did not exit in time \u2014 forcing primary exit");
1035
1131
  process.exit(1);
1036
1132
  }, timeoutMs + 2e3).unref();
1037
1133
  }
@@ -1066,6 +1162,6 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1066
1162
 
1067
1163
 
1068
1164
 
1069
- exports.HttpError = _chunkAGOYTFROcjs.HttpError; exports.ModelValidationError = _chunkGWMW6XY7cjs.ModelValidationError; exports.attachWebSockets = _chunkDGYPIIJEcjs.attachWebSockets; exports.cache = _chunkIEF6AEK3cjs.cache; exports.cacheResponse = cacheResponse; exports.closeWebSockets = _chunkDGYPIIJEcjs.closeWebSockets; exports.compose = compose; exports.db = _chunkSOU3PBJCcjs.db; exports.defineCollection = _chunkSOU3PBJCcjs.defineCollection; exports.defineModel = _chunkSOU3PBJCcjs.defineModel; exports.defineTable = _chunkSOU3PBJCcjs.defineTable; exports.generateOpenAPI = _chunkDGYPIIJEcjs.generateOpenAPI; exports.getDbClient = _chunkSOU3PBJCcjs.getDbClient; exports.getLogger = _chunkQSIP7YLWcjs.getLogger; exports.getQueryMetrics = _chunkQSIP7YLWcjs.getQueryMetrics; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkAGOYTFROcjs.isHttpError; exports.listTasks = _chunkH2PVWCWCcjs.listTasks; exports.logger = _chunkQSIP7YLWcjs.logger; exports.rateLimit = rateLimit; exports.resetQueryMetrics = _chunkQSIP7YLWcjs.resetQueryMetrics; exports.scanDir = _chunkWHBSVYUYcjs.scanDir; exports.setDbClient = _chunkSOU3PBJCcjs.setDbClient; exports.transaction = _chunkSOU3PBJCcjs.transaction; exports.workerCount = workerCount;
1165
+ exports.HttpError = _chunkAGOYTFROcjs.HttpError; exports.ModelValidationError = _chunkJVB5NLEMcjs.ModelValidationError; exports.attachWebSockets = _chunkAG7PVYPEcjs.attachWebSockets; exports.cache = _chunkH6MHRHUPcjs.cache; exports.cacheResponse = cacheResponse; exports.closeWebSockets = _chunkAG7PVYPEcjs.closeWebSockets; exports.compose = compose; exports.db = _chunkSV4C4HWPcjs.db; exports.defineCollection = _chunkSV4C4HWPcjs.defineCollection; exports.defineModel = _chunkSV4C4HWPcjs.defineModel; exports.defineTable = _chunkSV4C4HWPcjs.defineTable; exports.generateOpenAPI = _chunkAG7PVYPEcjs.generateOpenAPI; exports.getDbClient = _chunkSV4C4HWPcjs.getDbClient; exports.getLogger = _chunkJHCXIYJHcjs.getLogger; exports.getQueryMetrics = _chunkJHCXIYJHcjs.getQueryMetrics; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkAGOYTFROcjs.isHttpError; exports.listTasks = _chunkA2QGDWCGcjs.listTasks; exports.logger = _chunkJHCXIYJHcjs.logger; exports.rateLimit = rateLimit; exports.resetQueryMetrics = _chunkJHCXIYJHcjs.resetQueryMetrics; exports.scanDir = _chunk4FQP6QX3cjs.scanDir; exports.setDbClient = _chunkSV4C4HWPcjs.setDbClient; exports.transaction = _chunkSV4C4HWPcjs.transaction; exports.workerCount = workerCount;
1070
1166
  //# sourceMappingURL=index.cjs.map
1071
1167
  exports.generateOpenAPI = require("./openapi-cjs.cjs").generateOpenAPI;