express-file-cluster 0.9.6 → 0.10.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.
- package/dist/auth/index.cjs +7 -6
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +5 -5
- package/dist/chunk-3SWI46YK.js +74 -0
- package/dist/chunk-3SWI46YK.js.map +1 -0
- package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
- package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
- package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
- package/dist/chunk-74BSJXWD.cjs +220 -0
- package/dist/chunk-74BSJXWD.cjs.map +1 -0
- package/dist/{chunk-6KHBJOLB.cjs → chunk-7BC3AN7R.cjs} +14 -14
- package/dist/{chunk-6KHBJOLB.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
- package/dist/chunk-AGOYTFRO.cjs +42 -0
- package/dist/chunk-AGOYTFRO.cjs.map +1 -0
- package/dist/{chunk-HBYSKULC.js → chunk-B6MB6HEG.js} +5 -1
- package/dist/chunk-B6MB6HEG.js.map +1 -0
- package/dist/{chunk-OFA7OGN5.js → chunk-BG4A7Z32.js} +176 -7
- package/dist/chunk-BG4A7Z32.js.map +1 -0
- package/dist/{chunk-45BWAR6P.js → chunk-C2FOZ7ME.js} +4 -4
- package/dist/chunk-CGY7JU4Y.cjs +8 -0
- package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
- package/dist/{chunk-BBSZLGZW.js → chunk-DN4TCGYB.js} +43 -14
- package/dist/chunk-DN4TCGYB.js.map +1 -0
- package/dist/{chunk-TI24L4XE.cjs → chunk-H2PVWCWC.cjs} +6 -2
- package/dist/chunk-H2PVWCWC.cjs.map +1 -0
- package/dist/{chunk-TYCYYLLM.cjs → chunk-IUZ6A7PB.cjs} +20 -53
- package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
- package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
- package/dist/chunk-JP36TLL4.cjs.map +1 -0
- package/dist/chunk-KLWL7XSC.js +220 -0
- package/dist/chunk-KLWL7XSC.js.map +1 -0
- package/dist/{chunk-QL6EWT4B.cjs → chunk-M53GODCX.cjs} +44 -15
- package/dist/chunk-M53GODCX.cjs.map +1 -0
- package/dist/{chunk-7ZESZG3J.js → chunk-MUVO7MGS.js} +4 -4
- package/dist/{chunk-VWSUQKCJ.cjs → chunk-R2K7AFIB.cjs} +286 -117
- package/dist/chunk-R2K7AFIB.cjs.map +1 -0
- package/dist/{chunk-ULWNHN6P.js → chunk-RETV3GKE.js} +9 -42
- package/dist/chunk-RETV3GKE.js.map +1 -0
- package/dist/{chunk-7YEX4MQV.cjs → chunk-RPL2IFWK.cjs} +46 -7
- package/dist/chunk-RPL2IFWK.cjs.map +1 -0
- package/dist/{chunk-FMA76PRH.cjs → chunk-TBIVIR6L.cjs} +15 -15
- package/dist/{chunk-FMA76PRH.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
- package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
- package/dist/chunk-V73R76I4.js.map +1 -0
- package/dist/chunk-XPY5TQDK.js +42 -0
- package/dist/chunk-XPY5TQDK.js.map +1 -0
- package/dist/{chunk-RGT4ZVHL.cjs → chunk-Y4NKIXUL.cjs} +110 -55
- package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
- package/dist/{chunk-2SETEVMO.js → chunk-Y75V5FCU.js} +100 -45
- package/dist/chunk-Y75V5FCU.js.map +1 -0
- package/dist/cli/db-runner.cjs +2059 -126
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +2034 -102
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +50 -29
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +39 -21
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +23 -0
- package/dist/docs/api-reference/collection.md +44 -1
- package/dist/docs/api-reference/compose.md +1 -1
- package/dist/docs/api-reference/db.md +8 -0
- package/dist/docs/api-reference/ignite.md +13 -1
- package/dist/docs/api-reference/testing.md +26 -0
- package/dist/docs/api-reference/types.md +99 -0
- package/dist/docs/cli/add.md +2 -2
- package/dist/docs/cli/db.md +2 -2
- package/dist/docs/core-concepts/background-tasks.md +6 -3
- package/dist/docs/core-concepts/file-based-routing.md +2 -0
- package/dist/docs/core-concepts/middleware.md +2 -2
- package/dist/docs/getting-started/index.md +6 -1
- package/dist/docs/guides/authentication.md +33 -0
- package/dist/docs/guides/caching.md +34 -1
- package/dist/docs/guides/database.md +17 -0
- package/dist/docs/guides/environment-variables.md +6 -0
- package/dist/docs/guides/feature-matrix.md +58 -0
- package/dist/docs/guides/generated-portals.md +3 -1
- package/dist/docs/guides/logging.md +17 -0
- package/dist/docs/guides/migrations.md +26 -3
- package/dist/docs/guides/testing.md +31 -0
- package/dist/docs/guides/which-api.md +2 -2
- package/dist/docs/index.md +4 -1
- package/dist/docs/skills/SKILL.md +5 -1
- package/dist/docs/skills/api-surface.md +25 -4
- package/dist/docs/skills/auth-internals.md +14 -1
- package/dist/docs/skills/pre-flight.md +6 -0
- package/dist/docs/skills/routing-rules.md +1 -1
- package/dist/docs/skills/tasks-internals.md +4 -3
- package/dist/docs/skills/what-not-to-invent.md +13 -4
- package/dist/docs/versioning.md +1 -1
- package/dist/index.cjs +135 -255
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +228 -3
- package/dist/index.d.ts +228 -3
- package/dist/index.js +96 -217
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-4X2YT4RB.js +14 -0
- package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
- package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
- package/dist/registry/index.json +39 -3
- package/dist/registry/js-mongo/account-security.json +1 -1
- package/dist/registry/js-mongo/admin-users.json +1 -1
- package/dist/registry/js-mongo/auth.json +1 -1
- package/dist/registry/js-mongo/auth@apple.json +1 -1
- package/dist/registry/js-mongo/auth@google.json +1 -1
- package/dist/registry/js-mongo/forgot-password.json +1 -1
- package/dist/registry/js-mongo/user-profile.json +1 -1
- package/dist/registry/js-mongo-collection/_base.json +1 -0
- package/dist/registry/js-mongo-collection/account-security.json +1 -0
- package/dist/registry/js-mongo-collection/account-settings.json +1 -0
- package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/js-mongo-collection/admin-content.json +1 -0
- package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/js-mongo-collection/admin-support.json +1 -0
- package/dist/registry/js-mongo-collection/admin-system.json +1 -0
- package/dist/registry/js-mongo-collection/admin-users.json +1 -0
- package/dist/registry/js-mongo-collection/admin.json +1 -0
- package/dist/registry/js-mongo-collection/auth.json +1 -0
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/js-mongo-collection/auth@google.json +1 -0
- package/dist/registry/js-mongo-collection/billing.json +1 -0
- package/dist/registry/js-mongo-collection/email-client.json +1 -0
- package/dist/registry/js-mongo-collection/email-verification.json +1 -0
- package/dist/registry/js-mongo-collection/files.json +1 -0
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/js-mongo-collection/notifications.json +1 -0
- package/dist/registry/js-mongo-collection/support.json +1 -0
- package/dist/registry/js-mongo-collection/user-profile.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -1
- package/dist/registry/js-pg-model/admin-users.json +1 -1
- package/dist/registry/js-pg-model/auth.json +1 -1
- package/dist/registry/js-pg-model/auth@apple.json +1 -1
- package/dist/registry/js-pg-model/auth@google.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.json +1 -1
- package/dist/registry/js-pg-model/user-profile.json +1 -1
- package/dist/registry/js-pg-table/account-security.json +1 -1
- package/dist/registry/js-pg-table/admin-users.json +1 -1
- package/dist/registry/js-pg-table/auth.json +1 -1
- package/dist/registry/js-pg-table/auth@apple.json +1 -1
- package/dist/registry/js-pg-table/auth@google.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.json +1 -1
- package/dist/registry/js-pg-table/user-profile.json +1 -1
- package/dist/registry/ts-mongo/account-security.json +1 -1
- package/dist/registry/ts-mongo/admin-users.json +1 -1
- package/dist/registry/ts-mongo/auth.json +1 -1
- package/dist/registry/ts-mongo/auth@apple.json +1 -1
- package/dist/registry/ts-mongo/auth@google.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.json +1 -1
- package/dist/registry/ts-mongo/user-profile.json +1 -1
- package/dist/registry/ts-mongo-collection/_base.json +1 -0
- package/dist/registry/ts-mongo-collection/account-security.json +1 -0
- package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
- package/dist/registry/ts-mongo-collection/admin.json +1 -0
- package/dist/registry/ts-mongo-collection/auth.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
- package/dist/registry/ts-mongo-collection/billing.json +1 -0
- package/dist/registry/ts-mongo-collection/email-client.json +1 -0
- package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
- package/dist/registry/ts-mongo-collection/files.json +1 -0
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/ts-mongo-collection/notifications.json +1 -0
- package/dist/registry/ts-mongo-collection/support.json +1 -0
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -1
- package/dist/registry/ts-pg-model/admin-users.json +1 -1
- package/dist/registry/ts-pg-model/auth.json +1 -1
- package/dist/registry/ts-pg-model/auth@apple.json +1 -1
- package/dist/registry/ts-pg-model/auth@google.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.json +1 -1
- package/dist/registry/ts-pg-model/user-profile.json +1 -1
- package/dist/registry/ts-pg-table/account-security.json +1 -1
- package/dist/registry/ts-pg-table/admin-users.json +1 -1
- package/dist/registry/ts-pg-table/auth.json +1 -1
- package/dist/registry/ts-pg-table/auth@apple.json +1 -1
- package/dist/registry/ts-pg-table/auth@google.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/dist/registry/ts-pg-table/user-profile.json +1 -1
- package/dist/tasks/index.cjs +5 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +4 -2
- package/dist/tasks/index.d.ts +4 -2
- package/dist/tasks/index.js +3 -1
- package/dist/testing-cjs.cjs +5 -0
- package/dist/testing.cjs +59 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +27 -0
- package/dist/testing.d.ts +27 -0
- package/dist/testing.js +58 -0
- package/dist/testing.js.map +1 -0
- package/dist/thread-runner.cjs +9 -0
- package/dist/thread-runner.cjs.map +1 -0
- package/dist/thread-runner.d.cts +3 -0
- package/dist/thread-runner.d.ts +3 -0
- package/dist/thread-runner.js +8 -0
- package/dist/thread-runner.js.map +1 -0
- package/dist/{types-DAsBKVM-.d.ts → types-CPMFTVXm.d.cts} +15 -1
- package/dist/{types-DAsBKVM-.d.cts → types-CPMFTVXm.d.ts} +15 -1
- package/package.json +6 -1
- package/dist/chunk-2SETEVMO.js.map +0 -1
- package/dist/chunk-73XJUT2S.js.map +0 -1
- package/dist/chunk-7YEX4MQV.cjs.map +0 -1
- package/dist/chunk-BBSZLGZW.js.map +0 -1
- package/dist/chunk-DUADUR6R.cjs.map +0 -1
- package/dist/chunk-HBYSKULC.js.map +0 -1
- package/dist/chunk-LJNSJFOL.js +0 -38
- package/dist/chunk-LJNSJFOL.js.map +0 -1
- package/dist/chunk-OFA7OGN5.js.map +0 -1
- package/dist/chunk-QL6EWT4B.cjs.map +0 -1
- package/dist/chunk-RGT4ZVHL.cjs.map +0 -1
- package/dist/chunk-TI24L4XE.cjs.map +0 -1
- package/dist/chunk-TYCYYLLM.cjs.map +0 -1
- package/dist/chunk-ULWNHN6P.js.map +0 -1
- package/dist/chunk-VWSUQKCJ.cjs.map +0 -1
- package/dist/pgboss-backend-DSO3QTNK.cjs +0 -14
- package/dist/pgboss-backend-DSO3QTNK.cjs.map +0 -1
- package/dist/pgboss-backend-I6DFUNRM.js +0 -14
- /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
- /package/dist/{chunk-45BWAR6P.js.map → chunk-C2FOZ7ME.js.map} +0 -0
- /package/dist/{chunk-7ZESZG3J.js.map → chunk-MUVO7MGS.js.map} +0 -0
- /package/dist/{pgboss-backend-I6DFUNRM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
|
@@ -1,6 +1,14 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/process-state.ts
|
|
2
|
+
function processState(name, initialize) {
|
|
3
|
+
const key = /* @__PURE__ */ Symbol.for("express-file-cluster.runtime.v1." + name);
|
|
4
|
+
const globals = globalThis;
|
|
5
|
+
if (!(key in globals)) globals[key] = initialize();
|
|
6
|
+
return globals[key];
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// src/context.ts
|
|
2
10
|
var _async_hooks = require('async_hooks');
|
|
3
|
-
var storage = new (0, _async_hooks.AsyncLocalStorage)();
|
|
11
|
+
var storage = processState("request-context", () => new (0, _async_hooks.AsyncLocalStorage)());
|
|
4
12
|
function runWithContext(ctx, fn) {
|
|
5
13
|
return storage.run(ctx, fn);
|
|
6
14
|
}
|
|
@@ -116,17 +124,72 @@ function requestLogger() {
|
|
|
116
124
|
|
|
117
125
|
// src/db/query-log.ts
|
|
118
126
|
|
|
127
|
+
var metrics = /* @__PURE__ */ new Map();
|
|
128
|
+
var metricsSince = Date.now();
|
|
129
|
+
var metricsDropped = 0;
|
|
130
|
+
function getQueryMetrics() {
|
|
131
|
+
return {
|
|
132
|
+
enabled: !!_optionalChain([config, 'optionalAccess', _10 => _10.metricsLimit]),
|
|
133
|
+
since: metricsSince,
|
|
134
|
+
dropped: metricsDropped,
|
|
135
|
+
entries: [...metrics.values()].map((entry) => ({ ...entry })).sort((a, b) => a.model.localeCompare(b.model) || a.op.localeCompare(b.op))
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function resetQueryMetrics() {
|
|
139
|
+
metrics.clear();
|
|
140
|
+
metricsDropped = 0;
|
|
141
|
+
metricsSince = Date.now();
|
|
142
|
+
}
|
|
143
|
+
function collectMetric(event) {
|
|
144
|
+
if (!_optionalChain([config, 'optionalAccess', _11 => _11.metricsLimit])) return;
|
|
145
|
+
const key = event.model + "\0" + event.op;
|
|
146
|
+
let metric = metrics.get(key);
|
|
147
|
+
if (!metric) {
|
|
148
|
+
if (metrics.size >= config.metricsLimit) {
|
|
149
|
+
metricsDropped++;
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
metric = {
|
|
153
|
+
model: event.model,
|
|
154
|
+
op: event.op,
|
|
155
|
+
calls: 0,
|
|
156
|
+
errors: 0,
|
|
157
|
+
statements: 0,
|
|
158
|
+
totalMs: 0,
|
|
159
|
+
minMs: event.durationMs,
|
|
160
|
+
maxMs: event.durationMs,
|
|
161
|
+
meanMs: 0,
|
|
162
|
+
slow: 0
|
|
163
|
+
};
|
|
164
|
+
metrics.set(key, metric);
|
|
165
|
+
}
|
|
166
|
+
metric.calls++;
|
|
167
|
+
if (event.error !== void 0) metric.errors++;
|
|
168
|
+
metric.statements += event.statements;
|
|
169
|
+
metric.totalMs += event.durationMs;
|
|
170
|
+
metric.minMs = Math.min(metric.minMs, event.durationMs);
|
|
171
|
+
metric.maxMs = Math.max(metric.maxMs, event.durationMs);
|
|
172
|
+
metric.meanMs = metric.totalMs / metric.calls;
|
|
173
|
+
if (event.durationMs >= config.slowMs) metric.slow++;
|
|
174
|
+
}
|
|
119
175
|
var DEFAULTS = { slowMs: 500, nPlusOne: 10 };
|
|
120
176
|
var config;
|
|
121
177
|
var listeners = /* @__PURE__ */ new Set();
|
|
122
178
|
var enableHooks = [];
|
|
123
179
|
function configureQueryLog(logging) {
|
|
124
|
-
const q = logging === false ? void 0 : _optionalChain([logging, 'optionalAccess',
|
|
125
|
-
config = !q ? void 0 : q === true ? { all: true, ...DEFAULTS } : {
|
|
180
|
+
const q = logging === false ? void 0 : _optionalChain([logging, 'optionalAccess', _12 => _12.queries]);
|
|
181
|
+
config = !q ? void 0 : q === true ? { all: true, ...DEFAULTS, metricsLimit: 0 } : {
|
|
126
182
|
all: _nullishCoalesce(q.all, () => ( false)),
|
|
127
183
|
slowMs: _nullishCoalesce(q.slowMs, () => ( DEFAULTS.slowMs)),
|
|
128
|
-
nPlusOne: _nullishCoalesce(q.nPlusOne, () => ( DEFAULTS.nPlusOne))
|
|
184
|
+
nPlusOne: _nullishCoalesce(q.nPlusOne, () => ( DEFAULTS.nPlusOne)),
|
|
185
|
+
metricsLimit: !q.metrics ? 0 : typeof q.metrics === "object" ? _nullishCoalesce(q.metrics.maxEntries, () => ( 1e3)) : 1e3
|
|
129
186
|
};
|
|
187
|
+
if (config && (!Number.isSafeInteger(config.metricsLimit) || config.metricsLimit < 0)) {
|
|
188
|
+
config = void 0;
|
|
189
|
+
resetQueryMetrics();
|
|
190
|
+
throw new Error("[EFC] logging.queries.metrics.maxEntries must be a nonnegative safe integer");
|
|
191
|
+
}
|
|
192
|
+
resetQueryMetrics();
|
|
130
193
|
if (config) for (const hook of enableHooks) hook();
|
|
131
194
|
}
|
|
132
195
|
function active() {
|
|
@@ -146,12 +209,13 @@ function untracked(fn) {
|
|
|
146
209
|
function callSite(callee) {
|
|
147
210
|
const holder = {};
|
|
148
211
|
Error.captureStackTrace(holder, callee);
|
|
149
|
-
const line = _optionalChain([holder, 'access',
|
|
150
|
-
return _optionalChain([line, 'optionalAccess',
|
|
212
|
+
const line = _optionalChain([holder, 'access', _13 => _13.stack, 'optionalAccess', _14 => _14.split, 'call', _15 => _15("\n"), 'access', _16 => _16[1]]);
|
|
213
|
+
return _optionalChain([line, 'optionalAccess', _17 => _17.trim, 'call', _18 => _18(), 'access', _19 => _19.replace, 'call', _20 => _20(/^at /, "")]);
|
|
151
214
|
}
|
|
152
215
|
function emit(event, site, top) {
|
|
153
216
|
for (const listener of listeners) listener(event);
|
|
154
217
|
if (!config) return;
|
|
218
|
+
collectMetric(event);
|
|
155
219
|
const log = getLogger();
|
|
156
220
|
const msg = `${event.model}.${event.op} ${event.durationMs}ms`;
|
|
157
221
|
const fields = { ...event };
|
|
@@ -188,7 +252,7 @@ function traceOps(model, target, ops) {
|
|
|
188
252
|
const start = process.hrtime.bigint();
|
|
189
253
|
const finish = (error) => {
|
|
190
254
|
const durationMs = Math.round(Number(process.hrtime.bigint() - start) / 1e5) / 10;
|
|
191
|
-
const reqId = _optionalChain([getRequestContext, 'call',
|
|
255
|
+
const reqId = _optionalChain([getRequestContext, 'call', _21 => _21(), 'optionalAccess', _22 => _22.requestId]);
|
|
192
256
|
emit(
|
|
193
257
|
{
|
|
194
258
|
model,
|
|
@@ -196,7 +260,7 @@ function traceOps(model, target, ops) {
|
|
|
196
260
|
durationMs,
|
|
197
261
|
statements: frame.statements,
|
|
198
262
|
...reqId !== void 0 && { reqId },
|
|
199
|
-
...error !== void 0 && { error: _nullishCoalesce(_optionalChain([error, 'optionalAccess',
|
|
263
|
+
...error !== void 0 && { error: _nullishCoalesce(_optionalChain([error, 'optionalAccess', _23 => _23.message]), () => ( String(error))) }
|
|
200
264
|
},
|
|
201
265
|
site,
|
|
202
266
|
!parent
|
|
@@ -218,6 +282,86 @@ function traceOps(model, target, ops) {
|
|
|
218
282
|
return target;
|
|
219
283
|
}
|
|
220
284
|
|
|
285
|
+
// src/db/prepared-statements.ts
|
|
286
|
+
|
|
287
|
+
var invalidators = /* @__PURE__ */ new WeakMap();
|
|
288
|
+
function invalidatePreparedStatements(pool2) {
|
|
289
|
+
_optionalChain([invalidators, 'access', _24 => _24.get, 'call', _25 => _25(pool2), 'optionalCall', _26 => _26()]);
|
|
290
|
+
}
|
|
291
|
+
function preparedDriver(pool2, max) {
|
|
292
|
+
if (!Number.isSafeInteger(max) || max < 0) {
|
|
293
|
+
throw new Error("[EFC] databasePool.preparedStatements.max must be a nonnegative safe integer");
|
|
294
|
+
}
|
|
295
|
+
if (max === 0) return pool2;
|
|
296
|
+
let generation = 0;
|
|
297
|
+
invalidators.set(pool2, () => {
|
|
298
|
+
generation++;
|
|
299
|
+
});
|
|
300
|
+
const clients = /* @__PURE__ */ new WeakMap();
|
|
301
|
+
const wrap = (client) => {
|
|
302
|
+
const existing = clients.get(client);
|
|
303
|
+
if (existing) return existing;
|
|
304
|
+
let allocated = 0;
|
|
305
|
+
let seenGeneration = generation;
|
|
306
|
+
const names = /* @__PURE__ */ new Map();
|
|
307
|
+
const proxy = new Proxy(client, {
|
|
308
|
+
get(target, prop) {
|
|
309
|
+
if (prop === "query")
|
|
310
|
+
return (...args) => {
|
|
311
|
+
if (seenGeneration !== generation) {
|
|
312
|
+
names.clear();
|
|
313
|
+
seenGeneration = generation;
|
|
314
|
+
}
|
|
315
|
+
const query = args[0];
|
|
316
|
+
if (query && typeof query === "object" && "text" in query) {
|
|
317
|
+
const config2 = query;
|
|
318
|
+
const text = config2.text;
|
|
319
|
+
if (!config2.name && typeof text === "string" && /^\s*(select|insert|update|delete|with)\b/i.test(text) && !text.trim().replace(/;$/, "").includes(";")) {
|
|
320
|
+
let name = names.get(text);
|
|
321
|
+
if (!name && allocated < max) {
|
|
322
|
+
name = "efc_auto_" + _crypto.createHash.call(void 0, "sha256").update(generation + ":" + text).digest("hex").slice(0, 48);
|
|
323
|
+
names.set(text, name);
|
|
324
|
+
allocated++;
|
|
325
|
+
}
|
|
326
|
+
if (name) args[0] = { ...config2, name };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return Reflect.apply(target.query, target, args);
|
|
330
|
+
};
|
|
331
|
+
const value = Reflect.get(target, prop, target);
|
|
332
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
clients.set(client, proxy);
|
|
336
|
+
return proxy;
|
|
337
|
+
};
|
|
338
|
+
return new Proxy(pool2, {
|
|
339
|
+
get(target, prop) {
|
|
340
|
+
if (prop === "connect") return async () => wrap(await target.connect());
|
|
341
|
+
if (prop === "query")
|
|
342
|
+
return async (...args) => {
|
|
343
|
+
const client = await target.connect();
|
|
344
|
+
let failure;
|
|
345
|
+
const onError = (err) => {
|
|
346
|
+
failure = err;
|
|
347
|
+
};
|
|
348
|
+
client.once("error", onError);
|
|
349
|
+
try {
|
|
350
|
+
return await Reflect.apply(wrap(client).query, wrap(client), args);
|
|
351
|
+
} catch (err) {
|
|
352
|
+
failure = err instanceof Error ? err : new Error(String(err));
|
|
353
|
+
throw err;
|
|
354
|
+
} finally {
|
|
355
|
+
client.removeListener("error", onError);
|
|
356
|
+
client.release(failure);
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
const value = Reflect.get(target, prop, target);
|
|
360
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
221
365
|
// src/db/postgres.ts
|
|
222
366
|
var pool;
|
|
223
367
|
function notInstalled(err, pkg, install) {
|
|
@@ -229,7 +373,7 @@ async function connectPostgres(url, poolConfig = {}) {
|
|
|
229
373
|
let PoolCtor;
|
|
230
374
|
try {
|
|
231
375
|
const pg = await Promise.resolve().then(() => _interopRequireWildcard(require("pg")));
|
|
232
|
-
PoolCtor = _nullishCoalesce(_optionalChain([pg, 'access',
|
|
376
|
+
PoolCtor = _nullishCoalesce(_optionalChain([pg, 'access', _27 => _27.default, 'optionalAccess', _28 => _28.Pool]), () => ( pg.Pool));
|
|
233
377
|
} catch (err) {
|
|
234
378
|
throw notInstalled(err, "pg", "npm install pg drizzle-orm");
|
|
235
379
|
}
|
|
@@ -247,6 +391,15 @@ async function connectPostgres(url, poolConfig = {}) {
|
|
|
247
391
|
connectionTimeoutMillis: poolConfig.connectionTimeoutMs
|
|
248
392
|
}
|
|
249
393
|
});
|
|
394
|
+
const prepared = poolConfig.preparedStatements;
|
|
395
|
+
const maxStatements = prepared === false ? 0 : typeof prepared === "object" ? _nullishCoalesce(prepared.max, () => ( 100)) : 100;
|
|
396
|
+
let driver;
|
|
397
|
+
try {
|
|
398
|
+
driver = preparedDriver(next, maxStatements);
|
|
399
|
+
} catch (err) {
|
|
400
|
+
await next.end();
|
|
401
|
+
throw err;
|
|
402
|
+
}
|
|
250
403
|
next.on("error", (err) => getLogger().error({ err }, "PostgreSQL pool error"));
|
|
251
404
|
try {
|
|
252
405
|
await next.query("select 1");
|
|
@@ -256,7 +409,7 @@ async function connectPostgres(url, poolConfig = {}) {
|
|
|
256
409
|
throw explainPostgresError(err, url);
|
|
257
410
|
}
|
|
258
411
|
pool = next;
|
|
259
|
-
orm = drizzle(
|
|
412
|
+
orm = drizzle(driver, { logger: { logQuery: countStatement } });
|
|
260
413
|
getLogger().info("PostgreSQL connected");
|
|
261
414
|
return next;
|
|
262
415
|
}
|
|
@@ -339,7 +492,7 @@ async function closePostgres() {
|
|
|
339
492
|
const p = pool;
|
|
340
493
|
pool = void 0;
|
|
341
494
|
orm = void 0;
|
|
342
|
-
await _optionalChain([p, 'optionalAccess',
|
|
495
|
+
await _optionalChain([p, 'optionalAccess', _29 => _29.end, 'call', _30 => _30()]);
|
|
343
496
|
}
|
|
344
497
|
|
|
345
498
|
|
|
@@ -362,5 +515,9 @@ async function closePostgres() {
|
|
|
362
515
|
|
|
363
516
|
|
|
364
517
|
|
|
365
|
-
|
|
366
|
-
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
exports.processState = processState; exports.runWithContext = runWithContext; exports.setCurrentUser = setCurrentUser; exports.getCurrentUser = getCurrentUser; exports.configureLogger = configureLogger; exports.getLogger = getLogger; exports.logger = logger; exports.requestLogger = requestLogger; exports.getQueryMetrics = getQueryMetrics; exports.resetQueryMetrics = resetQueryMetrics; exports.configureQueryLog = configureQueryLog; exports.whenQueryTracking = whenQueryTracking; exports.countStatement = countStatement; exports.untracked = untracked; exports.traceOps = traceOps; exports.invalidatePreparedStatements = invalidatePreparedStatements; exports.notInstalled = notInstalled; exports.connectPostgres = connectPostgres; exports.explainPostgresError = explainPostgresError; exports.checkConnectionBudget = checkConnectionBudget; exports.getOrm = getOrm; exports.getPool = getPool; exports.closePostgres = closePostgres;
|
|
523
|
+
//# sourceMappingURL=chunk-JP36TLL4.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-JP36TLL4.cjs","../src/process-state.ts","../src/context.ts","../src/logger.ts","../src/db/query-log.ts","../src/db/prepared-statements.ts","../src/db/postgres.ts"],"names":["pool"],"mappings":"AAAA;ACCO,SAAS,YAAA,CAAgB,IAAA,EAAc,UAAA,EAAwB;AACpE,EAAA,MAAM,IAAA,kBAAM,MAAA,CAAO,GAAA,CAAI,mCAAA,EAAqC,IAAI,CAAA;AAChE,EAAA,MAAM,QAAA,EAAU,UAAA;AAChB,EAAA,GAAA,CAAI,CAAA,CAAE,IAAA,GAAO,OAAA,CAAA,EAAU,OAAA,CAAQ,GAAG,EAAA,EAAI,UAAA,CAAW,CAAA;AACjD,EAAA,OAAO,OAAA,CAAQ,GAAG,CAAA;AACpB;ADCA;AACA;AERA,0CAAkC;AAYlC,IAAM,QAAA,EAAU,YAAA,CAAa,iBAAA,EAAmB,CAAA,EAAA,GAAM,IAAI,mCAAA,CAAkC,CAAC,CAAA;AAMtF,SAAS,cAAA,CAAkB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file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-JP36TLL4.cjs","sourcesContent":[null,"/** Internal process state shared by the package's ESM and CommonJS module graphs. */\nexport function processState<T>(name: string, initialize: () => T): T {\n const key = Symbol.for('express-file-cluster.runtime.v1.' + name);\n const globals = globalThis as Record<symbol, unknown>;\n if (!(key in globals)) globals[key] = initialize();\n return globals[key] as T;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from 'pino';\nimport { processState } from './process-state.js';\n\nexport interface RequestContext {\n user?: Record<string, unknown> | undefined;\n requestId?: string;\n log?: Logger;\n /** Model operations run so far in this request, by `Model.op` (N+1 detection). */\n queryCounts?: Map<string, number>;\n}\n\nconst storage = processState('request-context', () => new AsyncLocalStorage<RequestContext>());\n\n// Wraps one request's lifecycle in an AsyncLocalStorage context. Node propagates\n// the store through the async chain the callback initiates (awaits, .then, etc.),\n// so anything running as part of the same request — including a `$currentUser`\n// default resolved deep inside a mongoose `.create()` call — can read it back.\nexport function runWithContext<T>(ctx: RequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getRequestContext(): RequestContext | undefined {\n return storage.getStore();\n}\n\nexport function setCurrentUser(user: Record<string, unknown> | undefined): void {\n const store = storage.getStore();\n if (store) store.user = user;\n}\n\nexport function getCurrentUser(): Record<string, unknown> | undefined {\n return storage.getStore()?.user;\n}\n","import cluster from 'node:cluster';\nimport { randomUUID } from 'node:crypto';\nimport type { RequestHandler } from 'express';\nimport pc from 'picocolors';\nimport { pino, type Logger, type DestinationStream } from 'pino';\nimport type { LoggingConfig } from './types.js';\nimport { getRequestContext } from './context.js';\n\nexport type { Logger };\n\nconst LEVEL_LABELS: Record<number, string> = {\n 10: pc.gray('TRACE'),\n 20: pc.blue('DEBUG'),\n 30: pc.green('INFO '),\n 40: pc.yellow('WARN '),\n 50: pc.red('ERROR'),\n 60: pc.bgRed('FATAL'),\n};\n\nconst OMIT = new Set(['level', 'time', 'msg', 'pid', 'hostname', 'worker', 'reqId']);\n\n// Dev-friendly one-line renderer, so readable output doesn't need pino-pretty or a\n// transport worker thread: `12:00:01 INFO [w2] a1b2c3d4 GET /users 200 (3ms)`.\nfunction prettyStream(out: NodeJS.WritableStream = process.stdout): DestinationStream {\n return {\n write(line: string) {\n let rec: Record<string, unknown>;\n try {\n rec = JSON.parse(line) as Record<string, unknown>;\n } catch {\n out.write(line);\n return;\n }\n const time = new Date(rec['time'] as number).toTimeString().slice(0, 8);\n const level = LEVEL_LABELS[rec['level'] as number] ?? String(rec['level']);\n const worker = rec['worker'] !== undefined ? pc.dim(`[${String(rec['worker'])}] `) : '';\n const reqId = rec['reqId'] ? pc.magenta(String(rec['reqId']).slice(0, 8)) + ' ' : '';\n const extra = Object.entries(rec).filter(([k]) => !OMIT.has(k));\n const err = rec['err'] as { stack?: string } | undefined;\n const fields = extra\n .filter(([k]) => k !== 'err')\n .map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`)\n .join(' ');\n out.write(\n `${pc.dim(time)} ${level} ${worker}${reqId}${String(rec['msg'] ?? '')}` +\n (fields ? ' ' + pc.dim(fields) : '') +\n (err?.stack ? '\\n' + pc.red(err.stack) : '') +\n '\\n',\n );\n },\n };\n}\n\nfunction workerLabel(): string {\n return cluster.isWorker ? `w${cluster.worker?.id ?? '?'}` : 'primary';\n}\n\nfunction build(config: LoggingConfig | false | undefined): Logger {\n if (config === false) return pino({ level: 'silent' });\n const opts = config ?? {};\n const pretty =\n opts.pretty ?? (process.env['NODE_ENV'] !== 'production' && process.stdout.isTTY === true);\n const base = { worker: workerLabel() };\n const level = opts.level ?? 'info';\n return pretty\n ? pino({ level, base, errorKey: 'err' }, prettyStream())\n : pino({ level, base, errorKey: 'err', timestamp: pino.stdTimeFunctions.isoTime });\n}\n\nlet rootLogger: Logger = build(undefined);\nlet logRequests = true;\n\n/** Called by ignite() during Pre-Flight; before that the defaults apply. */\nexport function configureLogger(config: LoggingConfig | false | undefined): void {\n rootLogger = build(config);\n logRequests = config !== false && (config?.requests ?? true);\n}\n\n/**\n * The logger for the current scope: inside a request it is a child carrying that\n * request's `reqId`, so everything logged while handling it can be correlated;\n * elsewhere (startup, task handlers, timers) it is the root logger.\n */\nexport function getLogger(): Logger {\n return getRequestContext()?.log ?? rootLogger;\n}\n\n/** Root logger proxy — always reflects the latest configureLogger() call. */\nexport const logger: Logger = new Proxy({} as Logger, {\n get(_t, prop) {\n const target = getLogger() as unknown as Record<PropertyKey, unknown>;\n const value = target[prop];\n return typeof value === 'function'\n ? (value as (...a: unknown[]) => unknown).bind(target)\n : value;\n },\n});\n\nconst SAFE_REQUEST_ID = /^[\\w.:-]{1,128}$/;\n\n/**\n * Assigns the request ID (trusting a well-formed incoming `X-Request-Id`, e.g. from\n * a load balancer), echoes it back, attaches `req.id` / `req.log`, and logs one\n * line per completed request. Must run inside the request's context.\n */\nexport function requestLogger(): RequestHandler {\n return (req, res, next) => {\n const incoming = req.get('x-request-id');\n const id = incoming && SAFE_REQUEST_ID.test(incoming) ? incoming : randomUUID();\n const log = rootLogger.child({ reqId: id });\n\n req.id = id;\n req.log = log;\n res.setHeader('X-Request-Id', id);\n const ctx = getRequestContext();\n if (ctx) {\n ctx.requestId = id;\n ctx.log = log;\n }\n\n if (logRequests) {\n const start = process.hrtime.bigint();\n res.on('finish', () => {\n const durationMs = Number(process.hrtime.bigint() - start) / 1e6;\n const status = res.statusCode;\n const line = {\n method: req.method,\n url: req.originalUrl,\n status,\n durationMs: Math.round(durationMs * 10) / 10,\n };\n const msg = `${req.method} ${req.originalUrl} ${status}`;\n if (status >= 500) log.error(line, msg);\n else if (status >= 400) log.warn(line, msg);\n else log.info(line, msg);\n });\n }\n next();\n };\n}\n\ndeclare module 'express-serve-static-core' {\n interface Request {\n /** Request ID — the incoming `X-Request-Id` if well-formed, else a UUID. */\n id: string;\n /** Logger bound to this request's ID. */\n log: Logger;\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { LoggingConfig } from '../types.js';\nimport { getRequestContext } from '../context.js';\nimport { getLogger } from '../logger.js';\n\n// Query logging (`logging.queries`): one event per model operation — model, operation,\n// duration, how many database statements it issued, and the request ID — plus slow-query\n// warnings and an N+1 detector. Statements are counted at the driver: Drizzle's logger on\n// PostgreSQL, mongoose's debug hook on MongoDB.\n\n/** One finished model operation. */\nexport interface QueryEvent {\n model: string;\n op: string;\n durationMs: number;\n /** Database statements (SQL statements / MongoDB commands) issued, nested calls included. */\n statements: number;\n /** The request it ran in, if any. */\n reqId?: string;\n /** Set when it threw. */\n error?: string;\n}\n\n/** Aggregated per-process model operation statistics; never contains SQL/parameter values. */\nexport interface QueryMetric {\n model: string;\n op: string;\n calls: number;\n errors: number;\n statements: number;\n totalMs: number;\n minMs: number;\n maxMs: number;\n meanMs: number;\n slow: number;\n}\nexport interface QueryMetricsSnapshot {\n enabled: boolean;\n since: number;\n dropped: number;\n entries: ReadonlyArray<QueryMetric>;\n}\nconst metrics = new Map<string, QueryMetric>();\nlet metricsSince = Date.now();\nlet metricsDropped = 0;\n\n/** Returns detached, deterministically ordered counters; no logs or SQL are exposed. */\nexport function getQueryMetrics(): QueryMetricsSnapshot {\n return {\n enabled: !!config?.metricsLimit,\n since: metricsSince,\n dropped: metricsDropped,\n entries: [...metrics.values()]\n .map((entry) => ({ ...entry }))\n .sort((a, b) => a.model.localeCompare(b.model) || a.op.localeCompare(b.op)),\n };\n}\n/** Clears this process's counters/window; does not disable collection. */\nexport function resetQueryMetrics(): void {\n metrics.clear();\n metricsDropped = 0;\n metricsSince = Date.now();\n}\nfunction collectMetric(event: QueryEvent): void {\n if (!config?.metricsLimit) return;\n const key = event.model + '\\0' + event.op;\n let metric = metrics.get(key);\n if (!metric) {\n if (metrics.size >= config.metricsLimit) {\n metricsDropped++;\n return;\n }\n metric = {\n model: event.model,\n op: event.op,\n calls: 0,\n errors: 0,\n statements: 0,\n totalMs: 0,\n minMs: event.durationMs,\n maxMs: event.durationMs,\n meanMs: 0,\n slow: 0,\n };\n metrics.set(key, metric);\n }\n metric.calls++;\n if (event.error !== undefined) metric.errors++;\n metric.statements += event.statements;\n metric.totalMs += event.durationMs;\n metric.minMs = Math.min(metric.minMs, event.durationMs);\n metric.maxMs = Math.max(metric.maxMs, event.durationMs);\n metric.meanMs = metric.totalMs / metric.calls;\n if (event.durationMs >= config.slowMs) metric.slow++;\n}\n\ninterface Resolved {\n all: boolean;\n slowMs: number;\n nPlusOne: number | false;\n metricsLimit: number;\n}\n\nconst DEFAULTS = { slowMs: 500, nPlusOne: 10 } as const;\n\nlet config: Resolved | undefined;\nconst listeners = new Set<(event: QueryEvent) => void>();\nconst enableHooks: (() => void)[] = [];\n\n/** Called by ignite() during Pre-Flight, next to configureLogger(). */\nexport function configureQueryLog(logging: LoggingConfig | false | undefined): void {\n const q = logging === false ? undefined : logging?.queries;\n config = !q\n ? undefined\n : q === true\n ? { all: true, ...DEFAULTS, metricsLimit: 0 }\n : {\n all: q.all ?? false,\n slowMs: q.slowMs ?? DEFAULTS.slowMs,\n nPlusOne: q.nPlusOne ?? DEFAULTS.nPlusOne,\n metricsLimit: !q.metrics\n ? 0\n : typeof q.metrics === 'object'\n ? (q.metrics.maxEntries ?? 1000)\n : 1000,\n };\n if (config && (!Number.isSafeInteger(config.metricsLimit) || config.metricsLimit < 0)) {\n config = undefined;\n resetQueryMetrics();\n throw new Error('[EFC] logging.queries.metrics.maxEntries must be a nonnegative safe integer');\n }\n resetQueryMetrics();\n if (config) for (const hook of enableHooks) hook();\n}\n\nfunction active(): boolean {\n return config !== undefined || listeners.size > 0;\n}\n\n/**\n * Receives every model operation while subscribed (whether or not `logging.queries` is\n * on). Returns the unsubscribe function. Internal — tests use it to count statements.\n */\nexport function onQuery(listener: (event: QueryEvent) => void): () => void {\n listeners.add(listener);\n for (const hook of enableHooks) hook();\n return () => listeners.delete(listener);\n}\n\n/** Registers a driver hook to install once query tracking is first needed. */\nexport function whenQueryTracking(install: () => void): void {\n enableHooks.push(install);\n if (active()) install();\n}\n\ninterface Frame {\n statements: number;\n parent: Frame | undefined;\n}\n\nconst frames = new AsyncLocalStorage<Frame | undefined>();\n\n/** Called by the driver hooks for each statement sent to the database. */\nexport function countStatement(): void {\n for (let f = frames.getStore(); f; f = f.parent) f.statements++;\n}\n\n/** Runs `fn` outside any operation, so its statements (e.g. auto-sync) are not counted. */\nexport function untracked<R>(fn: () => R): R {\n return frames.run(undefined, fn);\n}\n\n// The first stack frame outside EFC: the line in the app that made the call.\nfunction callSite(callee: (...args: never[]) => unknown): string | undefined {\n const holder: { stack?: string } = {};\n Error.captureStackTrace(holder, callee);\n const line = holder.stack?.split('\\n')[1];\n return line?.trim().replace(/^at /, '');\n}\n\nfunction emit(event: QueryEvent, site: string | undefined, top: boolean): void {\n for (const listener of listeners) listener(event);\n if (!config) return;\n collectMetric(event);\n const log = getLogger();\n const msg = `${event.model}.${event.op} ${event.durationMs}ms`;\n // The request's logger already carries reqId.\n const fields: Partial<QueryEvent> = { ...event };\n delete fields.reqId;\n if (event.durationMs >= config.slowMs) {\n log.warn({ ...fields, slow: true }, `Slow query: ${msg}`);\n } else if (config.all) {\n log.info(fields, msg);\n }\n if (top && config.nPlusOne !== false) detectNPlusOne(event, site, config.nPlusOne);\n}\n\nfunction detectNPlusOne(event: QueryEvent, site: string | undefined, threshold: number): void {\n const ctx = getRequestContext();\n if (!ctx) return;\n const key = `${event.model}.${event.op}`;\n const counts = (ctx.queryCounts ??= new Map());\n const n = (counts.get(key) ?? 0) + 1;\n counts.set(key, n);\n if (n !== threshold) return;\n getLogger().warn(\n { model: event.model, op: event.op, count: n, ...(site !== undefined && { site }) },\n `Possible N+1: ${key} ran ${n} times in one request — load them in one query instead`,\n );\n}\n\n/**\n * Wraps a model's public operations so each call is timed, its statements counted and\n * the result reported. A no-op wrapper while query logging is off.\n */\nexport function traceOps<M extends object>(model: string, target: M, ops: readonly string[]): M {\n const t = target as Record<string, unknown>;\n for (const op of ops) {\n const fn = t[op] as (...args: unknown[]) => Promise<unknown>;\n const traced = function (this: unknown, ...args: unknown[]): Promise<unknown> {\n if (!active()) return fn.apply(this, args);\n const parent = frames.getStore();\n const frame: Frame = { statements: 0, parent };\n // Only N+1 checks need the call site; capture it while the caller is on the stack.\n const site = !parent && config && config.nPlusOne !== false ? callSite(traced) : undefined;\n const start = process.hrtime.bigint();\n const finish = (error?: unknown) => {\n const durationMs = Math.round(Number(process.hrtime.bigint() - start) / 1e5) / 10;\n const reqId = getRequestContext()?.requestId;\n emit(\n {\n model,\n op,\n durationMs,\n statements: frame.statements,\n ...(reqId !== undefined && { reqId }),\n ...(error !== undefined && { error: (error as Error)?.message ?? String(error) }),\n },\n site,\n !parent,\n );\n };\n return frames\n .run(frame, () => fn.apply(this, args))\n .then(\n (result) => {\n finish();\n return result;\n },\n (err: unknown) => {\n finish(err);\n throw err;\n },\n );\n };\n t[op] = traced;\n }\n return target;\n}\n","import { createHash } from 'node:crypto';\nimport type { Pool, PoolClient } from 'pg';\n\nconst invalidators = new WeakMap<Pool, () => void>();\n\n/** Clear reusable shapes after EFC changes a table; existing server names stay bounded. */\nexport function invalidatePreparedStatements(pool: Pool): void {\n invalidators.get(pool)?.();\n}\n\n/**\n * Private Drizzle driver view. The exported native Pool is unchanged. Each real\n * connection owns its names, including connections checked out for transactions.\n * Once its lifetime budget is full, new shapes use the ordinary unnamed protocol.\n */\nexport function preparedDriver(pool: Pool, max: number): Pool {\n if (!Number.isSafeInteger(max) || max < 0) {\n throw new Error('[EFC] databasePool.preparedStatements.max must be a nonnegative safe integer');\n }\n if (max === 0) return pool;\n let generation = 0;\n invalidators.set(pool, () => {\n generation++;\n });\n const clients = new WeakMap<PoolClient, PoolClient>();\n const wrap = (client: PoolClient): PoolClient => {\n const existing = clients.get(client);\n if (existing) return existing;\n let allocated = 0;\n let seenGeneration = generation;\n const names = new Map<string, string>();\n const proxy = new Proxy(client, {\n get(target, prop) {\n if (prop === 'query')\n return (...args: unknown[]) => {\n if (seenGeneration !== generation) {\n names.clear();\n seenGeneration = generation;\n }\n const query = args[0];\n if (query && typeof query === 'object' && 'text' in query) {\n const config = query as Record<string, unknown>;\n const text = config.text;\n // No DDL, transaction control, multi-statements, or caller-named queries.\n if (\n !config.name &&\n typeof text === 'string' &&\n /^\\s*(select|insert|update|delete|with)\\b/i.test(text) &&\n !text.trim().replace(/;$/, '').includes(';')\n ) {\n let name = names.get(text);\n if (!name && allocated < max) {\n name =\n 'efc_auto_' +\n createHash('sha256')\n .update(generation + ':' + text)\n .digest('hex')\n .slice(0, 48);\n names.set(text, name);\n allocated++;\n }\n if (name) args[0] = { ...config, name };\n }\n }\n return Reflect.apply(target.query, target, args);\n };\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n clients.set(client, proxy);\n return proxy;\n };\n return new Proxy(pool, {\n get(target, prop) {\n if (prop === 'connect') return async () => wrap(await target.connect());\n if (prop === 'query')\n return async (...args: unknown[]) => {\n const client = await target.connect();\n // Match Pool.query's connection-error ownership while checked out: do\n // not leave a network error unhandled, and discard failed connections.\n let failure: Error | undefined;\n const onError = (err: Error) => {\n failure = err;\n };\n client.once('error', onError);\n try {\n return await Reflect.apply(wrap(client).query, wrap(client), args);\n } catch (err) {\n failure = err instanceof Error ? err : new Error(String(err));\n throw err;\n } finally {\n client.removeListener('error', onError);\n client.release(failure);\n }\n };\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n","import type { Pool } from 'pg';\nimport { getLogger } from '../logger.js';\nimport { countStatement } from './query-log.js';\nimport type { DatabasePoolConfig } from '../types.js';\nimport { preparedDriver } from './prepared-statements.js';\n\n// Pre-Flight's PostgreSQL connection: a node-postgres Pool (exposed as `db`) plus a\n// Drizzle instance over it that the model adapter queries through.\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- drizzle is an optional peer, loaded dynamically */\nlet pool: Pool | undefined;\n\n/** Only a genuinely missing package becomes \"not installed\"; other load errors surface as-is. */\nexport function notInstalled(err: unknown, pkg: string, install: string): Error {\n const code = (err as { code?: string }).code;\n return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND'\n ? new Error(`[EFC] ${pkg} is not installed. Run: ${install}`)\n : (err as Error);\n}\nlet orm: any;\n\nexport async function connectPostgres(\n url: string,\n poolConfig: DatabasePoolConfig = {},\n): Promise<Pool> {\n let PoolCtor: typeof Pool;\n try {\n const pg = (await import('pg')) as unknown as {\n default?: { Pool: typeof Pool };\n Pool?: typeof Pool;\n };\n PoolCtor = (pg.default?.Pool ?? pg.Pool)!;\n } catch (err) {\n throw notInstalled(err, 'pg', 'npm install pg drizzle-orm');\n }\n let drizzle: (client: Pool, config: object) => unknown;\n try {\n ({ drizzle } = (await import('drizzle-orm/node-postgres')) as unknown as {\n drizzle: (client: Pool, config: object) => unknown;\n });\n } catch (err) {\n throw notInstalled(err, 'drizzle-orm', 'npm install drizzle-orm');\n }\n\n const next = new PoolCtor({\n connectionString: url,\n ...(poolConfig.max !== undefined && { max: poolConfig.max }),\n ...(poolConfig.idleTimeoutMs !== undefined && { idleTimeoutMillis: poolConfig.idleTimeoutMs }),\n ...(poolConfig.connectionTimeoutMs !== undefined && {\n connectionTimeoutMillis: poolConfig.connectionTimeoutMs,\n }),\n });\n const prepared = poolConfig.preparedStatements;\n const maxStatements =\n prepared === false ? 0 : typeof prepared === 'object' ? (prepared.max ?? 100) : 100;\n let driver: Pool;\n try {\n driver = preparedDriver(next, maxStatements);\n } catch (err) {\n await next.end();\n throw err;\n }\n // Idle-client errors (e.g. the server restarting) are emitted on the pool; unhandled\n // they would crash the process.\n next.on('error', (err) => getLogger().error({ err }, 'PostgreSQL pool error'));\n try {\n await next.query('select 1');\n } catch (err) {\n await next.end().catch(() => {});\n throw explainPostgresError(err, url);\n }\n pool = next;\n // Every model statement goes through Drizzle, in or out of a transaction: count it.\n orm = drizzle(driver, { logger: { logQuery: countStatement } });\n getLogger().info('PostgreSQL connected');\n return next;\n}\n\n/** Where a connection string points, without the password (for error messages). */\nfunction describeUrl(url: string): { where: string; user: string; database: string } {\n try {\n const u = new URL(url);\n const database = decodeURIComponent(u.pathname.slice(1)) || '(default)';\n return {\n where: `${u.hostname || 'localhost'}:${u.port || '5432'}`,\n user: decodeURIComponent(u.username) || '(none)',\n database,\n };\n } catch {\n return { where: '(unparsable DATABASE_URL)', user: '?', database: '?' };\n }\n}\n\n/**\n * node-postgres' connection errors, said in terms of DATABASE_URL — e.g. a URL with no password\n * surfaces from pg as \"SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string\".\n * Unrecognised errors come back unchanged. The original is kept as `cause`.\n */\nexport function explainPostgresError(err: unknown, url: string): Error {\n const e = err as { code?: string; message?: string };\n const msg = e.message ?? '';\n const { where, user, database } = describeUrl(url);\n const hosted = 'For Neon, Supabase or RDS, copy the full connection string from the dashboard.';\n let text: string | undefined;\n if (/client password must be a string/.test(msg)) {\n text = `PostgreSQL asked for a password and DATABASE_URL has none (user \"${user}\" at ${where}). Put it in the URL: postgres://${user === '(none)' ? 'user' : user}:<password>@${where}/${database === '(default)' ? 'db' : database}. ${hosted}`;\n } else if (e.code === '28P01') {\n text = `PostgreSQL rejected the password for user \"${user}\" at ${where}. Check DATABASE_URL (special characters in the password must be URL-encoded). ${hosted}`;\n } else if (e.code === '28000' && /role .* does not exist/.test(msg)) {\n text = `PostgreSQL has no user \"${user}\" at ${where}. Create it (CREATE ROLE ${user} LOGIN PASSWORD '…';) or fix the user in DATABASE_URL.`;\n } else if (/no pg_hba\\.conf entry.*no encryption/.test(msg)) {\n text = `PostgreSQL at ${where} only accepts encrypted connections. Add ?sslmode=require to DATABASE_URL.`;\n } else if (e.code === '28000') {\n text = `PostgreSQL at ${where} refused user \"${user}\": ${msg}`;\n } else if (e.code === '3D000') {\n text = `Database \"${database}\" does not exist at ${where}. Create it first: createdb ${database} (or CREATE DATABASE \"${database}\";).`;\n } else if (/does not support SSL/.test(msg)) {\n text = `PostgreSQL at ${where} doesn't support SSL. Remove sslmode / ssl from DATABASE_URL (local servers usually run without it).`;\n } else if (e.code === 'ECONNREFUSED') {\n text = `Nothing is accepting connections at ${where}. Is PostgreSQL running, and is the host/port in DATABASE_URL right?`;\n } else if (e.code === 'ENOTFOUND' || e.code === 'EAI_AGAIN') {\n text = `Can't resolve the PostgreSQL host in DATABASE_URL (${where}). Check the hostname.`;\n } else if (e.code === 'ETIMEDOUT' || /timeout/i.test(msg)) {\n text = `Timed out connecting to PostgreSQL at ${where}. Check the host, and that a firewall / the provider's IP allow-list lets this machine in.`;\n }\n return text ? new Error(`[EFC] ${text}`, { cause: err }) : (err as Error);\n}\n\n/**\n * Every cluster worker opens its own pools, so a machine's total is `workers × (pool + …)`.\n * Logs that total against the server's limit, warning when this machine alone can exhaust it.\n * Best effort: a failure to read the limit is ignored.\n */\nexport async function checkConnectionBudget(perMachine: number, breakdown: string): Promise<void> {\n const log = getLogger();\n try {\n const { rows } = await getPool().query<{ max: number; reserved: number }>(\n `select current_setting('max_connections')::int as max,\n current_setting('superuser_reserved_connections')::int as reserved`,\n );\n const { max, reserved } = rows[0]!;\n const usable = max - reserved;\n if (perMachine > usable) {\n log.warn(\n `[EFC] PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}), but the server allows ${usable} (max_connections ${max} − ${reserved} reserved). Under load, queries will fail with \"too many clients\". Lower databasePool.max or workers, or put PgBouncer in front.`,\n );\n } else {\n log.info(\n `PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}) of ${usable} allowed — multiply by your instance count if you run several`,\n );\n }\n } catch {\n /* can't read the limit (permissions, pooler) — nothing to compare against */\n }\n}\n\nexport function getOrm(): any {\n if (!orm) {\n throw new Error(\n '[EFC] PostgreSQL not connected — set database/databaseUrl in ignite() (or call connectPostgres)',\n );\n }\n return orm;\n}\n\nexport function getPool(): Pool {\n if (!pool) throw new Error('[EFC] PostgreSQL not connected');\n return pool;\n}\n\nexport async function closePostgres(): Promise<void> {\n const p = pool;\n pool = undefined;\n orm = undefined;\n await p?.end();\n}\n"]}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isHttpError
|
|
3
|
+
} from "./chunk-XPY5TQDK.js";
|
|
4
|
+
import {
|
|
5
|
+
getLogger,
|
|
6
|
+
requestLogger,
|
|
7
|
+
runWithContext
|
|
8
|
+
} from "./chunk-V73R76I4.js";
|
|
9
|
+
|
|
10
|
+
// src/router/validate.ts
|
|
11
|
+
var LOCATIONS = ["params", "query", "body"];
|
|
12
|
+
function isRequestSchema(value) {
|
|
13
|
+
return value != null && typeof value === "object" && LOCATIONS.some((loc) => loc in value);
|
|
14
|
+
}
|
|
15
|
+
function schemaFor(schema, method) {
|
|
16
|
+
if (!schema) return void 0;
|
|
17
|
+
const byMethod = schema[method];
|
|
18
|
+
if (isRequestSchema(byMethod)) return byMethod;
|
|
19
|
+
return isRequestSchema(schema) ? schema : void 0;
|
|
20
|
+
}
|
|
21
|
+
function pathToString(path) {
|
|
22
|
+
if (!path) return "";
|
|
23
|
+
return path.map((p) => typeof p === "object" && p !== null && "key" in p ? p.key : p).map(String).join(".");
|
|
24
|
+
}
|
|
25
|
+
async function run(validator, input) {
|
|
26
|
+
const std = validator["~standard"];
|
|
27
|
+
if (std && typeof std.validate === "function") {
|
|
28
|
+
return await std.validate(input);
|
|
29
|
+
}
|
|
30
|
+
const v = validator;
|
|
31
|
+
const parse = v.safeParseAsync ?? v.safeParse;
|
|
32
|
+
if (typeof parse !== "function") {
|
|
33
|
+
throw new Error("[EFC] Route schema entries must be Standard Schema validators (e.g. zod)");
|
|
34
|
+
}
|
|
35
|
+
const r = await parse.call(validator, input);
|
|
36
|
+
return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: "Invalid" }] };
|
|
37
|
+
}
|
|
38
|
+
function validateRequest(schema) {
|
|
39
|
+
return (req, res, next) => {
|
|
40
|
+
void (async () => {
|
|
41
|
+
const issues = [];
|
|
42
|
+
const parsed = {};
|
|
43
|
+
for (const location of LOCATIONS) {
|
|
44
|
+
const validator = schema[location];
|
|
45
|
+
if (!validator) continue;
|
|
46
|
+
const result = await run(validator, req[location]);
|
|
47
|
+
if (result.issues) {
|
|
48
|
+
for (const issue of result.issues) {
|
|
49
|
+
issues.push({ location, path: pathToString(issue.path), message: issue.message });
|
|
50
|
+
}
|
|
51
|
+
} else {
|
|
52
|
+
parsed[location] = result.value;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (issues.length > 0) {
|
|
56
|
+
res.status(400).json({ error: "Validation failed", statusCode: 400, issues });
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
for (const location of LOCATIONS) {
|
|
60
|
+
if (location in parsed) {
|
|
61
|
+
Object.defineProperty(req, location, {
|
|
62
|
+
value: parsed[location],
|
|
63
|
+
writable: true,
|
|
64
|
+
configurable: true,
|
|
65
|
+
enumerable: true
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
next();
|
|
70
|
+
})().catch(next);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/router/mount.ts
|
|
75
|
+
var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
76
|
+
function asyncWrap(handler) {
|
|
77
|
+
return (req, res, next) => {
|
|
78
|
+
Promise.resolve(handler(req, res, next)).catch(next);
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function namedParams(route) {
|
|
82
|
+
const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\*/g)].map((m) => m[1]));
|
|
83
|
+
return (req, _res, next) => {
|
|
84
|
+
const captures = route.pattern.exec(req.path);
|
|
85
|
+
const named = {};
|
|
86
|
+
route.params.forEach((name, i) => {
|
|
87
|
+
const value = captures?.[i + 1];
|
|
88
|
+
if (value === void 0 || value === "") {
|
|
89
|
+
named[name] = catchAlls.has(name) ? [] : void 0;
|
|
90
|
+
} else if (catchAlls.has(name)) {
|
|
91
|
+
named[name] = value.split("/").filter(Boolean).map(decodeURIComponent);
|
|
92
|
+
} else {
|
|
93
|
+
named[name] = decodeURIComponent(value);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
req.params = named;
|
|
97
|
+
next();
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
async function mountRoutes(app, routes) {
|
|
101
|
+
const mounted = [];
|
|
102
|
+
for (const route of routes) {
|
|
103
|
+
const mod = await import(route.filePath);
|
|
104
|
+
const routeMiddlewares = Array.isArray(mod["middlewares"]) ? mod["middlewares"] : [];
|
|
105
|
+
const raw = mod["meta"];
|
|
106
|
+
const meta = raw != null && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
|
|
107
|
+
const schema = mod["schema"] != null && typeof mod["schema"] === "object" ? mod["schema"] : void 0;
|
|
108
|
+
const routePath = route.pattern ?? route.urlPath;
|
|
109
|
+
const paramMapper = route.pattern ? [namedParams(route)] : [];
|
|
110
|
+
const implemented = [];
|
|
111
|
+
const unimplemented = [];
|
|
112
|
+
for (const method of HTTP_METHODS) {
|
|
113
|
+
if (typeof mod[method] === "function") {
|
|
114
|
+
implemented.push(method);
|
|
115
|
+
const methodSchema = schemaFor(schema, method);
|
|
116
|
+
const validation = methodSchema ? [validateRequest(methodSchema)] : [];
|
|
117
|
+
app[method.toLowerCase()](
|
|
118
|
+
routePath,
|
|
119
|
+
...paramMapper,
|
|
120
|
+
...routeMiddlewares,
|
|
121
|
+
...validation,
|
|
122
|
+
asyncWrap(mod[method])
|
|
123
|
+
);
|
|
124
|
+
} else {
|
|
125
|
+
unimplemented.push(method);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (implemented.length > 0 && unimplemented.length > 0) {
|
|
129
|
+
const allowHeader = implemented.join(", ");
|
|
130
|
+
app.all(routePath, (req, res, next) => {
|
|
131
|
+
if (unimplemented.includes(req.method)) {
|
|
132
|
+
res.set("Allow", allowHeader).status(405).json({ error: "Method Not Allowed" });
|
|
133
|
+
} else {
|
|
134
|
+
next();
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
mounted.push({ ...route, methods: implemented, ...meta !== void 0 && { meta } });
|
|
139
|
+
}
|
|
140
|
+
return mounted;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// src/http-app.ts
|
|
144
|
+
import express from "express";
|
|
145
|
+
import cors from "cors";
|
|
146
|
+
import cookieParser from "cookie-parser";
|
|
147
|
+
function createHttpApp(config) {
|
|
148
|
+
const globalMiddlewares = config.globalMiddlewares ?? [];
|
|
149
|
+
const app = express();
|
|
150
|
+
if (config.trustProxy !== void 0) app.set("trust proxy", config.trustProxy);
|
|
151
|
+
app.set(
|
|
152
|
+
"json replacer",
|
|
153
|
+
(_key, value) => typeof value === "bigint" ? value.toString() : value
|
|
154
|
+
);
|
|
155
|
+
app.use((_req, _res, next) => {
|
|
156
|
+
runWithContext({}, next);
|
|
157
|
+
});
|
|
158
|
+
app.use(requestLogger());
|
|
159
|
+
if (config.requestTimeout) {
|
|
160
|
+
const ms = config.requestTimeout;
|
|
161
|
+
app.use((_req, res, next) => {
|
|
162
|
+
const timer = setTimeout(() => {
|
|
163
|
+
if (!res.headersSent) res.status(408).json({ error: "Request Timeout", statusCode: 408 });
|
|
164
|
+
}, ms);
|
|
165
|
+
const clear = () => clearTimeout(timer);
|
|
166
|
+
res.once("finish", clear);
|
|
167
|
+
res.once("close", clear);
|
|
168
|
+
next();
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
const corsOption = config.cors ?? true;
|
|
172
|
+
if (corsOption !== false) {
|
|
173
|
+
const origin = typeof corsOption === "object" && corsOption.origin !== void 0 ? corsOption.origin : true;
|
|
174
|
+
const corsOpts = typeof corsOption === "object" ? { ...corsOption, origin } : { origin };
|
|
175
|
+
app.use(cors(corsOpts));
|
|
176
|
+
}
|
|
177
|
+
app.use(express.json());
|
|
178
|
+
app.use(express.urlencoded({ extended: true }));
|
|
179
|
+
app.use(cookieParser());
|
|
180
|
+
for (const mw of globalMiddlewares) {
|
|
181
|
+
app.use(mw);
|
|
182
|
+
}
|
|
183
|
+
return app;
|
|
184
|
+
}
|
|
185
|
+
function mountErrorHandler(app, onError) {
|
|
186
|
+
if (onError) {
|
|
187
|
+
app.use(onError);
|
|
188
|
+
} else {
|
|
189
|
+
app.use(
|
|
190
|
+
(err, _req, res, _next) => {
|
|
191
|
+
if (res.headersSent) {
|
|
192
|
+
getLogger().warn({ err }, "Error after the response was sent");
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const status = err?.statusCode;
|
|
196
|
+
const duckTyped = err instanceof Error && typeof status === "number" && status >= 400 && status < 500 ? err : null;
|
|
197
|
+
if (isHttpError(err)) {
|
|
198
|
+
const issues = err.issues;
|
|
199
|
+
res.status(err.statusCode).json({
|
|
200
|
+
error: err.message,
|
|
201
|
+
statusCode: err.statusCode,
|
|
202
|
+
...issues !== void 0 && { issues }
|
|
203
|
+
});
|
|
204
|
+
} else if (duckTyped) {
|
|
205
|
+
res.status(duckTyped.statusCode).json({ error: duckTyped.message, statusCode: duckTyped.statusCode });
|
|
206
|
+
} else {
|
|
207
|
+
getLogger().error({ err }, "Unhandled error");
|
|
208
|
+
res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export {
|
|
216
|
+
mountRoutes,
|
|
217
|
+
createHttpApp,
|
|
218
|
+
mountErrorHandler
|
|
219
|
+
};
|
|
220
|
+
//# sourceMappingURL=chunk-KLWL7XSC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/validate.ts","../src/router/mount.ts","../src/http-app.ts"],"sourcesContent":["import type { Request, RequestHandler } from 'express';\nimport type { RequestSchema, RouteSchema, ValidationIssue, Validator } from '../types.js';\n\nconst LOCATIONS = ['params', 'query', 'body'] as const;\ntype Location = (typeof LOCATIONS)[number];\n\ninterface StandardResult {\n value?: unknown;\n issues?: ReadonlyArray<{\n message: string;\n path?: ReadonlyArray<PropertyKey | { key: PropertyKey }>;\n }>;\n}\n\nfunction isRequestSchema(value: unknown): value is RequestSchema {\n return (\n value != null &&\n typeof value === 'object' &&\n LOCATIONS.some((loc) => loc in (value as Record<string, unknown>))\n );\n}\n\n/** Picks the schema for `method`: a method-keyed entry wins over a file-wide one. */\nexport function schemaFor(\n schema: RouteSchema | undefined,\n method: string,\n): RequestSchema | undefined {\n if (!schema) return undefined;\n const byMethod = (schema as Record<string, unknown>)[method];\n if (isRequestSchema(byMethod)) return byMethod;\n return isRequestSchema(schema) ? schema : undefined;\n}\n\ntype IssuePath = ReadonlyArray<PropertyKey | { key: PropertyKey }> | undefined;\n\nfunction pathToString(path: IssuePath): string {\n if (!path) return '';\n return path\n .map((p) => (typeof p === 'object' && p !== null && 'key' in p ? p.key : p))\n .map(String)\n .join('.');\n}\n\n// Standard Schema (zod >=3.24, valibot, arktype, ...) first; plain zod-style\n// safeParse as a fallback so older zod 3 releases work too.\nasync function run(validator: Validator, input: unknown): Promise<StandardResult> {\n const std = (validator as { '~standard'?: { validate: (v: unknown) => unknown } })['~standard'];\n if (std && typeof std.validate === 'function') {\n return (await std.validate(input)) as StandardResult;\n }\n const v = validator as {\n safeParseAsync?: (x: unknown) => Promise<unknown>;\n safeParse?: (x: unknown) => unknown;\n };\n const parse = v.safeParseAsync ?? v.safeParse;\n if (typeof parse !== 'function') {\n throw new Error('[EFC] Route schema entries must be Standard Schema validators (e.g. zod)');\n }\n const r = (await parse.call(validator, input)) as {\n success: boolean;\n data?: unknown;\n error?: { issues: Array<{ message: string; path: PropertyKey[] }> };\n };\n return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: 'Invalid' }] };\n}\n\n/**\n * Validates params/query/body against the route's schema. On success the parsed\n * output replaces the raw input (so coercions and defaults apply); on failure\n * responds 400 with every issue across all locations.\n */\nexport function validateRequest(schema: RequestSchema): RequestHandler {\n return (req, res, next) => {\n void (async () => {\n const issues: ValidationIssue[] = [];\n const parsed: Partial<Record<Location, unknown>> = {};\n\n for (const location of LOCATIONS) {\n const validator = schema[location];\n if (!validator) continue;\n const result = await run(validator, req[location]);\n if (result.issues) {\n for (const issue of result.issues) {\n issues.push({ location, path: pathToString(issue.path), message: issue.message });\n }\n } else {\n parsed[location] = result.value;\n }\n }\n\n if (issues.length > 0) {\n res.status(400).json({ error: 'Validation failed', statusCode: 400, issues });\n return;\n }\n\n for (const location of LOCATIONS) {\n if (location in parsed) {\n // req.query is a getter in some Express setups — define rather than assign.\n Object.defineProperty(req as Request, location, {\n value: parsed[location],\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n next();\n })().catch(next);\n };\n}\n","import type { IRouter, RequestHandler } from 'express';\nimport type { MountedRoute, RouteMeta, RouteEntry, RouteSchema } from '../types.js';\nimport { schemaFor, validateRequest } from './validate.js';\n\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\ntype HttpMethod = (typeof HTTP_METHODS)[number];\n\nfunction asyncWrap(handler: RequestHandler): RequestHandler {\n return (req, res, next) => {\n Promise.resolve(handler(req, res, next)).catch(next);\n };\n}\n\n/**\n * For RegExp-mounted (catch-all) routes, Express exposes captures as params[0..n].\n * Rename them to the segment names from the file path; catch-alls become string\n * arrays (`[...slug]` → `['a', 'b']`), absent optional segments become undefined.\n */\nfunction namedParams(route: RouteEntry): RequestHandler {\n const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\\*/g)].map((m) => m[1]!));\n return (req, _res, next) => {\n // Express has already decoded req.params. Read the raw captures so splitting\n // happens before decoding (an encoded slash belongs to a single segment).\n const captures = route.pattern!.exec(req.path);\n const named: Record<string, unknown> = {};\n route.params.forEach((name, i) => {\n const value = captures?.[i + 1];\n if (value === undefined || value === '') {\n named[name] = catchAlls.has(name) ? [] : undefined;\n } else if (catchAlls.has(name)) {\n named[name] = value.split('/').filter(Boolean).map(decodeURIComponent);\n } else {\n named[name] = decodeURIComponent(value);\n }\n });\n req.params = named as typeof req.params;\n next();\n };\n}\n\nexport async function mountRoutes(app: IRouter, routes: RouteEntry[]): Promise<MountedRoute[]> {\n const mounted: MountedRoute[] = [];\n\n for (const route of routes) {\n const mod = (await import(route.filePath)) as Record<string, unknown>;\n const routeMiddlewares: RequestHandler[] = Array.isArray(mod['middlewares'])\n ? (mod['middlewares'] as RequestHandler[])\n : [];\n\n const raw = mod['meta'];\n const meta: RouteMeta | undefined =\n raw != null && typeof raw === 'object' && !Array.isArray(raw)\n ? (raw as RouteMeta)\n : undefined;\n\n const schema =\n mod['schema'] != null && typeof mod['schema'] === 'object'\n ? (mod['schema'] as RouteSchema)\n : undefined;\n\n const routePath = route.pattern ?? route.urlPath;\n const paramMapper = route.pattern ? [namedParams(route)] : [];\n\n const implemented: HttpMethod[] = [];\n const unimplemented: HttpMethod[] = [];\n\n for (const method of HTTP_METHODS) {\n if (typeof mod[method] === 'function') {\n implemented.push(method);\n const methodSchema = schemaFor(schema, method);\n const validation = methodSchema ? [validateRequest(methodSchema)] : [];\n app[method.toLowerCase() as Lowercase<HttpMethod>](\n routePath,\n ...paramMapper,\n ...routeMiddlewares,\n ...validation,\n asyncWrap(mod[method] as RequestHandler),\n );\n } else {\n unimplemented.push(method);\n }\n }\n\n if (implemented.length > 0 && unimplemented.length > 0) {\n const allowHeader = implemented.join(', ');\n app.all(routePath, (req, res, next) => {\n if ((unimplemented as string[]).includes(req.method)) {\n res.set('Allow', allowHeader).status(405).json({ error: 'Method Not Allowed' });\n } else {\n next();\n }\n });\n }\n\n mounted.push({ ...route, methods: implemented, ...(meta !== undefined && { meta }) });\n }\n\n return mounted;\n}\n\nexport { asyncWrap };\n","import express from 'express';\nimport cors from 'cors';\nimport cookieParser from 'cookie-parser';\nimport type { EFCConfig } from './types.js';\nimport { runWithContext } from './context.js';\nimport { requestLogger, getLogger } from './logger.js';\nimport { isHttpError } from './errors.js';\n\n/** Shared production/test HTTP middleware stack; service boot remains in ignite(). */\nexport function createHttpApp(config: EFCConfig): express.Express {\n const globalMiddlewares = config.globalMiddlewares ?? [];\n const app = express();\n if (config.trustProxy !== undefined) app.set('trust proxy', config.trustProxy);\n // defineTable returns `bigint` for bigint columns and bigserial ids, which JSON.stringify\n // rejects; send them as strings (exact — a JS number would lose precision past 2^53).\n app.set('json replacer', (_key: string, value: unknown) =>\n typeof value === 'bigint' ? value.toString() : value,\n );\n\n // Wraps every request in its own AsyncLocalStorage context, first thing, so\n // requireAuth (below) and any downstream code — including a `$currentUser`\n // default resolved inside a mongoose `.create()` call — share the same store.\n app.use((_req, _res, next) => {\n runWithContext({}, next);\n });\n app.use(requestLogger());\n\n if (config.requestTimeout) {\n const ms = config.requestTimeout;\n app.use((_req, res, next) => {\n const timer = setTimeout(() => {\n if (!res.headersSent) res.status(408).json({ error: 'Request Timeout', statusCode: 408 });\n }, ms);\n const clear = () => clearTimeout(timer);\n res.once('finish', clear);\n res.once('close', clear);\n next();\n });\n }\n\n const corsOption = config.cors ?? true;\n if (corsOption !== false) {\n const origin =\n typeof corsOption === 'object' && corsOption.origin !== undefined ? corsOption.origin : true;\n const corsOpts = typeof corsOption === 'object' ? { ...corsOption, origin } : { origin };\n app.use(cors(corsOpts));\n }\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n for (const mw of globalMiddlewares) {\n app.use(mw);\n }\n\n return app;\n}\n\nexport function mountErrorHandler(\n app: express.Express,\n onError?: express.ErrorRequestHandler,\n): void {\n if (onError) {\n app.use(onError);\n } else {\n app.use(\n (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {\n // e.g. a handler that kept going after requestTimeout already answered 408.\n if (res.headersSent) {\n getLogger().warn({ err }, 'Error after the response was sent');\n return;\n }\n // isHttpError() covers the common case, but errors can also arrive as plain\n // objects with a numeric statusCode (e.g. thrown across a module boundary, or\n // duck-typed by user code) — fall back to that shape before giving up to 500.\n // Only 4xx: a library's 5xx message can describe internals (hosts, SQL, paths).\n const status = (err as { statusCode?: unknown } | null)?.statusCode;\n const duckTyped =\n err instanceof Error && typeof status === 'number' && status >= 400 && status < 500\n ? (err as Error & { statusCode: number })\n : null;\n\n if (isHttpError(err)) {\n // ModelValidationError carries per-field issues; surface them like route validation does.\n const issues = (err as { issues?: unknown }).issues;\n res.status(err.statusCode).json({\n error: err.message,\n statusCode: err.statusCode,\n ...(issues !== undefined && { issues }),\n });\n } else if (duckTyped) {\n res\n .status(duckTyped.statusCode)\n .json({ error: duckTyped.message, statusCode: duckTyped.statusCode });\n } else {\n getLogger().error({ err }, 'Unhandled error');\n res.status(500).json({ error: 'Internal Server Error', statusCode: 500 });\n }\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAGA,IAAM,YAAY,CAAC,UAAU,SAAS,MAAM;AAW5C,SAAS,gBAAgB,OAAwC;AAC/D,SACE,SAAS,QACT,OAAO,UAAU,YACjB,UAAU,KAAK,CAAC,QAAQ,OAAQ,KAAiC;AAErE;AAGO,SAAS,UACd,QACA,QAC2B;AAC3B,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,WAAY,OAAmC,MAAM;AAC3D,MAAI,gBAAgB,QAAQ,EAAG,QAAO;AACtC,SAAO,gBAAgB,MAAM,IAAI,SAAS;AAC5C;AAIA,SAAS,aAAa,MAAyB;AAC7C,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KACJ,IAAI,CAAC,MAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,SAAS,IAAI,EAAE,MAAM,CAAE,EAC1E,IAAI,MAAM,EACV,KAAK,GAAG;AACb;AAIA,eAAe,IAAI,WAAsB,OAAyC;AAChF,QAAM,MAAO,UAAsE,WAAW;AAC9F,MAAI,OAAO,OAAO,IAAI,aAAa,YAAY;AAC7C,WAAQ,MAAM,IAAI,SAAS,KAAK;AAAA,EAClC;AACA,QAAM,IA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