express-file-cluster 0.10.0 → 0.11.0
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 +3 -1
- package/dist/auth/index.d.ts +3 -1
- package/dist/auth/index.js +5 -5
- package/dist/{chunk-73XJUT2S.js → chunk-2IDRC7RK.js} +163 -5
- package/dist/chunk-2IDRC7RK.js.map +1 -0
- package/dist/{chunk-QDEDOHP7.js → chunk-336IU55W.js} +9 -42
- package/dist/chunk-336IU55W.js.map +1 -0
- package/dist/{chunk-R52CUEGT.js → chunk-3SWI46YK.js} +2 -2
- package/dist/{chunk-7KO4DJRJ.cjs → chunk-6WTMRZS7.cjs} +14 -14
- package/dist/{chunk-7KO4DJRJ.cjs.map → chunk-6WTMRZS7.cjs.map} +1 -1
- package/dist/chunk-AGOYTFRO.cjs +42 -0
- package/dist/chunk-AGOYTFRO.cjs.map +1 -0
- package/dist/{chunk-RAB44UGX.js → chunk-B6MB6HEG.js} +1 -1
- package/dist/chunk-CGY7JU4Y.cjs +8 -0
- package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
- package/dist/chunk-DGYPIIJE.cjs +845 -0
- package/dist/chunk-DGYPIIJE.cjs.map +1 -0
- package/dist/{chunk-EGSSZUVO.js → chunk-DN4TCGYB.js} +38 -11
- package/dist/chunk-DN4TCGYB.js.map +1 -0
- package/dist/{chunk-YK4ZM3CA.cjs → chunk-DTMDJGRW.cjs} +15 -15
- package/dist/{chunk-YK4ZM3CA.cjs.map → chunk-DTMDJGRW.cjs.map} +1 -1
- package/dist/{chunk-R4XO4SVM.js → chunk-EJDZZ4KX.js} +4 -4
- package/dist/{chunk-NKLOE4AK.cjs → chunk-GWMW6XY7.cjs} +20 -53
- package/dist/chunk-GWMW6XY7.cjs.map +1 -0
- package/dist/{chunk-GBI77W5T.cjs → chunk-H2PVWCWC.cjs} +1 -1
- package/dist/{chunk-GBI77W5T.cjs.map → chunk-H2PVWCWC.cjs.map} +1 -1
- package/dist/{chunk-KFVFP2Q7.cjs → chunk-IEF6AEK3.cjs} +70 -55
- package/dist/chunk-IEF6AEK3.cjs.map +1 -0
- package/dist/{chunk-PGJQK36V.js → chunk-JBOMTZT5.js} +7 -5
- package/dist/{chunk-PGJQK36V.js.map → chunk-JBOMTZT5.js.map} +1 -1
- package/dist/chunk-LECHRAU3.js +845 -0
- package/dist/chunk-LECHRAU3.js.map +1 -0
- package/dist/{chunk-4DOHQU6I.cjs → chunk-M53GODCX.cjs} +39 -12
- package/dist/chunk-M53GODCX.cjs.map +1 -0
- package/dist/{chunk-NI2BNGGV.js → chunk-O2E7H2XA.js} +2 -2
- package/dist/{chunk-ATVD2HGC.js → chunk-OM2XJJWX.js} +4 -4
- package/dist/{chunk-DUADUR6R.cjs → chunk-QSIP7YLW.cjs} +172 -14
- package/dist/chunk-QSIP7YLW.cjs.map +1 -0
- package/dist/{chunk-7KC2H76D.js → chunk-R6GPQZLI.js} +62 -47
- package/dist/chunk-R6GPQZLI.js.map +1 -0
- package/dist/{chunk-WBLUGOAG.cjs → chunk-RPL2IFWK.cjs} +8 -5
- package/dist/chunk-RPL2IFWK.cjs.map +1 -0
- package/dist/{chunk-HBCY7ILD.cjs → chunk-SOU3PBJC.cjs} +97 -95
- package/dist/chunk-SOU3PBJC.cjs.map +1 -0
- package/dist/{chunk-DCJOWFVD.cjs → chunk-WHBSVYUY.cjs} +3 -3
- package/dist/{chunk-DCJOWFVD.cjs.map → chunk-WHBSVYUY.cjs.map} +1 -1
- package/dist/chunk-XPY5TQDK.js +42 -0
- package/dist/chunk-XPY5TQDK.js.map +1 -0
- package/dist/cli/db-runner.cjs +81 -42
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +54 -16
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +23 -25
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +12 -17
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +23 -0
- 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 +8 -1
- package/dist/docs/api-reference/openapi.md +36 -0
- package/dist/docs/api-reference/testing.md +28 -0
- package/dist/docs/api-reference/websockets.md +23 -0
- package/dist/docs/cli/add.md +2 -2
- package/dist/docs/core-concepts/clustering.md +2 -0
- package/dist/docs/core-concepts/file-based-routing.md +4 -0
- package/dist/docs/core-concepts/middleware.md +2 -2
- package/dist/docs/getting-started/index.md +4 -0
- package/dist/docs/guides/authentication.md +33 -0
- package/dist/docs/guides/caching.md +2 -0
- package/dist/docs/guides/database.md +15 -0
- package/dist/docs/guides/environment-variables.md +6 -0
- package/dist/docs/guides/feature-matrix.md +9 -0
- package/dist/docs/guides/generated-portals.md +3 -1
- package/dist/docs/guides/logging.md +17 -0
- package/dist/docs/guides/migrations.md +4 -2
- package/dist/docs/guides/openapi.md +57 -0
- package/dist/docs/guides/testing.md +31 -0
- package/dist/docs/guides/validation.md +2 -0
- package/dist/docs/guides/websockets.md +60 -0
- package/dist/docs/index.md +4 -1
- package/dist/docs/skills/SKILL.md +8 -2
- package/dist/docs/skills/api-surface.md +30 -4
- package/dist/docs/skills/auth-internals.md +14 -1
- package/dist/docs/skills/pre-flight.md +8 -0
- package/dist/docs/skills/routing-rules.md +5 -1
- package/dist/docs/skills/what-not-to-invent.md +11 -1
- package/dist/docs/versioning.md +1 -1
- package/dist/index.cjs +100 -267
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -3
- package/dist/index.d.ts +28 -3
- package/dist/index.js +52 -221
- package/dist/index.js.map +1 -1
- package/dist/openapi-cjs.cjs +5 -0
- package/dist/pgboss-backend-PQW6I3VF.js +14 -0
- package/dist/pgboss-backend-QVXISTLP.cjs +15 -0
- package/dist/pgboss-backend-QVXISTLP.cjs.map +1 -0
- package/dist/registry/index.json +27 -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/account-security.json +1 -1
- package/dist/registry/js-mongo-collection/admin-users.json +1 -1
- package/dist/registry/js-mongo-collection/auth.json +1 -1
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -1
- package/dist/registry/js-mongo-collection/auth@google.json +1 -1
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -1
- package/dist/registry/js-mongo-collection/user-profile.json +1 -1
- 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/account-security.json +1 -1
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -1
- package/dist/registry/ts-mongo-collection/auth.json +1 -1
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -1
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -1
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -1
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -1
- 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 +3 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +3 -1
- package/dist/tasks/index.d.ts +3 -1
- package/dist/tasks/index.js +1 -1
- package/dist/testing-cjs.cjs +5 -0
- package/dist/testing.cjs +65 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +30 -0
- package/dist/testing.d.ts +30 -0
- package/dist/testing.js +64 -0
- package/dist/testing.js.map +1 -0
- package/dist/thread-runner.cjs +4 -3
- package/dist/thread-runner.cjs.map +1 -1
- package/dist/thread-runner.js +2 -2
- package/dist/{types-Bnxvj3l0.d.ts → types-D3QmZgeX.d.cts} +88 -2
- package/dist/{types-Bnxvj3l0.d.cts → types-D3QmZgeX.d.ts} +88 -2
- package/package.json +11 -4
- package/dist/chunk-4DOHQU6I.cjs.map +0 -1
- package/dist/chunk-73XJUT2S.js.map +0 -1
- package/dist/chunk-7KC2H76D.js.map +0 -1
- package/dist/chunk-DUADUR6R.cjs.map +0 -1
- package/dist/chunk-EGSSZUVO.js.map +0 -1
- package/dist/chunk-HBCY7ILD.cjs.map +0 -1
- package/dist/chunk-KFVFP2Q7.cjs.map +0 -1
- package/dist/chunk-NKLOE4AK.cjs.map +0 -1
- package/dist/chunk-QDEDOHP7.js.map +0 -1
- package/dist/chunk-WBLUGOAG.cjs.map +0 -1
- package/dist/pgboss-backend-FW42SBSM.js +0 -14
- package/dist/pgboss-backend-RVHUBJTU.cjs +0 -14
- package/dist/pgboss-backend-RVHUBJTU.cjs.map +0 -1
- /package/dist/{chunk-R52CUEGT.js.map → chunk-3SWI46YK.js.map} +0 -0
- /package/dist/{chunk-RAB44UGX.js.map → chunk-B6MB6HEG.js.map} +0 -0
- /package/dist/{chunk-R4XO4SVM.js.map → chunk-EJDZZ4KX.js.map} +0 -0
- /package/dist/{chunk-NI2BNGGV.js.map → chunk-O2E7H2XA.js.map} +0 -0
- /package/dist/{chunk-ATVD2HGC.js.map → chunk-OM2XJJWX.js.map} +0 -0
- /package/dist/{pgboss-backend-FW42SBSM.js.map → pgboss-backend-PQW6I3VF.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/index.cjs","../src/index.ts","../src/router/validate.ts","../src/router/mount.ts","../src/cluster/index.ts","../src/tasks/scanner.ts","../src/dashboard.ts","../src/rate-limit.ts","../src/cache/response.ts","../src/compose.ts"],"names":["path"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B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I,MAAA;AACf,IAAA;AACU,MAAA;AAEE,MAAA;AACG,QAAA;AACJ,QAAA;AACY,MAAA;AAC9B,IAAA;AACF,EAAA;AAC+C,EAAA;AACF,EAAA;AAC/C;ADo1BqD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/index.cjs","sourcesContent":[null,"import type http from 'node:http';\nimport fs from 'node:fs';\nimport express from 'express';\nimport cors from 'cors';\nimport cookieParser from 'cookie-parser';\nimport cluster from 'node:cluster';\nimport os from 'node:os';\nimport path from 'node:path';\nimport type { EFCConfig, MountedRoute } from './types.js';\nexport type {\n TableModel,\n TableRecord,\n TableCreateInput,\n TableWhere,\n TableWhereUnique,\n TableUpdateData,\n TableCreateData,\n TableUpdateInput,\n TableOrderBy,\n TableSelect,\n TableInclude,\n TableResult,\n Tables,\n TableFindManyArgs,\n TableAggregateArgs,\n TableGroupByArgs,\n TableAggregateResult,\n ScalarFilter,\n StringFilter,\n ListFilter,\n JsonFilter,\n InferTableRecord,\n} from './table-types.js';\nimport { scanDir } from './router/scan.js';\nimport { mountRoutes } from './router/mount.js';\nimport { runMaster, shutdownMaster } from './cluster/index.js';\nimport { configureAuth } from './auth/index.js';\nimport { isHttpError } from './errors.js';\nimport { connectMongo } from './db/mongo.js';\nimport { setDbClient } from './db/index.js';\nimport { setDbEngine, setAutoSync } from './db/engine.js';\nimport { checkConnectionBudget, connectPostgres } from './db/postgres.js';\nimport { runWithContext } from './context.js';\nimport { configureLogger, getLogger, requestLogger } from './logger.js';\nimport { configureQueryLog } from './db/query-log.js';\nimport { scanTasks } from './tasks/scanner.js';\nimport { initBullMQ, closeBullMQ } from './tasks/bullmq-backend.js';\nimport { initPgBoss, closePgBoss } from './tasks/pgboss-backend.js';\nimport { configureCache, closeCache } from './cache/index.js';\nimport { servePrimaryCache } from './cache/ipc.js';\nimport { generateDashboard } from './dashboard.js';\n\nfunction detectDatabase(url?: string): 'mongodb' | 'postgresql' | undefined {\n if (!url) return undefined;\n if (url.startsWith('mongodb')) return 'mongodb';\n if (url.startsWith('postgres')) return 'postgresql';\n return undefined;\n}\n\nexport async function ignite(config: EFCConfig): Promise<http.Server | undefined> {\n const {\n port: _port,\n workers,\n globalMiddlewares = [],\n onWorkerReady,\n onWorkerCrash,\n onError,\n } = config;\n\n // Resolve api/tasks dirs from convention. argv[1]-based resolution is unreliable in tsx watch\n // + cluster workers (argv[1] can point to the tsx binary instead of the user's script), so we\n // probe multiple candidates and use the first that exists on disk.\n function resolveConventionDir(name: string): string {\n const candidates: string[] = [\n ...(process.argv[1] ? [path.join(path.dirname(process.argv[1]), name)] : []),\n path.join(process.cwd(), 'src', name),\n path.join(process.cwd(), name),\n path.join(process.cwd(), 'dist', name),\n ];\n return candidates.find((c) => fs.existsSync(c)) ?? candidates[0]!;\n }\n const apiDir = resolveConventionDir('api');\n const tasksDir = resolveConventionDir('tasks');\n const basePath = config.basePath ?? '/v1/api';\n\n function readProjectMeta(): { name: string; version: string } {\n try {\n const raw = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');\n const pkg = JSON.parse(raw) as { name?: string; version?: string };\n return { name: pkg.name ?? 'API', version: pkg.version ?? '' };\n } catch {\n return { name: 'API', version: '' };\n }\n }\n\n const port = _port != null && !Number.isNaN(_port) ? _port : 3000;\n const databaseUrl = config.databaseUrl;\n const database = config.database ?? detectDatabase(databaseUrl);\n const jwtSecret = config.jwtSecret;\n const authStrategy = config.authStrategy ?? 'http-only';\n // NODE_ENV is a Node/Express-wide runtime-mode signal set by the platform, not an app\n // secret — unlike PORT/DATABASE_URL/JWT_SECRET/etc. this one is still read directly.\n const clusterEnabled = config.cluster ?? process.env['NODE_ENV'] === 'production';\n\n configureLogger(config.logging);\n // Any value but 'http-only' acts as bearer, as it always has — an app may rely on that, so\n // 0.9.x only warns (a typo of 'http-only' silently means no cookie). 1.0 makes it an error.\n if (\n !['http-only', 'bearer', 'localStorage'].includes(authStrategy) &&\n (!clusterEnabled || cluster.isPrimary) // once, not once per worker\n ) {\n getLogger().warn(\n `[EFC] Unknown authStrategy \"${String(authStrategy)}\" — treated as 'bearer'. Use 'http-only' or 'bearer'; this will be an error in 1.0.`,\n );\n }\n // HS256 with a short secret can be brute-forced offline from any token a user holds.\n if (\n jwtSecret &&\n Buffer.byteLength(jwtSecret) < 32 &&\n process.env['NODE_ENV'] === 'production' &&\n (!clusterEnabled || cluster.isPrimary)\n ) {\n getLogger().warn(\n `[EFC] jwtSecret is ${Buffer.byteLength(jwtSecret)} bytes — use at least 32 random bytes in production (openssl rand -hex 64).`,\n );\n }\n configureQueryLog(config.logging);\n\n if (clusterEnabled && cluster.isPrimary) {\n // The memory cache lives in the primary so all workers share it (cache/ipc.ts).\n if (config.cache && config.cache.backend === 'memory') {\n servePrimaryCache(config.cache.maxEntries ?? 10_000);\n }\n runMaster({\n workers: workers ?? os.cpus().length,\n ...(onWorkerReady !== undefined && { onWorkerReady }),\n ...(onWorkerCrash !== undefined && { onWorkerCrash }),\n });\n return;\n }\n\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 // Pre-Flight step 1: Connect database. The engine decides what defineModel compiles to.\n if (database) setDbEngine(database);\n setAutoSync(config.autoSync ?? true);\n // Pools are per worker; one process per machine reports the machine's total.\n const poolWorkers = clusterEnabled ? (workers ?? os.cpus().length) : 1;\n const reportsPools = !clusterEnabled || cluster.worker?.id === 1;\n if (database === 'mongodb' && databaseUrl) {\n const conn = await connectMongo(databaseUrl, config.databasePool);\n setDbClient(conn as unknown as Record<string, unknown>);\n if (reportsPools) {\n const max = config.databasePool?.max ?? 100; // mongoose's maxPoolSize default\n getLogger().info(\n `MongoDB connections: up to ${poolWorkers * max} from this machine (${poolWorkers} worker(s) × maxPoolSize ${max})`,\n );\n }\n } else if (database === 'postgresql' && databaseUrl) {\n const pool = await connectPostgres(databaseUrl, config.databasePool);\n setDbClient(pool as unknown as Record<string, unknown>);\n if (reportsPools) {\n const max = config.databasePool?.max ?? 10; // node-postgres' default\n // pg-boss on the same database opens its own pool (node-postgres default 10).\n const boss =\n config.tasks && config.tasks.backend === 'pg-boss' && !config.tasks.connectionString\n ? 10\n : 0;\n const breakdown = `${poolWorkers} worker(s) × (pool ${max}${boss ? ` + pg-boss ${boss}` : ''})`;\n await checkConnectionBudget(poolWorkers * (max + boss), breakdown);\n }\n }\n\n // Pre-Flight step 1b: Cache (also the session-revocation store requireAuth consults)\n if (config.cache) {\n await configureCache(config.cache);\n }\n\n // Pre-Flight step 2: Configure auth\n if (jwtSecret) {\n configureAuth({\n secret: jwtSecret,\n strategy: authStrategy,\n expiresIn: config.jwtExpiresIn ?? '7d',\n ...(config.cookieDomain !== undefined && { cookieDomain: config.cookieDomain }),\n });\n }\n\n // Pre-Flight step 3: Scan and register tasks\n if (tasksDir) {\n await scanTasks(tasksDir);\n }\n\n // Pre-Flight step 4: Start task queue backend\n if (config.tasks) {\n if (config.tasks.backend === 'bullmq') {\n await initBullMQ({\n redisUrl: config.tasks.redisUrl ?? 'redis://localhost:6379',\n concurrency: config.tasks.concurrency ?? 5,\n enqueueTimeout: config.tasks.enqueueTimeout ?? 5000,\n queue: config.tasks.queue ?? 'efc',\n });\n } else if (config.tasks.backend === 'pg-boss') {\n const connectionString = config.tasks.connectionString ?? databaseUrl;\n if (!connectionString) {\n throw new Error(\n '[EFC] tasks.backend \"pg-boss\" needs tasks.connectionString or databaseUrl',\n );\n }\n await initPgBoss({\n connectionString,\n concurrency: config.tasks.concurrency ?? 5,\n enqueueTimeout: config.tasks.enqueueTimeout ?? 5000,\n queue: config.tasks.queue ?? 'efc',\n ...(config.tasks.schema !== undefined && { schema: config.tasks.schema }),\n });\n }\n }\n\n // Pre-Flight step 5: Scan routes and mount\n const routes = scanDir(apiDir);\n const apiRouter = express.Router();\n const mounted: MountedRoute[] = await mountRoutes(apiRouter, routes);\n app.use(basePath, apiRouter);\n\n if (config.dashboard !== false && process.env['NODE_ENV'] === 'development') {\n app.get('/', (_req, res) => {\n const { name, version } = readProjectMeta();\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.send(generateDashboard(mounted, basePath, port, name, version));\n });\n }\n\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 return new Promise<http.Server>((resolve, reject) => {\n const server = app.listen(port);\n\n server.once('listening', () => {\n const wid = (cluster.worker as { id: number } | undefined)?.id ?? 'primary';\n const addr = server.address() as { port: number } | null;\n getLogger().info(`Worker ${wid} listening on :${addr?.port ?? port}`);\n resolve(server);\n });\n\n server.once('error', reject);\n });\n}\n\nexport function gracefulShutdown(server: http.Server | undefined, timeoutMs = 10_000): void {\n let shuttingDown = false;\n const shutdown = (signal: string) => {\n // A worker can get the signal twice (process-group Ctrl+C plus the primary's\n // forward); the default handler for a repeat would kill it mid-drain.\n if (shuttingDown) return;\n shuttingDown = true;\n getLogger().info(`${signal} received — closing server gracefully…`);\n if (server) {\n server.closeIdleConnections();\n server.close(() => {\n getLogger().info('Server closed');\n // Let in-flight task jobs finish before exiting; the timeout below still caps it.\n Promise.all([closeBullMQ(), closePgBoss(), closeCache()])\n .catch((err: unknown) => getLogger().error({ err }, 'Task backend close failed'))\n .finally(() => process.exit(0));\n });\n setTimeout(() => {\n getLogger().error('Forced exit after timeout');\n process.exit(1);\n }, timeoutMs).unref();\n } else {\n shutdownMaster();\n // Workers get the same budget plus a margin before the primary gives up on them.\n setTimeout(() => {\n getLogger().error('Workers did not exit in time — forcing primary exit');\n process.exit(1);\n }, timeoutMs + 2_000).unref();\n }\n };\n process.on('SIGTERM', () => shutdown('SIGTERM'));\n process.on('SIGINT', () => shutdown('SIGINT'));\n}\n\nexport { HttpError, isHttpError } from './errors.js';\nexport { logger, getLogger } from './logger.js';\nexport { cache } from './cache/index.js';\nexport { rateLimit } from './rate-limit.js';\nexport type { RateLimitOptions } from './rate-limit.js';\nexport { cacheResponse } from './cache/response.js';\nexport { compose } from './compose.js';\nexport {\n db,\n setDbClient,\n getDbClient,\n defineModel,\n defineTable,\n defineCollection,\n} from './db/index.js';\nexport type {\n CollectionModel,\n CollectionOptions,\n CollectionFilter,\n CollectionUpdate,\n CollectionFindOptions,\n CollectionWriteResult,\n CollectionBulkResult,\n CollectionBulkOp,\n CollectionChange,\n CollectionChangeStream,\n} from './db/collection-model.js';\nexport type {\n Pipeline,\n FieldRef,\n Accumulator,\n GroupResult,\n LookedUp,\n LookupTarget,\n} from './db/pipeline.js';\nexport { transaction } from './db/transaction.js';\nexport { ModelValidationError } from './db/schema.js';\nexport { scanDir } from './router/scan.js';\nexport { listTasks } from './tasks/index.js';\nexport { workerCount } from './cluster/index.js';\nexport type {\n EFCConfig,\n DatabasePoolConfig,\n CollectionSchema,\n CollectionFieldDefinition,\n GeoPoint,\n CorsConfig,\n RouteEntry,\n RouteMeta,\n RouteMethodMeta,\n RouteSchema,\n LoggingConfig,\n QueryLogConfig,\n CacheConfig,\n RequestSchema,\n Validator,\n ValidationIssue,\n TaskOptions,\n TaskDefinition,\n DatabaseEngine,\n AuthStrategy,\n ModelSchema,\n TableSchema,\n TableSchemaField,\n TableFieldDefinition,\n TableOptions,\n TableRelation,\n MigrationContext,\n SchemaField,\n Filter,\n FilterOperators,\n Update,\n FindOptions,\n IndexDefinition,\n ModelRecord,\n InferRecord,\n InferCreate,\n InferSchema,\n InferCreateInput,\n ScalarKeys,\n SortDirection,\n ModelCRUD,\n ModelQueryOptions,\n ModelOptions,\n FieldDefinition,\n DefaultOperator,\n} from './types.js';\n","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 const positional = req.params as Record<string, string | undefined>;\n const named: Record<string, unknown> = {};\n route.params.forEach((name, i) => {\n const value = positional[String(i)];\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 cluster from 'node:cluster';\nimport { getLogger } from '../logger.js';\n\ninterface ClusterOptions {\n workers?: number;\n onWorkerReady?: ((id: number) => void) | undefined;\n onWorkerCrash?: ((id: number, code: number) => void) | undefined;\n}\n\nlet isShuttingDown = false;\n\n/**\n * Returns the number of currently alive (not yet exited) cluster workers.\n * Returns `0` when running in single-process mode.\n */\nexport function workerCount(): number {\n return Object.keys(cluster.workers ?? {}).length;\n}\n\nexport function shutdownMaster(): void {\n isShuttingDown = true;\n getLogger().info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers…`);\n if (workerCount() === 0) process.exit(0);\n // Orchestrators (docker stop, k8s) signal only PID 1 — the primary — so forward the\n // signal; each worker's gracefulShutdown drains its server and exits on its own.\n for (const worker of Object.values(cluster.workers ?? {})) {\n worker?.process.kill('SIGTERM');\n }\n}\n\nexport function runMaster(options: ClusterOptions = {}): void {\n const count = options.workers ?? 1;\n\n getLogger().info(`Primary ${process.pid} starting ${count} workers`);\n\n for (let i = 0; i < count; i++) {\n cluster.fork();\n }\n\n cluster.on('online', (worker) => {\n options.onWorkerReady?.(worker.id);\n });\n\n cluster.on('exit', (worker, code, signal) => {\n const exitCode = code ?? (signal ? -1 : 0);\n if (isShuttingDown) {\n getLogger().info(`Worker ${worker.id} gracefully exited`);\n if (workerCount() === 0) {\n getLogger().info('All workers exited. Primary exiting.');\n process.exit(0);\n }\n return;\n }\n\n getLogger().warn(`Worker ${worker.id} exited (code=${exitCode}), respawning…`);\n options.onWorkerCrash?.(worker.id, exitCode);\n cluster.fork();\n });\n}\n\nexport { cluster };\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { registerTask } from './index.js';\nimport { getLogger } from '../logger.js';\nimport type { TaskDefinition } from '../types.js';\n\nexport async function scanTasks(tasksDir: string): Promise<void> {\n if (!fs.existsSync(tasksDir)) return;\n\n const files = fs.readdirSync(tasksDir).filter((f) => /\\.(ts|js|mts|mjs)$/.test(f));\n\n for (const file of files) {\n const filePath = path.join(tasksDir, file);\n const taskName = path.basename(file, path.extname(file));\n\n try {\n const mod = (await import(filePath)) as Record<string, unknown>;\n const def = mod['default'] as TaskDefinition | undefined;\n\n if (!def || typeof def.handler !== 'function') {\n getLogger().warn(`Task file ${file} has no valid default export — skipping`);\n continue;\n }\n\n registerTask(taskName, { ...def, filePath });\n getLogger().debug(`Registered task: ${taskName}`);\n } catch (err) {\n getLogger().warn({ err }, `Failed to load task ${file}`);\n }\n }\n}\n","import type { MountedRoute } from './types.js';\n\nconst HTTP_STATUS: Record<number, string> = {\n 200: 'OK',\n 201: 'Created',\n 202: 'Accepted',\n 204: 'No Content',\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 409: 'Conflict',\n 422: 'Unprocessable Entity',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n};\n\nexport function generateDashboard(\n routes: MountedRoute[],\n basePath: string,\n port: number,\n projectName: string,\n projectVersion: string,\n): string {\n const safeRoutes = JSON.stringify(\n routes.map((r) => ({\n urlPath: r.urlPath,\n methods: r.methods,\n params: r.params,\n meta: r.meta ?? null,\n })),\n ).replace(/<\\/script>/gi, '<\\\\/script>');\n const safeHttpStatus = JSON.stringify(HTTP_STATUS);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${projectName} — API Reference</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap\" rel=\"stylesheet\" />\n <style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n :root {\n --bg: #080b0f;\n --bg-card: #0d1117;\n --bg-raised: #111820;\n --border: #1e2832;\n --border-lit: #263040;\n --text: #e2e8f0;\n --text-dim: #64748b;\n --text-muted: #334155;\n --accent: #F0A030;\n --accent-dim: rgba(240,160,48,.12);\n --accent-glow: rgba(240,160,48,.22);\n --purple: #a78bfa;\n --blue: #60a5fa;\n --orange: #fb923c;\n --green: #7AAE8E;\n --radius: 10px;\n --radius-lg: 16px;\n --font-mono: 'JetBrains Mono', monospace;\n --font-sans: 'Inter', sans-serif;\n }\n html { scroll-behavior: smooth; }\n body {\n background: var(--bg); color: var(--text);\n font-family: var(--font-sans); font-size: 16px;\n line-height: 1.6; -webkit-font-smoothing: antialiased;\n position: relative;\n }\n body::before {\n content: ''; position: fixed; inset: 0; z-index: 0;\n background-image:\n linear-gradient(var(--border) 1px, transparent 1px),\n linear-gradient(90deg, var(--border) 1px, transparent 1px);\n background-size: 60px 60px; opacity: .28; pointer-events: none;\n }\n section, footer, .page-hero, .docs-layout { position: relative; z-index: 1; }\n a { text-decoration: none; color: inherit; }\n em { font-style: italic; }\n code {\n font-family: var(--font-mono); font-size: .85em;\n background: var(--bg-raised); border: 1px solid var(--border);\n border-radius: 4px; padding: 1px 6px; color: var(--accent);\n }\n .container { max-width: 1140px; margin: 0 auto; padding: 0 24px; }\n ::-webkit-scrollbar { width: 6px; }\n ::-webkit-scrollbar-track { background: var(--bg); }\n ::-webkit-scrollbar-thumb { background: var(--border-lit); border-radius: 3px; }\n\n /* ── PAGE HERO ── */\n .page-hero {\n padding: 48px 0 56px; border-bottom: 1px solid var(--border);\n }\n .page-hero .hero-glow {\n position: absolute; top: -40px; left: 10%; width: 500px; height: 350px;\n background: radial-gradient(ellipse, rgba(240,160,48,.1) 0%, transparent 68%);\n pointer-events: none;\n }\n .page-title {\n font-size: clamp(2rem, 5vw, 3.4rem); font-weight: 800;\n line-height: 1.1; letter-spacing: -.02em; margin-bottom: 24px;\n display: flex; align-items: baseline; gap: 16px; flex-wrap: wrap;\n }\n .project-version {\n font-family: var(--font-mono); font-size: clamp(.85rem, 2vw, 1.1rem);\n font-weight: 500; color: var(--accent);\n background: var(--accent-dim); border: 1px solid rgba(240,160,48,.3);\n border-radius: 6px; padding: 2px 10px; letter-spacing: .5px;\n }\n .hero-meta { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 40px; }\n .base-url-pill {\n display: flex; align-items: center; gap: 8px;\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: 7px; padding: 8px 14px;\n }\n .base-url-label { font-size: .72rem; font-family: var(--font-mono);\n color: var(--text-muted); text-transform: uppercase; letter-spacing: .5px; }\n .base-url-val { font-family: var(--font-mono); font-size: .8rem; color: var(--accent); }\n .count-pill {\n font-family: var(--font-mono); font-size: .72rem; color: var(--text-dim);\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: 7px; padding: 8px 14px;\n }\n\n /* ── TOOLBAR ── */\n .toolbar {\n display: flex; align-items: center; gap: 12px; flex-wrap: wrap;\n }\n .method-filters { display: flex; gap: 4px; flex-wrap: wrap; }\n .filter-btn {\n background: var(--bg-card); border: 1px solid var(--border);\n color: var(--text-dim); font-family: var(--font-mono);\n font-size: .72rem; font-weight: 600; letter-spacing: .5px;\n padding: 6px 12px; border-radius: 6px; cursor: pointer;\n transition: all .15s;\n }\n .filter-btn:hover { border-color: var(--border-lit); color: var(--text); }\n .filter-btn.active { background: var(--accent); color: #0d0d1a; border-color: var(--accent); }\n .filter-btn[data-method=\"GET\"].active { background: rgba(96,165,250,.18); color: #60a5fa; border-color: rgba(96,165,250,.4); }\n .filter-btn[data-method=\"POST\"].active { background: rgba(122,174,142,.18); color: #7AAE8E; border-color: rgba(122,174,142,.4); }\n .filter-btn[data-method=\"PUT\"].active { background: rgba(240,160,48,.18); color: #F0A030; border-color: rgba(240,160,48,.4); }\n .filter-btn[data-method=\"PATCH\"].active { background: rgba(251,191,36,.18); color: #fbbf24; border-color: rgba(251,191,36,.4); }\n .filter-btn[data-method=\"DELETE\"].active { background: rgba(248,113,113,.18); color: #f87171; border-color: rgba(248,113,113,.4); }\n .filter-btn[data-method=\"HEAD\"].active { background: rgba(167,139,250,.18); color: #a78bfa; border-color: rgba(167,139,250,.4); }\n .search-wrap { margin-left: auto; }\n .search-input {\n background: var(--bg-card); border: 1px solid var(--border);\n color: var(--text); font-family: var(--font-sans); font-size: .85rem;\n padding: 7px 14px; border-radius: 7px; width: 240px;\n outline: none; transition: border-color .2s;\n }\n .search-input::placeholder { color: var(--text-muted); }\n .search-input:focus { border-color: var(--border-lit); }\n\n /* ── DOCS LAYOUT ── */\n .docs-layout {\n display: grid; grid-template-columns: 260px 1fr;\n gap: 48px; padding: 52px 0 80px; max-width: 1140px;\n margin: 0 auto; padding-left: 24px; padding-right: 24px;\n align-items: start;\n }\n\n /* ── SIDEBAR ── */\n .docs-sidebar {\n position: sticky; top: 24px;\n max-height: calc(100vh - 48px);\n overflow-y: auto;\n overflow-x: hidden;\n scrollbar-width: none;\n padding-right: 4px;\n }\n .docs-sidebar::-webkit-scrollbar { display: none; }\n .sidebar-section { margin-bottom: 28px; }\n .sidebar-label {\n font-family: var(--font-mono); font-size: .68rem; font-weight: 600;\n color: var(--text-muted); letter-spacing: 1.2px; text-transform: uppercase;\n margin-bottom: 8px; padding: 0 4px;\n }\n .sidebar-link {\n display: flex; align-items: center; gap: 8px;\n padding: 7px 10px; border-radius: 6px;\n border-left: 2px solid transparent;\n font-size: .82rem; color: var(--text-dim); cursor: pointer;\n transition: background .15s, color .15s, border-color .15s;\n overflow: hidden; white-space: nowrap;\n }\n .sidebar-link:hover { background: var(--bg-raised); color: var(--text); }\n .sidebar-link.active { color: var(--accent); border-left-color: var(--accent); background: var(--accent-dim); }\n .sidebar-method-dot {\n width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0;\n }\n .sidebar-path { font-family: var(--font-mono); font-size: .72rem; }\n\n /* ── ENDPOINT CARDS ── */\n .endpoint-card {\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: var(--radius-lg); margin-bottom: 20px;\n overflow: hidden; transition: border-color .2s;\n animation: fadeUp .45s ease both;\n }\n .endpoint-card:hover { border-color: var(--border-lit); }\n @keyframes fadeUp {\n from { opacity: 0; transform: translateY(16px); }\n to { opacity: 1; transform: translateY(0); }\n }\n @media (prefers-reduced-motion: reduce) {\n .endpoint-card { animation: none; }\n }\n .endpoint-header {\n display: flex; align-items: center; gap: 14px;\n padding: 20px 24px 18px; border-bottom: 1px solid var(--border);\n flex-wrap: wrap;\n }\n .method-badges { display: flex; gap: 6px; flex-wrap: wrap; }\n .method-badge {\n font-family: var(--font-mono); font-size: .7rem; font-weight: 600;\n letter-spacing: .8px; padding: 4px 10px; border-radius: 5px;\n border: 1px solid; text-transform: uppercase;\n }\n .endpoint-path {\n font-family: var(--font-mono); font-size: .9rem; color: var(--text);\n background: none; border: none; padding: 0;\n word-break: break-all;\n }\n .endpoint-body { padding: 6px 24px 24px; }\n .endpoint-desc { font-size: .9rem; color: var(--text-dim); line-height: 1.7; margin-bottom: 20px; }\n\n /* ── PER-METHOD DOC BLOCKS ── */\n .method-block { padding-top: 20px; }\n .method-block + .method-block { margin-top: 4px; border-top: 1px solid var(--border); }\n .method-block-header { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }\n .method-block-header .method-badge { font-size: .68rem; }\n .method-block-empty { font-size: .82rem; color: var(--text-muted); }\n\n /* ── CODE BLOCKS ── */\n .example-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }\n .code-block-wrap {\n background: var(--bg-raised); border: 1px solid var(--border);\n border-radius: var(--radius); overflow: hidden;\n }\n .code-bar {\n display: flex; align-items: center; gap: 6px;\n padding: 9px 14px; border-bottom: 1px solid var(--border);\n background: var(--bg-card);\n }\n .dot { width: 11px; height: 11px; border-radius: 50%; }\n .dot-r { background: #ff5f57; }\n .dot-y { background: #febc2e; }\n .dot-g { background: #28c840; }\n .code-label { font-family: var(--font-mono); font-size: .68rem; color: var(--text-dim); margin-left: 4px; }\n pre.code-pre {\n font-family: var(--font-mono); font-size: .78rem; line-height: 1.7;\n padding: 16px 18px; overflow-x: auto; tab-size: 2; white-space: pre;\n }\n .c-dim { color: var(--text-muted); }\n .c-green { color: #7AAE8E; }\n .c-blue { color: #60a5fa; }\n .c-orange { color: #fb923c; }\n .c-purple { color: #a78bfa; }\n .c-accent { color: var(--accent); }\n .status-2xx { color: #7AAE8E; }\n .status-4xx { color: #f87171; }\n .status-5xx { color: #fb923c; }\n\n /* ── EMPTY STATE ── */\n .empty-state {\n text-align: center; padding: 80px 24px;\n color: var(--text-muted); font-size: .9rem;\n }\n\n /* ── RESPONSIVE ── */\n @media (max-width: 900px) {\n .docs-layout { grid-template-columns: 1fr; }\n .docs-sidebar { position: static; max-height: none; overflow-y: visible; padding-right: 0; }\n .example-grid { grid-template-columns: 1fr; }\n .search-wrap { margin-left: 0; width: 100%; }\n .search-input { width: 100%; }\n }\n @media (max-width: 600px) {\n .page-hero { padding: 32px 0 32px; }\n .page-title { font-size: 2rem; }\n }\n </style>\n</head>\n<body>\n\n <div class=\"page-hero\">\n <div class=\"hero-glow\"></div>\n <div class=\"container\">\n <h1 class=\"page-title\">${projectName}${projectVersion ? `<span class=\"project-version\">v${projectVersion}</span>` : ''}</h1>\n <div class=\"hero-meta\">\n <div class=\"base-url-pill\">\n <span class=\"base-url-label\">Base</span>\n <span class=\"base-url-val\">http://localhost:${port}${basePath}</span>\n </div>\n <div class=\"count-pill\" id=\"countPill\"></div>\n </div>\n <div class=\"toolbar\">\n <div class=\"method-filters\" id=\"methodFilters\">\n <button class=\"filter-btn active\" data-method=\"ALL\">ALL</button>\n </div>\n <div class=\"search-wrap\">\n <input type=\"text\" id=\"searchInput\" class=\"search-input\" placeholder=\"Search endpoints…\" />\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"docs-layout\">\n <aside class=\"docs-sidebar\" id=\"sidebar\"></aside>\n <main id=\"endpoints\"></main>\n </div>\n\n <script>\n const ROUTES = ${safeRoutes};\n const BASE_PATH = ${JSON.stringify(basePath)};\n const HTTP_STATUS = ${safeHttpStatus};\n\n const METHOD_STYLE = {\n GET: { bg: 'rgba(96,165,250,.14)', color: '#60a5fa', border: 'rgba(96,165,250,.35)' },\n POST: { bg: 'rgba(122,174,142,.14)', color: '#7AAE8E', border: 'rgba(122,174,142,.35)' },\n PUT: { bg: 'rgba(240,160,48,.14)', color: '#F0A030', border: 'rgba(240,160,48,.35)' },\n PATCH: { bg: 'rgba(251,191,36,.14)', color: '#fbbf24', border: 'rgba(251,191,36,.35)' },\n DELETE: { bg: 'rgba(248,113,113,.14)', color: '#f87171', border: 'rgba(248,113,113,.35)' },\n HEAD: { bg: 'rgba(167,139,250,.14)', color: '#a78bfa', border: 'rgba(167,139,250,.35)' },\n OPTIONS: { bg: 'rgba(148,163,184,.14)', color: '#94a3b8', border: 'rgba(148,163,184,.35)' },\n };\n\n function esc(s) {\n return String(s)\n .replace(/&/g,'&').replace(/</g,'<')\n .replace(/>/g,'>').replace(/\"/g,'"');\n }\n\n function methodBadge(m) {\n const s = METHOD_STYLE[m] || METHOD_STYLE.GET;\n return '<span class=\"method-badge\" style=\"background:' + s.bg + ';color:' + s.color + ';border-color:' + s.border + '\">' + m + '</span>';\n }\n\n function joinPath(base, p) {\n return (base.replace(/\\\\/+$/, '') + p) || '/';\n }\n\n function sidebarDot(method) {\n const s = METHOD_STYLE[method] || METHOD_STYLE.GET;\n return '<span class=\"sidebar-method-dot\" style=\"background:' + s.color + '\"></span>';\n }\n\n function statusClass(code) {\n if (code >= 200 && code < 300) return 'status-2xx';\n if (code >= 400 && code < 500) return 'status-4xx';\n if (code >= 500) return 'status-5xx';\n return '';\n }\n\n function renderSchema(val, indent) {\n const pad = ' '.repeat(indent || 0);\n if (val === null) return '<span class=\"c-dim\">null</span>';\n if (typeof val === 'string') {\n const isDate = /^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}/.test(val);\n return isDate ? '<span class=\"c-green\">Date</span>' : '<span class=\"c-purple\">String</span>';\n }\n if (typeof val === 'number') return '<span class=\"c-orange\">Number</span>';\n if (typeof val === 'boolean') return '<span class=\"c-purple\">Boolean</span>';\n if (Array.isArray(val)) {\n if (!val.length) return '[]';\n return '[\\\\n' + pad + ' ' + renderSchema(val[0], (indent || 0) + 1) + '\\\\n' + pad + ']';\n }\n if (typeof val === 'object') {\n const keys = Object.keys(val);\n if (!keys.length) return '{}';\n const inner = keys.map(function(k) {\n return pad + ' <span class=\"c-blue\">"' + esc(k) + '"</span>: ' + renderSchema(val[k], (indent || 0) + 1);\n }).join(',\\\\n');\n return '{\\\\n' + inner + '\\\\n' + pad + '}';\n }\n return esc(String(val));\n }\n\n function codeBlock(label, content) {\n return '<div class=\"code-block-wrap\">' +\n '<div class=\"code-bar\">' +\n '<span class=\"dot dot-r\"></span>' +\n '<span class=\"dot dot-y\"></span>' +\n '<span class=\"dot dot-g\"></span>' +\n '<span class=\"code-label\">' + esc(label) + '</span>' +\n '</div>' +\n '<pre class=\"code-pre\">' + content + '</pre>' +\n '</div>';\n }\n\n function buildRequestContent(route, method, example) {\n const req = example || {};\n let path = joinPath(BASE_PATH, route.urlPath);\n if (req.params) {\n for (const [k, v] of Object.entries(req.params)) {\n path = path.replace(':' + k, String(v));\n }\n }\n if (req.query && Object.keys(req.query).length) {\n path += '?' + new URLSearchParams(req.query).toString();\n }\n let lines = '<span class=\"c-accent\">' + esc(method) + '</span> <span class=\"c-blue\">' + esc(path) + '</span>';\n const headers = { ...(req.headers || {}) };\n if (req.body !== undefined && !headers['Content-Type']) {\n headers['Content-Type'] = 'application/json';\n }\n if (Object.keys(headers).length) {\n lines += '\\\\n' + Object.entries(headers)\n .map(([k, v]) => '<span class=\"c-dim\">' + esc(k) + ':</span> ' + esc(String(v)))\n .join('\\\\n');\n }\n if (req.body !== undefined) {\n lines += '\\\\n\\\\n' + renderSchema(req.body, 0);\n }\n return lines;\n }\n\n function buildResponseContent(example) {\n const resp = example || {};\n const code = resp.status || 200;\n const text = HTTP_STATUS[code] || 'OK';\n const cls = statusClass(code);\n let lines = 'HTTP/1.1 <span class=\"' + cls + '\">' + code + ' ' + esc(text) + '</span>';\n if (resp.body !== undefined) {\n lines += '\\\\n<span class=\"c-dim\">Content-Type:</span> application/json\\\\n\\\\n';\n lines += renderSchema(resp.body, 0);\n }\n return lines;\n }\n\n function renderMethodBlock(route, method) {\n const methodMeta = route.meta ? route.meta[method] : null;\n const header = '<div class=\"method-block-header\">' + methodBadge(method) + '</div>';\n\n if (!methodMeta) {\n return '<div class=\"method-block\" data-method=\"' + esc(method) + '\">' + header +\n '<p class=\"method-block-empty\">No documentation provided for this method.</p></div>';\n }\n\n const desc = methodMeta.description\n ? '<p class=\"endpoint-desc\">' + esc(methodMeta.description) + '</p>'\n : '';\n const reqHtml = methodMeta.request !== undefined\n ? codeBlock('request', buildRequestContent(route, method, methodMeta.request))\n : '';\n const respHtml = methodMeta.response !== undefined\n ? codeBlock('response', buildResponseContent(methodMeta.response))\n : '';\n const examples = reqHtml || respHtml\n ? '<div class=\"example-grid\">' + reqHtml + respHtml + '</div>'\n : '';\n\n return '<div class=\"method-block\" data-method=\"' + esc(method) + '\">' + header + desc + examples + '</div>';\n }\n\n function renderCard(route, index) {\n const id = 'ep-' + index;\n const fullPath = joinPath(BASE_PATH, route.urlPath);\n const badges = route.methods.map(methodBadge).join('');\n const body = route.methods.map(function(m) { return renderMethodBlock(route, m); }).join('');\n const delay = (index * 0.06).toFixed(2) + 's';\n return '<div class=\"endpoint-card\" id=\"' + id + '\" data-methods=\"' + route.methods.join(',') + '\" data-path=\"' + esc(fullPath) + '\" style=\"animation-delay:' + delay + '\">' +\n '<div class=\"endpoint-header\">' +\n '<div class=\"method-badges\">' + badges + '</div>' +\n '<code class=\"endpoint-path\">' + esc(fullPath) + '</code>' +\n '</div>' +\n '<div class=\"endpoint-body\">' + body + '</div>' +\n '</div>';\n }\n\n function buildMethodFilters() {\n const allMethods = [...new Set(ROUTES.flatMap(r => r.methods))].sort();\n const filtersEl = document.getElementById('methodFilters');\n allMethods.forEach(m => {\n const btn = document.createElement('button');\n btn.className = 'filter-btn';\n btn.dataset.method = m;\n btn.textContent = m;\n filtersEl.appendChild(btn);\n });\n }\n\n function buildSidebar(routes) {\n const sidebar = document.getElementById('sidebar');\n if (!routes.length) { sidebar.innerHTML = ''; return; }\n\n const label = document.createElement('div');\n label.className = 'sidebar-label';\n label.textContent = 'Endpoints';\n sidebar.appendChild(label);\n\n routes.forEach((route, i) => {\n const link = document.createElement('div');\n link.className = 'sidebar-link';\n link.dataset.target = 'ep-' + ROUTES.indexOf(route);\n link.innerHTML = sidebarDot(route.methods[0] || 'GET') +\n '<span class=\"sidebar-path\">' + esc(route.urlPath || '/') + '</span>';\n link.addEventListener('click', () => {\n const target = document.getElementById(link.dataset.target);\n if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });\n });\n sidebar.appendChild(link);\n });\n }\n\n let activeFilter = 'ALL';\n let searchQuery = '';\n\n function applyFilters() {\n const cards = document.querySelectorAll('.endpoint-card');\n let visible = 0;\n cards.forEach(card => {\n const methods = card.dataset.methods.split(',');\n const path = card.dataset.path || '';\n const matchMethod = activeFilter === 'ALL' || methods.includes(activeFilter);\n const matchSearch = !searchQuery || path.toLowerCase().includes(searchQuery);\n const show = matchMethod && matchSearch;\n card.style.display = show ? '' : 'none';\n if (show) visible++;\n });\n document.getElementById('empty-state').style.display = visible ? 'none' : 'block';\n\n // Sync sidebar visibility\n document.querySelectorAll('.sidebar-link').forEach(link => {\n const targetId = link.dataset.target;\n const targetCard = document.getElementById(targetId);\n link.style.display = targetCard && targetCard.style.display !== 'none' ? '' : 'none';\n });\n }\n\n function init() {\n const count = ROUTES.length;\n document.getElementById('countPill').textContent = count + ' endpoint' + (count !== 1 ? 's' : '');\n\n buildMethodFilters();\n\n const container = document.getElementById('endpoints');\n container.innerHTML = ROUTES.map((r, i) => renderCard(r, i)).join('');\n\n // Add empty state after cards\n const emptyEl = document.createElement('div');\n emptyEl.id = 'empty-state';\n emptyEl.className = 'empty-state';\n emptyEl.style.display = 'none';\n emptyEl.innerHTML = '<p>No endpoints match your filter.</p>';\n container.after(emptyEl);\n\n buildSidebar(ROUTES);\n\n // Method filter clicks\n document.getElementById('methodFilters').addEventListener('click', e => {\n const btn = e.target.closest('.filter-btn');\n if (!btn) return;\n document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));\n btn.classList.add('active');\n activeFilter = btn.dataset.method;\n applyFilters();\n });\n\n // Search\n document.getElementById('searchInput').addEventListener('input', e => {\n searchQuery = e.target.value.trim().toLowerCase();\n applyFilters();\n });\n\n // Scroll spy for sidebar\n const cardEls = document.querySelectorAll('.endpoint-card');\n const sidebarLinks = document.querySelectorAll('.sidebar-link');\n const observer = new IntersectionObserver(entries => {\n entries.forEach(entry => {\n if (entry.isIntersecting) {\n const id = entry.target.id;\n sidebarLinks.forEach(l => l.classList.toggle('active', l.dataset.target === id));\n const sidebar = document.getElementById('sidebar');\n const activeLink = sidebar && sidebar.querySelector('.sidebar-link.active');\n if (sidebar && activeLink) {\n const linkTop = activeLink.getBoundingClientRect().top - sidebar.getBoundingClientRect().top + sidebar.scrollTop;\n sidebar.scrollTo({ top: linkTop, behavior: 'smooth' });\n }\n }\n });\n }, { rootMargin: '-80px 0px -60% 0px' });\n cardEls.forEach(el => observer.observe(el));\n\n }\n\n try {\n init();\n } catch (e) {\n document.body.insertAdjacentHTML('afterbegin',\n '<div style=\"position:fixed;top:60px;left:0;right:0;z-index:9999;background:#7f1d1d;color:#fca5a5;padding:16px 24px;font-family:monospace;font-size:13px;border-bottom:1px solid #ef4444\">' +\n '<strong>Dashboard JS error:</strong> ' + (e && e.message ? e.message : String(e)) +\n (e && e.stack ? '<pre style=\"margin-top:8px;white-space:pre-wrap\">' + e.stack + '</pre>' : '') +\n '</div>'\n );\n }\n </script>\n</body>\n</html>`;\n}\n","import type { Request, RequestHandler } from 'express';\nimport { isCacheConfigured, rawIncr } from './cache/index.js';\nimport { getLogger } from './logger.js';\n\n// rateLimit(): a fixed-window limit (windows aligned to the clock) counted in the cache\n// (`cache.incr`), so every worker — and with Redis every instance — shares one count. An\n// in-memory counter per worker would let N workers accept N × max.\n\nexport interface RateLimitOptions {\n /** Window length: seconds, or `'30s'`, `'15m'`, `'1h'`, `'1d'`. */\n window: number | string;\n /** Requests allowed per window and key. */\n max: number;\n /**\n * Who a request counts against. Default: the client IP (`req.ip`) — behind a proxy or load\n * balancer set `trustProxy` in ignite(), or every client shares the proxy's IP. Return\n * `undefined` to not limit this request.\n */\n key?: (req: Request) => string | undefined;\n /**\n * Which counter: requests to routes with the same name share a limit. Default: the route\n * pattern (`/users/:id`), so each route file has its own — or the path, for middleware\n * that isn't on a route.\n */\n name?: string;\n /** Body of the 429 response. Default: `'Too many requests, try again later'`. */\n message?: string;\n /**\n * The cache can't be reached: `'allow'` (default) lets requests through — a limiter\n * shouldn't take the API down with it; `'reject'` answers 503.\n */\n onCacheError?: 'allow' | 'reject';\n /** Send `RateLimit-Limit/Remaining/Reset` (and `Retry-After` on 429). Default: true. */\n headers?: boolean;\n}\n\nconst UNITS: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86_400 };\n\nexport function parseWindow(window: number | string): number {\n if (typeof window === 'number') {\n if (window > 0) return window;\n } else {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*(s|m|h|d)$/.exec(window.trim());\n if (m) return Number(m[1]) * UNITS[m[2]!]!;\n }\n throw new Error(`[EFC] rateLimit: window must be seconds or like '15m' — got ${String(window)}`);\n}\n\nlet lastCacheError = 0;\n\n/**\n * Limits requests per key (default: client IP) to `max` per `window`, counted in the cache\n * so the limit holds across every worker and instance:\n *\n * ```ts\n * export const middlewares = [rateLimit({ window: '15m', max: 10 })];\n * ```\n *\n * Needs `cache` in ignite() — use the Redis backend when you run more than one instance.\n */\nexport function rateLimit(options: RateLimitOptions): RequestHandler {\n const windowSeconds = parseWindow(options.window);\n if (!Number.isInteger(options.max) || options.max < 1) {\n throw new Error('[EFC] rateLimit: max must be a positive integer');\n }\n const keyOf = options.key ?? ((req: Request) => req.ip ?? req.socket.remoteAddress);\n const message = options.message ?? 'Too many requests, try again later';\n const headers = options.headers ?? true;\n\n return (req, res, next) => {\n void (async () => {\n const who = keyOf(req);\n if (who === undefined) return next();\n if (!isCacheConfigured()) {\n throw new Error('[EFC] rateLimit needs a cache — pass cache: { backend } to ignite()');\n }\n const bucket = options.name ?? req.baseUrl + (req.route?.path ?? req.path);\n // Windows are aligned to the clock: every key restarts at the same boundary, and the\n // reset is exact. The key outlives its window by a second, then expires.\n const windowMs = windowSeconds * 1000;\n const now = Date.now();\n const slot = Math.floor(now / windowMs);\n const resetMs = (slot + 1) * windowMs - now;\n let count: number;\n try {\n count = (await rawIncr(`rl:${bucket}:${who}:${slot}`, Math.ceil(resetMs / 1000) + 1)).value;\n } catch (err) {\n if (Date.now() - lastCacheError > 30_000) {\n lastCacheError = Date.now();\n getLogger().error(\n { err },\n `rateLimit: cache unavailable — ${options.onCacheError === 'reject' ? 'rejecting with 503' : 'allowing requests'}`,\n );\n }\n if (options.onCacheError === 'reject') {\n res.status(503).json({ error: 'Service Unavailable', statusCode: 503 });\n return;\n }\n return next();\n }\n const resetSeconds = Math.max(1, Math.ceil(resetMs / 1000));\n if (headers) {\n res.setHeader('RateLimit-Limit', String(options.max));\n res.setHeader('RateLimit-Remaining', String(Math.max(0, options.max - count)));\n res.setHeader('RateLimit-Reset', String(resetSeconds));\n }\n if (count > options.max) {\n if (headers) res.setHeader('Retry-After', String(resetSeconds));\n res.status(429).json({ error: message, statusCode: 429 });\n return;\n }\n next();\n })().catch(next);\n };\n}\n","import type { Request, RequestHandler } from 'express';\nimport { cache } from './index.js';\nimport { getCurrentUser } from '../context.js';\n\nexport interface CacheResponseOptions {\n /** Seconds to keep a response. */\n ttl: number;\n /**\n * Cache per authenticated user (keyed by the JWT's `sub`/`id`). Put `requireAuth`\n * before this middleware. Without it, a response is shared by everyone hitting the URL.\n */\n perUser?: boolean;\n /** Custom cache key. Default: the request's original URL (path + query). */\n key?: (req: Request) => string;\n}\n\ninterface Stored {\n status: number;\n body: unknown;\n}\n\n/** Key prefix for cached responses — `cache.clear(RESPONSE_PREFIX + '/v1/api/posts')` drops those. */\nexport const RESPONSE_PREFIX = 'res:';\n\n/**\n * Caches successful (200) JSON responses of GET/HEAD requests. Adds `X-Cache: HIT|MISS`.\n *\n * @example\n * export const middlewares = [cacheResponse(60)];\n * export const middlewares = [requireAuth, cacheResponse({ ttl: 30, perUser: true })];\n */\nexport function cacheResponse(options: number | CacheResponseOptions): RequestHandler {\n const opts: CacheResponseOptions = typeof options === 'number' ? { ttl: options } : options;\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') return next();\n\n let scope = '';\n if (opts.perUser) {\n const user = getCurrentUser();\n const id = user?.['sub'] ?? user?.['id'];\n // Never fall back to a shared entry for a per-user route.\n if (id === undefined) return next();\n scope = `u:${String(id)}:`;\n }\n const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);\n\n void (async () => {\n const hit = await cache.get<Stored>(key);\n if (hit) {\n res.setHeader('X-Cache', 'HIT');\n res.status(hit.status).json(hit.body);\n return;\n }\n res.setHeader('X-Cache', 'MISS');\n const json = res.json.bind(res);\n res.json = (body: unknown) => {\n if (res.statusCode === 200) void cache.set(key, { status: 200, body }, { ttl: opts.ttl });\n return json(body);\n };\n next();\n })().catch(next);\n };\n}\n","import type { RequestHandler } from 'express';\n\n/**\n * Chains multiple Express request handlers into a single handler.\n * Each handler calls the next one via its `next` callback.\n *\n * @example\n * export const GET = compose(requireAuth, rateLimiter, myHandler);\n */\nexport function compose(...handlers: RequestHandler[]): RequestHandler {\n return (req, res, next) => {\n function dispatch(i: number): void {\n if (i >= handlers.length) {\n next();\n return;\n }\n const handler = handlers[i];\n if (!handler) {\n next();\n return;\n }\n try {\n Promise.resolve(handler(req, res, () => dispatch(i + 1))).catch(next);\n } catch (err) {\n next(err);\n }\n }\n\n dispatch(0);\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/index.cjs","../src/index.ts","../src/cluster/index.ts","../src/tasks/scanner.ts","../src/dashboard.ts","../src/rate-limit.ts","../src/cache/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A;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/index.cjs","sourcesContent":[null,"import http from 'node:http';\nimport fs from 'node:fs';\nimport express from 'express';\nimport cluster from 'node:cluster';\nimport os from 'node:os';\nimport path from 'node:path';\nimport type { EFCConfig, MountedRoute } from './types.js';\nexport type {\n TableModel,\n TableRecord,\n TableCreateInput,\n TableWhere,\n TableWhereUnique,\n TableUpdateData,\n TableCreateData,\n TableUpdateInput,\n TableOrderBy,\n TableSelect,\n TableInclude,\n TableResult,\n Tables,\n TableFindManyArgs,\n TableAggregateArgs,\n TableGroupByArgs,\n TableAggregateResult,\n ScalarFilter,\n StringFilter,\n ListFilter,\n JsonFilter,\n InferTableRecord,\n} from './table-types.js';\nimport { scanDir } from './router/scan.js';\nimport { mountRoutes } from './router/mount.js';\nimport { mountOpenAPI } from './openapi.js';\nimport { attachWebSockets, closeWebSockets } from './websocket.js';\nimport { runMaster, shutdownMaster } from './cluster/index.js';\nimport { configureAuth } from './auth/index.js';\nimport { connectMongo } from './db/mongo.js';\nimport { setDbClient } from './db/index.js';\nimport { setDbEngine, setAutoSync } from './db/engine.js';\nimport { checkConnectionBudget, connectPostgres } from './db/postgres.js';\nimport { configureLogger, getLogger } from './logger.js';\nimport { configureQueryLog } from './db/query-log.js';\nimport { scanTasks } from './tasks/scanner.js';\nimport { initBullMQ, closeBullMQ } from './tasks/bullmq-backend.js';\nimport { initPgBoss, closePgBoss } from './tasks/pgboss-backend.js';\nimport { configureCache, closeCache } from './cache/index.js';\nimport { servePrimaryCache } from './cache/ipc.js';\nimport { generateDashboard } from './dashboard.js';\nimport { createHttpApp, mountErrorHandler } from './http-app.js';\n\nfunction detectDatabase(url?: string): 'mongodb' | 'postgresql' | undefined {\n if (!url) return undefined;\n if (url.startsWith('mongodb')) return 'mongodb';\n if (url.startsWith('postgres')) return 'postgresql';\n return undefined;\n}\n\nexport async function ignite(config: EFCConfig): Promise<http.Server | undefined> {\n const { port: _port, workers, onWorkerReady, onWorkerCrash, onError } = config;\n\n // Resolve api/tasks dirs from convention. argv[1]-based resolution is unreliable in tsx watch\n // + cluster workers (argv[1] can point to the tsx binary instead of the user's script), so we\n // probe multiple candidates and use the first that exists on disk.\n function resolveConventionDir(name: string): string {\n const candidates: string[] = [\n ...(process.argv[1] ? [path.join(path.dirname(process.argv[1]), name)] : []),\n path.join(process.cwd(), 'src', name),\n path.join(process.cwd(), name),\n path.join(process.cwd(), 'dist', name),\n ];\n return candidates.find((c) => fs.existsSync(c)) ?? candidates[0]!;\n }\n const apiDir = resolveConventionDir('api');\n const tasksDir = resolveConventionDir('tasks');\n const basePath = config.basePath ?? '/v1/api';\n\n function readProjectMeta(): { name: string; version: string } {\n try {\n const raw = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');\n const pkg = JSON.parse(raw) as { name?: string; version?: string };\n return { name: pkg.name ?? 'API', version: pkg.version ?? '' };\n } catch {\n return { name: 'API', version: '' };\n }\n }\n\n const port = _port != null && !Number.isNaN(_port) ? _port : 3000;\n const databaseUrl = config.databaseUrl;\n const database = config.database ?? detectDatabase(databaseUrl);\n const jwtSecret = config.jwtSecret;\n const authStrategy = config.authStrategy ?? 'http-only';\n // NODE_ENV is a Node/Express-wide runtime-mode signal set by the platform, not an app\n // secret — unlike PORT/DATABASE_URL/JWT_SECRET/etc. this one is still read directly.\n const clusterEnabled = config.cluster ?? process.env['NODE_ENV'] === 'production';\n\n configureLogger(config.logging);\n // Any value but 'http-only' acts as bearer, as it always has — an app may rely on that, so\n // 0.9.x only warns (a typo of 'http-only' silently means no cookie). 1.0 makes it an error.\n if (\n !['http-only', 'bearer', 'localStorage'].includes(authStrategy) &&\n (!clusterEnabled || cluster.isPrimary) // once, not once per worker\n ) {\n getLogger().warn(\n `[EFC] Unknown authStrategy \"${String(authStrategy)}\" — treated as 'bearer'. Use 'http-only' or 'bearer'; this will be an error in 1.0.`,\n );\n }\n // HS256 with a short secret can be brute-forced offline from any token a user holds.\n if (\n jwtSecret &&\n Buffer.byteLength(jwtSecret) < 32 &&\n process.env['NODE_ENV'] === 'production' &&\n (!clusterEnabled || cluster.isPrimary)\n ) {\n getLogger().warn(\n `[EFC] jwtSecret is ${Buffer.byteLength(jwtSecret)} bytes — use at least 32 random bytes in production (openssl rand -hex 64).`,\n );\n }\n configureQueryLog(config.logging);\n\n if (clusterEnabled && cluster.isPrimary) {\n // The memory cache lives in the primary so all workers share it (cache/ipc.ts).\n if (config.cache && config.cache.backend === 'memory') {\n servePrimaryCache(config.cache.maxEntries ?? 10_000);\n }\n runMaster({\n workers: workers ?? os.cpus().length,\n ...(onWorkerReady !== undefined && { onWorkerReady }),\n ...(onWorkerCrash !== undefined && { onWorkerCrash }),\n });\n return;\n }\n\n const app = createHttpApp(config);\n\n // Pre-Flight step 1: Connect database. The engine decides what defineModel compiles to.\n if (database) setDbEngine(database);\n setAutoSync(config.autoSync ?? true);\n // Pools are per worker; one process per machine reports the machine's total.\n const poolWorkers = clusterEnabled ? (workers ?? os.cpus().length) : 1;\n const reportsPools = !clusterEnabled || cluster.worker?.id === 1;\n if (database === 'mongodb' && databaseUrl) {\n const conn = await connectMongo(databaseUrl, config.databasePool);\n setDbClient(conn as unknown as Record<string, unknown>);\n if (reportsPools) {\n const max = config.databasePool?.max ?? 100; // mongoose's maxPoolSize default\n getLogger().info(\n `MongoDB connections: up to ${poolWorkers * max} from this machine (${poolWorkers} worker(s) × maxPoolSize ${max})`,\n );\n }\n } else if (database === 'postgresql' && databaseUrl) {\n const pool = await connectPostgres(databaseUrl, config.databasePool);\n setDbClient(pool as unknown as Record<string, unknown>);\n if (reportsPools) {\n const max = config.databasePool?.max ?? 10; // node-postgres' default\n // pg-boss on the same database opens its own pool (node-postgres default 10).\n const boss =\n config.tasks && config.tasks.backend === 'pg-boss' && !config.tasks.connectionString\n ? 10\n : 0;\n const breakdown = `${poolWorkers} worker(s) × (pool ${max}${boss ? ` + pg-boss ${boss}` : ''})`;\n await checkConnectionBudget(poolWorkers * (max + boss), breakdown);\n }\n }\n\n // Pre-Flight step 1b: Cache (also the session-revocation store requireAuth consults)\n if (config.cache) {\n await configureCache(config.cache);\n }\n\n // Pre-Flight step 2: Configure auth\n if (jwtSecret) {\n configureAuth({\n secret: jwtSecret,\n strategy: authStrategy,\n expiresIn: config.jwtExpiresIn ?? '7d',\n ...(config.cookieDomain !== undefined && { cookieDomain: config.cookieDomain }),\n });\n }\n\n // Pre-Flight step 3: Scan and register tasks\n if (tasksDir) {\n await scanTasks(tasksDir);\n }\n\n // Pre-Flight step 4: Start task queue backend\n if (config.tasks) {\n if (config.tasks.backend === 'bullmq') {\n await initBullMQ({\n redisUrl: config.tasks.redisUrl ?? 'redis://localhost:6379',\n concurrency: config.tasks.concurrency ?? 5,\n enqueueTimeout: config.tasks.enqueueTimeout ?? 5000,\n queue: config.tasks.queue ?? 'efc',\n });\n } else if (config.tasks.backend === 'pg-boss') {\n const connectionString = config.tasks.connectionString ?? databaseUrl;\n if (!connectionString) {\n throw new Error(\n '[EFC] tasks.backend \"pg-boss\" needs tasks.connectionString or databaseUrl',\n );\n }\n await initPgBoss({\n connectionString,\n concurrency: config.tasks.concurrency ?? 5,\n enqueueTimeout: config.tasks.enqueueTimeout ?? 5000,\n queue: config.tasks.queue ?? 'efc',\n ...(config.tasks.schema !== undefined && { schema: config.tasks.schema }),\n });\n }\n }\n\n // Pre-Flight step 5: Scan routes and mount\n const routes = scanDir(apiDir);\n const apiRouter = express.Router();\n const mounted: MountedRoute[] = await mountRoutes(apiRouter, routes);\n if (config.openapi) {\n const meta = readProjectMeta();\n const options = config.openapi === true ? {} : config.openapi;\n await mountOpenAPI(app, mounted, {\n info: { title: meta.name, version: meta.version },\n ...options,\n basePath,\n });\n }\n app.use(basePath, apiRouter);\n\n if (config.dashboard !== false && process.env['NODE_ENV'] === 'development') {\n app.get('/', (_req, res) => {\n const { name, version } = readProjectMeta();\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.send(generateDashboard(mounted, basePath, port, name, version));\n });\n }\n\n mountErrorHandler(app, onError);\n\n return new Promise<http.Server>((resolve, reject) => {\n const server = http.createServer(app);\n if (config.websocket !== false && mounted.some((route) => route.websocket))\n attachWebSockets(server, app, config.websocket);\n\n server.once('listening', () => {\n const wid = (cluster.worker as { id: number } | undefined)?.id ?? 'primary';\n const addr = server.address() as { port: number } | null;\n getLogger().info(`Worker ${wid} listening on :${addr?.port ?? port}`);\n resolve(server);\n });\n\n server.once('error', reject);\n server.listen(port);\n });\n}\n\nexport function gracefulShutdown(server: http.Server | undefined, timeoutMs = 10_000): void {\n let shuttingDown = false;\n const shutdown = (signal: string) => {\n // A worker can get the signal twice (process-group Ctrl+C plus the primary's\n // forward); the default handler for a repeat would kill it mid-drain.\n if (shuttingDown) return;\n shuttingDown = true;\n getLogger().info(`${signal} received — closing server gracefully…`);\n if (server) {\n const websocketDrain = closeWebSockets(server, Math.max(1, Math.min(1000, timeoutMs / 2)));\n server.closeIdleConnections();\n server.close(() => {\n getLogger().info('Server closed');\n // Let in-flight task jobs finish before exiting; the timeout below still caps it.\n Promise.all([websocketDrain, closeBullMQ(), closePgBoss(), closeCache()])\n .catch((err: unknown) => getLogger().error({ err }, 'Task backend close failed'))\n .finally(() => process.exit(0));\n });\n setTimeout(() => {\n getLogger().error('Forced exit after timeout');\n process.exit(1);\n }, timeoutMs).unref();\n } else {\n shutdownMaster();\n // Workers get the same budget plus a margin before the primary gives up on them.\n setTimeout(() => {\n getLogger().error('Workers did not exit in time — forcing primary exit');\n process.exit(1);\n }, timeoutMs + 2_000).unref();\n }\n };\n process.on('SIGTERM', () => shutdown('SIGTERM'));\n process.on('SIGINT', () => shutdown('SIGINT'));\n}\n\nexport { HttpError, isHttpError } from './errors.js';\nexport { logger, getLogger } from './logger.js';\nexport { getQueryMetrics, resetQueryMetrics } from './db/query-log.js';\nexport type { QueryMetric, QueryMetricsSnapshot } from './db/query-log.js';\nexport { cache } from './cache/index.js';\nexport { rateLimit } from './rate-limit.js';\nexport type { RateLimitOptions } from './rate-limit.js';\nexport { cacheResponse } from './cache/response.js';\nexport { compose } from './compose.js';\nexport {\n db,\n setDbClient,\n getDbClient,\n defineModel,\n defineTable,\n defineCollection,\n} from './db/index.js';\nexport type {\n CollectionModel,\n CollectionOptions,\n CollectionFilter,\n CollectionUpdate,\n CollectionFindOptions,\n CollectionWriteResult,\n CollectionBulkResult,\n CollectionBulkOp,\n CollectionChange,\n CollectionChangeStream,\n} from './db/collection-model.js';\nexport type {\n Pipeline,\n FieldRef,\n Accumulator,\n GroupResult,\n LookedUp,\n LookupTarget,\n} from './db/pipeline.js';\nexport { transaction } from './db/transaction.js';\nexport { ModelValidationError } from './db/schema.js';\nexport { scanDir } from './router/scan.js';\nexport { listTasks } from './tasks/index.js';\nexport { workerCount } from './cluster/index.js';\nexport type {\n EFCConfig,\n DatabasePoolConfig,\n CollectionSchema,\n CollectionFieldDefinition,\n GeoPoint,\n CorsConfig,\n RouteEntry,\n RouteMeta,\n RouteMethodMeta,\n RouteSchema,\n LoggingConfig,\n QueryLogConfig,\n CacheConfig,\n RequestSchema,\n Validator,\n ValidationIssue,\n TaskOptions,\n TaskDefinition,\n DatabaseEngine,\n AuthStrategy,\n ModelSchema,\n TableSchema,\n TableSchemaField,\n TableFieldDefinition,\n TableOptions,\n TableRelation,\n MigrationContext,\n SchemaField,\n Filter,\n FilterOperators,\n Update,\n FindOptions,\n IndexDefinition,\n ModelRecord,\n InferRecord,\n InferCreate,\n InferSchema,\n InferCreateInput,\n ScalarKeys,\n SortDirection,\n ModelCRUD,\n ModelQueryOptions,\n ModelOptions,\n FieldDefinition,\n DefaultOperator,\n} from './types.js';\n\nexport { generateOpenAPI } from './openapi.js';\nexport type { OpenAPIOptions, OpenAPIDocument, JSONSchema } from './openapi.js';\nexport { attachWebSockets, closeWebSockets } from './websocket.js';\nexport type { WebSocketHandler, WebSocketOptions } from './websocket.js';\n","import cluster from 'node:cluster';\nimport { getLogger } from '../logger.js';\n\ninterface ClusterOptions {\n workers?: number;\n onWorkerReady?: ((id: number) => void) | undefined;\n onWorkerCrash?: ((id: number, code: number) => void) | undefined;\n}\n\nlet isShuttingDown = false;\n\n/**\n * Returns the number of currently alive (not yet exited) cluster workers.\n * Returns `0` when running in single-process mode.\n */\nexport function workerCount(): number {\n return Object.keys(cluster.workers ?? {}).length;\n}\n\nexport function shutdownMaster(): void {\n isShuttingDown = true;\n getLogger().info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers…`);\n if (workerCount() === 0) process.exit(0);\n // Orchestrators (docker stop, k8s) signal only PID 1 — the primary — so forward the\n // signal; each worker's gracefulShutdown drains its server and exits on its own.\n for (const worker of Object.values(cluster.workers ?? {})) {\n worker?.process.kill('SIGTERM');\n }\n}\n\nexport function runMaster(options: ClusterOptions = {}): void {\n const count = options.workers ?? 1;\n\n getLogger().info(`Primary ${process.pid} starting ${count} workers`);\n\n for (let i = 0; i < count; i++) {\n cluster.fork();\n }\n\n cluster.on('online', (worker) => {\n options.onWorkerReady?.(worker.id);\n });\n\n cluster.on('exit', (worker, code, signal) => {\n const exitCode = code ?? (signal ? -1 : 0);\n if (isShuttingDown) {\n getLogger().info(`Worker ${worker.id} gracefully exited`);\n if (workerCount() === 0) {\n getLogger().info('All workers exited. Primary exiting.');\n process.exit(0);\n }\n return;\n }\n\n getLogger().warn(`Worker ${worker.id} exited (code=${exitCode}), respawning…`);\n options.onWorkerCrash?.(worker.id, exitCode);\n cluster.fork();\n });\n}\n\nexport { cluster };\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { registerTask } from './index.js';\nimport { getLogger } from '../logger.js';\nimport type { TaskDefinition } from '../types.js';\n\nexport async function scanTasks(tasksDir: string): Promise<void> {\n if (!fs.existsSync(tasksDir)) return;\n\n const files = fs.readdirSync(tasksDir).filter((f) => /\\.(ts|js|mts|mjs)$/.test(f));\n\n for (const file of files) {\n const filePath = path.join(tasksDir, file);\n const taskName = path.basename(file, path.extname(file));\n\n try {\n const mod = (await import(filePath)) as Record<string, unknown>;\n const def = mod['default'] as TaskDefinition | undefined;\n\n if (!def || typeof def.handler !== 'function') {\n getLogger().warn(`Task file ${file} has no valid default export — skipping`);\n continue;\n }\n\n registerTask(taskName, { ...def, filePath });\n getLogger().debug(`Registered task: ${taskName}`);\n } catch (err) {\n getLogger().warn({ err }, `Failed to load task ${file}`);\n }\n }\n}\n","import type { MountedRoute } from './types.js';\n\nconst HTTP_STATUS: Record<number, string> = {\n 200: 'OK',\n 201: 'Created',\n 202: 'Accepted',\n 204: 'No Content',\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 409: 'Conflict',\n 422: 'Unprocessable Entity',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n};\n\nexport function generateDashboard(\n routes: MountedRoute[],\n basePath: string,\n port: number,\n projectName: string,\n projectVersion: string,\n): string {\n const safeRoutes = JSON.stringify(\n routes.map((r) => ({\n urlPath: r.urlPath,\n methods: r.websocket ? [...r.methods, 'WS'] : r.methods,\n params: r.params,\n meta: r.meta ?? null,\n })),\n ).replace(/<\\/script>/gi, '<\\\\/script>');\n const safeHttpStatus = JSON.stringify(HTTP_STATUS);\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${projectName} — API Reference</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\" />\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin />\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap\" rel=\"stylesheet\" />\n <style>\n *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }\n :root {\n --bg: #080b0f;\n --bg-card: #0d1117;\n --bg-raised: #111820;\n --border: #1e2832;\n --border-lit: #263040;\n --text: #e2e8f0;\n --text-dim: #64748b;\n --text-muted: #334155;\n --accent: #F0A030;\n --accent-dim: rgba(240,160,48,.12);\n --accent-glow: rgba(240,160,48,.22);\n --purple: #a78bfa;\n --blue: #60a5fa;\n --orange: #fb923c;\n --green: #7AAE8E;\n --radius: 10px;\n --radius-lg: 16px;\n --font-mono: 'JetBrains Mono', monospace;\n --font-sans: 'Inter', sans-serif;\n }\n html { scroll-behavior: smooth; }\n body {\n background: var(--bg); color: var(--text);\n font-family: var(--font-sans); font-size: 16px;\n line-height: 1.6; -webkit-font-smoothing: antialiased;\n position: relative;\n }\n body::before {\n content: ''; position: fixed; inset: 0; z-index: 0;\n background-image:\n linear-gradient(var(--border) 1px, transparent 1px),\n linear-gradient(90deg, var(--border) 1px, transparent 1px);\n background-size: 60px 60px; opacity: .28; pointer-events: none;\n }\n section, footer, .page-hero, .docs-layout { position: relative; z-index: 1; }\n a { text-decoration: none; color: inherit; }\n em { font-style: italic; }\n code {\n font-family: var(--font-mono); font-size: .85em;\n background: var(--bg-raised); border: 1px solid var(--border);\n border-radius: 4px; padding: 1px 6px; color: var(--accent);\n }\n .container { max-width: 1140px; margin: 0 auto; padding: 0 24px; }\n ::-webkit-scrollbar { width: 6px; }\n ::-webkit-scrollbar-track { background: var(--bg); }\n ::-webkit-scrollbar-thumb { background: var(--border-lit); border-radius: 3px; }\n\n /* ── PAGE HERO ── */\n .page-hero {\n padding: 48px 0 56px; border-bottom: 1px solid var(--border);\n }\n .page-hero .hero-glow {\n position: absolute; top: -40px; left: 10%; width: 500px; height: 350px;\n background: radial-gradient(ellipse, rgba(240,160,48,.1) 0%, transparent 68%);\n pointer-events: none;\n }\n .page-title {\n font-size: clamp(2rem, 5vw, 3.4rem); font-weight: 800;\n line-height: 1.1; letter-spacing: -.02em; margin-bottom: 24px;\n display: flex; align-items: baseline; gap: 16px; flex-wrap: wrap;\n }\n .project-version {\n font-family: var(--font-mono); font-size: clamp(.85rem, 2vw, 1.1rem);\n font-weight: 500; color: var(--accent);\n background: var(--accent-dim); border: 1px solid rgba(240,160,48,.3);\n border-radius: 6px; padding: 2px 10px; letter-spacing: .5px;\n }\n .hero-meta { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 40px; }\n .base-url-pill {\n display: flex; align-items: center; gap: 8px;\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: 7px; padding: 8px 14px;\n }\n .base-url-label { font-size: .72rem; font-family: var(--font-mono);\n color: var(--text-muted); text-transform: uppercase; letter-spacing: .5px; }\n .base-url-val { font-family: var(--font-mono); font-size: .8rem; color: var(--accent); }\n .count-pill {\n font-family: var(--font-mono); font-size: .72rem; color: var(--text-dim);\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: 7px; padding: 8px 14px;\n }\n\n /* ── TOOLBAR ── */\n .toolbar {\n display: flex; align-items: center; gap: 12px; flex-wrap: wrap;\n }\n .method-filters { display: flex; gap: 4px; flex-wrap: wrap; }\n .filter-btn {\n background: var(--bg-card); border: 1px solid var(--border);\n color: var(--text-dim); font-family: var(--font-mono);\n font-size: .72rem; font-weight: 600; letter-spacing: .5px;\n padding: 6px 12px; border-radius: 6px; cursor: pointer;\n transition: all .15s;\n }\n .filter-btn:hover { border-color: var(--border-lit); color: var(--text); }\n .filter-btn.active { background: var(--accent); color: #0d0d1a; border-color: var(--accent); }\n .filter-btn[data-method=\"GET\"].active { background: rgba(96,165,250,.18); color: #60a5fa; border-color: rgba(96,165,250,.4); }\n .filter-btn[data-method=\"POST\"].active { background: rgba(122,174,142,.18); color: #7AAE8E; border-color: rgba(122,174,142,.4); }\n .filter-btn[data-method=\"PUT\"].active { background: rgba(240,160,48,.18); color: #F0A030; border-color: rgba(240,160,48,.4); }\n .filter-btn[data-method=\"PATCH\"].active { background: rgba(251,191,36,.18); color: #fbbf24; border-color: rgba(251,191,36,.4); }\n .filter-btn[data-method=\"DELETE\"].active { background: rgba(248,113,113,.18); color: #f87171; border-color: rgba(248,113,113,.4); }\n .filter-btn[data-method=\"HEAD\"].active { background: rgba(167,139,250,.18); color: #a78bfa; border-color: rgba(167,139,250,.4); }\n .search-wrap { margin-left: auto; }\n .search-input {\n background: var(--bg-card); border: 1px solid var(--border);\n color: var(--text); font-family: var(--font-sans); font-size: .85rem;\n padding: 7px 14px; border-radius: 7px; width: 240px;\n outline: none; transition: border-color .2s;\n }\n .search-input::placeholder { color: var(--text-muted); }\n .search-input:focus { border-color: var(--border-lit); }\n\n /* ── DOCS LAYOUT ── */\n .docs-layout {\n display: grid; grid-template-columns: 260px 1fr;\n gap: 48px; padding: 52px 0 80px; max-width: 1140px;\n margin: 0 auto; padding-left: 24px; padding-right: 24px;\n align-items: start;\n }\n\n /* ── SIDEBAR ── */\n .docs-sidebar {\n position: sticky; top: 24px;\n max-height: calc(100vh - 48px);\n overflow-y: auto;\n overflow-x: hidden;\n scrollbar-width: none;\n padding-right: 4px;\n }\n .docs-sidebar::-webkit-scrollbar { display: none; }\n .sidebar-section { margin-bottom: 28px; }\n .sidebar-label {\n font-family: var(--font-mono); font-size: .68rem; font-weight: 600;\n color: var(--text-muted); letter-spacing: 1.2px; text-transform: uppercase;\n margin-bottom: 8px; padding: 0 4px;\n }\n .sidebar-link {\n display: flex; align-items: center; gap: 8px;\n padding: 7px 10px; border-radius: 6px;\n border-left: 2px solid transparent;\n font-size: .82rem; color: var(--text-dim); cursor: pointer;\n transition: background .15s, color .15s, border-color .15s;\n overflow: hidden; white-space: nowrap;\n }\n .sidebar-link:hover { background: var(--bg-raised); color: var(--text); }\n .sidebar-link.active { color: var(--accent); border-left-color: var(--accent); background: var(--accent-dim); }\n .sidebar-method-dot {\n width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0;\n }\n .sidebar-path { font-family: var(--font-mono); font-size: .72rem; }\n\n /* ── ENDPOINT CARDS ── */\n .endpoint-card {\n background: var(--bg-card); border: 1px solid var(--border);\n border-radius: var(--radius-lg); margin-bottom: 20px;\n overflow: hidden; transition: border-color .2s;\n animation: fadeUp .45s ease both;\n }\n .endpoint-card:hover { border-color: var(--border-lit); }\n @keyframes fadeUp {\n from { opacity: 0; transform: translateY(16px); }\n to { opacity: 1; transform: translateY(0); }\n }\n @media (prefers-reduced-motion: reduce) {\n .endpoint-card { animation: none; }\n }\n .endpoint-header {\n display: flex; align-items: center; gap: 14px;\n padding: 20px 24px 18px; border-bottom: 1px solid var(--border);\n flex-wrap: wrap;\n }\n .method-badges { display: flex; gap: 6px; flex-wrap: wrap; }\n .method-badge {\n font-family: var(--font-mono); font-size: .7rem; font-weight: 600;\n letter-spacing: .8px; padding: 4px 10px; border-radius: 5px;\n border: 1px solid; text-transform: uppercase;\n }\n .endpoint-path {\n font-family: var(--font-mono); font-size: .9rem; color: var(--text);\n background: none; border: none; padding: 0;\n word-break: break-all;\n }\n .endpoint-body { padding: 6px 24px 24px; }\n .endpoint-desc { font-size: .9rem; color: var(--text-dim); line-height: 1.7; margin-bottom: 20px; }\n\n /* ── PER-METHOD DOC BLOCKS ── */\n .method-block { padding-top: 20px; }\n .method-block + .method-block { margin-top: 4px; border-top: 1px solid var(--border); }\n .method-block-header { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }\n .method-block-header .method-badge { font-size: .68rem; }\n .method-block-empty { font-size: .82rem; color: var(--text-muted); }\n\n /* ── CODE BLOCKS ── */\n .example-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }\n .code-block-wrap {\n background: var(--bg-raised); border: 1px solid var(--border);\n border-radius: var(--radius); overflow: hidden;\n }\n .code-bar {\n display: flex; align-items: center; gap: 6px;\n padding: 9px 14px; border-bottom: 1px solid var(--border);\n background: var(--bg-card);\n }\n .dot { width: 11px; height: 11px; border-radius: 50%; }\n .dot-r { background: #ff5f57; }\n .dot-y { background: #febc2e; }\n .dot-g { background: #28c840; }\n .code-label { font-family: var(--font-mono); font-size: .68rem; color: var(--text-dim); margin-left: 4px; }\n pre.code-pre {\n font-family: var(--font-mono); font-size: .78rem; line-height: 1.7;\n padding: 16px 18px; overflow-x: auto; tab-size: 2; white-space: pre;\n }\n .c-dim { color: var(--text-muted); }\n .c-green { color: #7AAE8E; }\n .c-blue { color: #60a5fa; }\n .c-orange { color: #fb923c; }\n .c-purple { color: #a78bfa; }\n .c-accent { color: var(--accent); }\n .status-2xx { color: #7AAE8E; }\n .status-4xx { color: #f87171; }\n .status-5xx { color: #fb923c; }\n\n /* ── EMPTY STATE ── */\n .empty-state {\n text-align: center; padding: 80px 24px;\n color: var(--text-muted); font-size: .9rem;\n }\n\n /* ── RESPONSIVE ── */\n @media (max-width: 900px) {\n .docs-layout { grid-template-columns: 1fr; }\n .docs-sidebar { position: static; max-height: none; overflow-y: visible; padding-right: 0; }\n .example-grid { grid-template-columns: 1fr; }\n .search-wrap { margin-left: 0; width: 100%; }\n .search-input { width: 100%; }\n }\n @media (max-width: 600px) {\n .page-hero { padding: 32px 0 32px; }\n .page-title { font-size: 2rem; }\n }\n </style>\n</head>\n<body>\n\n <div class=\"page-hero\">\n <div class=\"hero-glow\"></div>\n <div class=\"container\">\n <h1 class=\"page-title\">${projectName}${projectVersion ? `<span class=\"project-version\">v${projectVersion}</span>` : ''}</h1>\n <div class=\"hero-meta\">\n <div class=\"base-url-pill\">\n <span class=\"base-url-label\">Base</span>\n <span class=\"base-url-val\">http://localhost:${port}${basePath}</span>\n </div>\n <div class=\"count-pill\" id=\"countPill\"></div>\n </div>\n <div class=\"toolbar\">\n <div class=\"method-filters\" id=\"methodFilters\">\n <button class=\"filter-btn active\" data-method=\"ALL\">ALL</button>\n </div>\n <div class=\"search-wrap\">\n <input type=\"text\" id=\"searchInput\" class=\"search-input\" placeholder=\"Search endpoints…\" />\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"docs-layout\">\n <aside class=\"docs-sidebar\" id=\"sidebar\"></aside>\n <main id=\"endpoints\"></main>\n </div>\n\n <script>\n const ROUTES = ${safeRoutes};\n const BASE_PATH = ${JSON.stringify(basePath)};\n const HTTP_STATUS = ${safeHttpStatus};\n\n const METHOD_STYLE = {\n GET: { bg: 'rgba(96,165,250,.14)', color: '#60a5fa', border: 'rgba(96,165,250,.35)' },\n POST: { bg: 'rgba(122,174,142,.14)', color: '#7AAE8E', border: 'rgba(122,174,142,.35)' },\n PUT: { bg: 'rgba(240,160,48,.14)', color: '#F0A030', border: 'rgba(240,160,48,.35)' },\n PATCH: { bg: 'rgba(251,191,36,.14)', color: '#fbbf24', border: 'rgba(251,191,36,.35)' },\n DELETE: { bg: 'rgba(248,113,113,.14)', color: '#f87171', border: 'rgba(248,113,113,.35)' },\n HEAD: { bg: 'rgba(167,139,250,.14)', color: '#a78bfa', border: 'rgba(167,139,250,.35)' },\n OPTIONS: { bg: 'rgba(148,163,184,.14)', color: '#94a3b8', border: 'rgba(148,163,184,.35)' },\n };\n\n function esc(s) {\n return String(s)\n .replace(/&/g,'&').replace(/</g,'<')\n .replace(/>/g,'>').replace(/\"/g,'"');\n }\n\n function methodBadge(m) {\n const s = METHOD_STYLE[m] || METHOD_STYLE.GET;\n return '<span class=\"method-badge\" style=\"background:' + s.bg + ';color:' + s.color + ';border-color:' + s.border + '\">' + m + '</span>';\n }\n\n function joinPath(base, p) {\n return (base.replace(/\\\\/+$/, '') + p) || '/';\n }\n\n function sidebarDot(method) {\n const s = METHOD_STYLE[method] || METHOD_STYLE.GET;\n return '<span class=\"sidebar-method-dot\" style=\"background:' + s.color + '\"></span>';\n }\n\n function statusClass(code) {\n if (code >= 200 && code < 300) return 'status-2xx';\n if (code >= 400 && code < 500) return 'status-4xx';\n if (code >= 500) return 'status-5xx';\n return '';\n }\n\n function renderSchema(val, indent) {\n const pad = ' '.repeat(indent || 0);\n if (val === null) return '<span class=\"c-dim\">null</span>';\n if (typeof val === 'string') {\n const isDate = /^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}/.test(val);\n return isDate ? '<span class=\"c-green\">Date</span>' : '<span class=\"c-purple\">String</span>';\n }\n if (typeof val === 'number') return '<span class=\"c-orange\">Number</span>';\n if (typeof val === 'boolean') return '<span class=\"c-purple\">Boolean</span>';\n if (Array.isArray(val)) {\n if (!val.length) return '[]';\n return '[\\\\n' + pad + ' ' + renderSchema(val[0], (indent || 0) + 1) + '\\\\n' + pad + ']';\n }\n if (typeof val === 'object') {\n const keys = Object.keys(val);\n if (!keys.length) return '{}';\n const inner = keys.map(function(k) {\n return pad + ' <span class=\"c-blue\">"' + esc(k) + '"</span>: ' + renderSchema(val[k], (indent || 0) + 1);\n }).join(',\\\\n');\n return '{\\\\n' + inner + '\\\\n' + pad + '}';\n }\n return esc(String(val));\n }\n\n function codeBlock(label, content) {\n return '<div class=\"code-block-wrap\">' +\n '<div class=\"code-bar\">' +\n '<span class=\"dot dot-r\"></span>' +\n '<span class=\"dot dot-y\"></span>' +\n '<span class=\"dot dot-g\"></span>' +\n '<span class=\"code-label\">' + esc(label) + '</span>' +\n '</div>' +\n '<pre class=\"code-pre\">' + content + '</pre>' +\n '</div>';\n }\n\n function buildRequestContent(route, method, example) {\n const req = example || {};\n let path = joinPath(BASE_PATH, route.urlPath);\n if (req.params) {\n for (const [k, v] of Object.entries(req.params)) {\n path = path.replace(':' + k, String(v));\n }\n }\n if (req.query && Object.keys(req.query).length) {\n path += '?' + new URLSearchParams(req.query).toString();\n }\n let lines = '<span class=\"c-accent\">' + esc(method) + '</span> <span class=\"c-blue\">' + esc(path) + '</span>';\n const headers = { ...(req.headers || {}) };\n if (req.body !== undefined && !headers['Content-Type']) {\n headers['Content-Type'] = 'application/json';\n }\n if (Object.keys(headers).length) {\n lines += '\\\\n' + Object.entries(headers)\n .map(([k, v]) => '<span class=\"c-dim\">' + esc(k) + ':</span> ' + esc(String(v)))\n .join('\\\\n');\n }\n if (req.body !== undefined) {\n lines += '\\\\n\\\\n' + renderSchema(req.body, 0);\n }\n return lines;\n }\n\n function buildResponseContent(example) {\n const resp = example || {};\n const code = resp.status || 200;\n const text = HTTP_STATUS[code] || 'OK';\n const cls = statusClass(code);\n let lines = 'HTTP/1.1 <span class=\"' + cls + '\">' + code + ' ' + esc(text) + '</span>';\n if (resp.body !== undefined) {\n lines += '\\\\n<span class=\"c-dim\">Content-Type:</span> application/json\\\\n\\\\n';\n lines += renderSchema(resp.body, 0);\n }\n return lines;\n }\n\n function renderMethodBlock(route, method) {\n const methodMeta = route.meta ? route.meta[method] : null;\n const header = '<div class=\"method-block-header\">' + methodBadge(method) + '</div>';\n\n if (!methodMeta) {\n return '<div class=\"method-block\" data-method=\"' + esc(method) + '\">' + header +\n '<p class=\"method-block-empty\">No documentation provided for this method.</p></div>';\n }\n\n const desc = methodMeta.description\n ? '<p class=\"endpoint-desc\">' + esc(methodMeta.description) + '</p>'\n : '';\n const reqHtml = methodMeta.request !== undefined\n ? codeBlock('request', buildRequestContent(route, method, methodMeta.request))\n : '';\n const respHtml = methodMeta.response !== undefined\n ? codeBlock('response', buildResponseContent(methodMeta.response))\n : '';\n const examples = reqHtml || respHtml\n ? '<div class=\"example-grid\">' + reqHtml + respHtml + '</div>'\n : '';\n\n return '<div class=\"method-block\" data-method=\"' + esc(method) + '\">' + header + desc + examples + '</div>';\n }\n\n function renderCard(route, index) {\n const id = 'ep-' + index;\n const fullPath = joinPath(BASE_PATH, route.urlPath);\n const badges = route.methods.map(methodBadge).join('');\n const body = route.methods.map(function(m) { return renderMethodBlock(route, m); }).join('');\n const delay = (index * 0.06).toFixed(2) + 's';\n return '<div class=\"endpoint-card\" id=\"' + id + '\" data-methods=\"' + route.methods.join(',') + '\" data-path=\"' + esc(fullPath) + '\" style=\"animation-delay:' + delay + '\">' +\n '<div class=\"endpoint-header\">' +\n '<div class=\"method-badges\">' + badges + '</div>' +\n '<code class=\"endpoint-path\">' + esc(fullPath) + '</code>' +\n '</div>' +\n '<div class=\"endpoint-body\">' + body + '</div>' +\n '</div>';\n }\n\n function buildMethodFilters() {\n const allMethods = [...new Set(ROUTES.flatMap(r => r.methods))].sort();\n const filtersEl = document.getElementById('methodFilters');\n allMethods.forEach(m => {\n const btn = document.createElement('button');\n btn.className = 'filter-btn';\n btn.dataset.method = m;\n btn.textContent = m;\n filtersEl.appendChild(btn);\n });\n }\n\n function buildSidebar(routes) {\n const sidebar = document.getElementById('sidebar');\n if (!routes.length) { sidebar.innerHTML = ''; return; }\n\n const label = document.createElement('div');\n label.className = 'sidebar-label';\n label.textContent = 'Endpoints';\n sidebar.appendChild(label);\n\n routes.forEach((route, i) => {\n const link = document.createElement('div');\n link.className = 'sidebar-link';\n link.dataset.target = 'ep-' + ROUTES.indexOf(route);\n link.innerHTML = sidebarDot(route.methods[0] || 'GET') +\n '<span class=\"sidebar-path\">' + esc(route.urlPath || '/') + '</span>';\n link.addEventListener('click', () => {\n const target = document.getElementById(link.dataset.target);\n if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });\n });\n sidebar.appendChild(link);\n });\n }\n\n let activeFilter = 'ALL';\n let searchQuery = '';\n\n function applyFilters() {\n const cards = document.querySelectorAll('.endpoint-card');\n let visible = 0;\n cards.forEach(card => {\n const methods = card.dataset.methods.split(',');\n const path = card.dataset.path || '';\n const matchMethod = activeFilter === 'ALL' || methods.includes(activeFilter);\n const matchSearch = !searchQuery || path.toLowerCase().includes(searchQuery);\n const show = matchMethod && matchSearch;\n card.style.display = show ? '' : 'none';\n if (show) visible++;\n });\n document.getElementById('empty-state').style.display = visible ? 'none' : 'block';\n\n // Sync sidebar visibility\n document.querySelectorAll('.sidebar-link').forEach(link => {\n const targetId = link.dataset.target;\n const targetCard = document.getElementById(targetId);\n link.style.display = targetCard && targetCard.style.display !== 'none' ? '' : 'none';\n });\n }\n\n function init() {\n const count = ROUTES.length;\n document.getElementById('countPill').textContent = count + ' endpoint' + (count !== 1 ? 's' : '');\n\n buildMethodFilters();\n\n const container = document.getElementById('endpoints');\n container.innerHTML = ROUTES.map((r, i) => renderCard(r, i)).join('');\n\n // Add empty state after cards\n const emptyEl = document.createElement('div');\n emptyEl.id = 'empty-state';\n emptyEl.className = 'empty-state';\n emptyEl.style.display = 'none';\n emptyEl.innerHTML = '<p>No endpoints match your filter.</p>';\n container.after(emptyEl);\n\n buildSidebar(ROUTES);\n\n // Method filter clicks\n document.getElementById('methodFilters').addEventListener('click', e => {\n const btn = e.target.closest('.filter-btn');\n if (!btn) return;\n document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));\n btn.classList.add('active');\n activeFilter = btn.dataset.method;\n applyFilters();\n });\n\n // Search\n document.getElementById('searchInput').addEventListener('input', e => {\n searchQuery = e.target.value.trim().toLowerCase();\n applyFilters();\n });\n\n // Scroll spy for sidebar\n const cardEls = document.querySelectorAll('.endpoint-card');\n const sidebarLinks = document.querySelectorAll('.sidebar-link');\n const observer = new IntersectionObserver(entries => {\n entries.forEach(entry => {\n if (entry.isIntersecting) {\n const id = entry.target.id;\n sidebarLinks.forEach(l => l.classList.toggle('active', l.dataset.target === id));\n const sidebar = document.getElementById('sidebar');\n const activeLink = sidebar && sidebar.querySelector('.sidebar-link.active');\n if (sidebar && activeLink) {\n const linkTop = activeLink.getBoundingClientRect().top - sidebar.getBoundingClientRect().top + sidebar.scrollTop;\n sidebar.scrollTo({ top: linkTop, behavior: 'smooth' });\n }\n }\n });\n }, { rootMargin: '-80px 0px -60% 0px' });\n cardEls.forEach(el => observer.observe(el));\n\n }\n\n try {\n init();\n } catch (e) {\n document.body.insertAdjacentHTML('afterbegin',\n '<div style=\"position:fixed;top:60px;left:0;right:0;z-index:9999;background:#7f1d1d;color:#fca5a5;padding:16px 24px;font-family:monospace;font-size:13px;border-bottom:1px solid #ef4444\">' +\n '<strong>Dashboard JS error:</strong> ' + (e && e.message ? e.message : String(e)) +\n (e && e.stack ? '<pre style=\"margin-top:8px;white-space:pre-wrap\">' + e.stack + '</pre>' : '') +\n '</div>'\n );\n }\n </script>\n</body>\n</html>`;\n}\n","import type { Request, RequestHandler } from 'express';\nimport { isCacheConfigured, rawIncr } from './cache/index.js';\nimport { getLogger } from './logger.js';\n\n// rateLimit(): a fixed-window limit (windows aligned to the clock) counted in the cache\n// (`cache.incr`), so every worker — and with Redis every instance — shares one count. An\n// in-memory counter per worker would let N workers accept N × max.\n\nexport interface RateLimitOptions {\n /** Window length: seconds, or `'30s'`, `'15m'`, `'1h'`, `'1d'`. */\n window: number | string;\n /** Requests allowed per window and key. */\n max: number;\n /**\n * Who a request counts against. Default: the client IP (`req.ip`) — behind a proxy or load\n * balancer set `trustProxy` in ignite(), or every client shares the proxy's IP. Return\n * `undefined` to not limit this request.\n */\n key?: (req: Request) => string | undefined;\n /**\n * Which counter: requests to routes with the same name share a limit. Default: the route\n * pattern (`/users/:id`), so each route file has its own — or the path, for middleware\n * that isn't on a route.\n */\n name?: string;\n /** Body of the 429 response. Default: `'Too many requests, try again later'`. */\n message?: string;\n /**\n * The cache can't be reached: `'allow'` (default) lets requests through — a limiter\n * shouldn't take the API down with it; `'reject'` answers 503.\n */\n onCacheError?: 'allow' | 'reject';\n /** Send `RateLimit-Limit/Remaining/Reset` (and `Retry-After` on 429). Default: true. */\n headers?: boolean;\n}\n\nconst UNITS: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86_400 };\n\nexport function parseWindow(window: number | string): number {\n if (typeof window === 'number') {\n if (window > 0) return window;\n } else {\n const m = /^(\\d+(?:\\.\\d+)?)\\s*(s|m|h|d)$/.exec(window.trim());\n if (m) return Number(m[1]) * UNITS[m[2]!]!;\n }\n throw new Error(`[EFC] rateLimit: window must be seconds or like '15m' — got ${String(window)}`);\n}\n\nlet lastCacheError = 0;\n\n/**\n * Limits requests per key (default: client IP) to `max` per `window`, counted in the cache\n * so the limit holds across every worker and instance:\n *\n * ```ts\n * export const middlewares = [rateLimit({ window: '15m', max: 10 })];\n * ```\n *\n * Needs `cache` in ignite() — use the Redis backend when you run more than one instance.\n */\nexport function rateLimit(options: RateLimitOptions): RequestHandler {\n const windowSeconds = parseWindow(options.window);\n if (!Number.isInteger(options.max) || options.max < 1) {\n throw new Error('[EFC] rateLimit: max must be a positive integer');\n }\n const keyOf = options.key ?? ((req: Request) => req.ip ?? req.socket.remoteAddress);\n const message = options.message ?? 'Too many requests, try again later';\n const headers = options.headers ?? true;\n\n return (req, res, next) => {\n void (async () => {\n const who = keyOf(req);\n if (who === undefined) return next();\n if (!isCacheConfigured()) {\n throw new Error('[EFC] rateLimit needs a cache — pass cache: { backend } to ignite()');\n }\n const bucket = options.name ?? req.baseUrl + (req.route?.path ?? req.path);\n // Windows are aligned to the clock: every key restarts at the same boundary, and the\n // reset is exact. The key outlives its window by a second, then expires.\n const windowMs = windowSeconds * 1000;\n const now = Date.now();\n const slot = Math.floor(now / windowMs);\n const resetMs = (slot + 1) * windowMs - now;\n let count: number;\n try {\n count = (await rawIncr(`rl:${bucket}:${who}:${slot}`, Math.ceil(resetMs / 1000) + 1)).value;\n } catch (err) {\n if (Date.now() - lastCacheError > 30_000) {\n lastCacheError = Date.now();\n getLogger().error(\n { err },\n `rateLimit: cache unavailable — ${options.onCacheError === 'reject' ? 'rejecting with 503' : 'allowing requests'}`,\n );\n }\n if (options.onCacheError === 'reject') {\n res.status(503).json({ error: 'Service Unavailable', statusCode: 503 });\n return;\n }\n return next();\n }\n const resetSeconds = Math.max(1, Math.ceil(resetMs / 1000));\n if (headers) {\n res.setHeader('RateLimit-Limit', String(options.max));\n res.setHeader('RateLimit-Remaining', String(Math.max(0, options.max - count)));\n res.setHeader('RateLimit-Reset', String(resetSeconds));\n }\n if (count > options.max) {\n if (headers) res.setHeader('Retry-After', String(resetSeconds));\n res.status(429).json({ error: message, statusCode: 429 });\n return;\n }\n next();\n })().catch(next);\n };\n}\n","import type { Request, RequestHandler } from 'express';\nimport { cache } from './index.js';\nimport { getCurrentUser } from '../context.js';\n\nexport interface CacheResponseOptions {\n /** Seconds to keep a response. */\n ttl: number;\n /**\n * Cache per authenticated user (keyed by the JWT's `sub`/`id`). Put `requireAuth`\n * before this middleware. Without it, a response is shared by everyone hitting the URL.\n */\n perUser?: boolean;\n /** Custom cache key. Default: the request's original URL (path + query). */\n key?: (req: Request) => string;\n}\n\ninterface Stored {\n status: number;\n body: unknown;\n}\n\n/** Key prefix for cached responses — `cache.clear(RESPONSE_PREFIX + '/v1/api/posts')` drops those. */\nexport const RESPONSE_PREFIX = 'res:';\n\n/**\n * Caches successful (200) JSON responses of GET/HEAD requests. Adds `X-Cache: HIT|MISS`.\n *\n * @example\n * export const middlewares = [cacheResponse(60)];\n * export const middlewares = [requireAuth, cacheResponse({ ttl: 30, perUser: true })];\n */\nexport function cacheResponse(options: number | CacheResponseOptions): RequestHandler {\n const opts: CacheResponseOptions = typeof options === 'number' ? { ttl: options } : options;\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') return next();\n\n let scope = '';\n if (opts.perUser) {\n const user = getCurrentUser();\n const id = user?.['sub'] ?? user?.['id'];\n // Never fall back to a shared entry for a per-user route.\n if (id === undefined) return next();\n scope = `u:${String(id)}:`;\n }\n const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);\n\n void (async () => {\n const hit = await cache.get<Stored>(key);\n if (hit) {\n res.setHeader('X-Cache', 'HIT');\n res.status(hit.status).json(hit.body);\n return;\n }\n res.setHeader('X-Cache', 'MISS');\n const json = res.json.bind(res);\n res.json = (body: unknown) => {\n if (res.statusCode === 200) void cache.set(key, { status: 200, body }, { ttl: opts.ttl });\n return json(body);\n };\n next();\n })().catch(next);\n };\n}\n","import type { RequestHandler } from 'express';\n\n/**\n * Chains multiple Express request handlers into a single handler.\n * Each handler calls the next one via its `next` callback.\n *\n * @example\n * export const GET = compose(requireAuth, rateLimiter, myHandler);\n */\nexport function compose(...handlers: RequestHandler[]): RequestHandler {\n return (req, res, next) => {\n function dispatch(i: number): void {\n if (i >= handlers.length) {\n next();\n return;\n }\n const handler = handlers[i];\n if (!handler) {\n next();\n return;\n }\n try {\n Promise.resolve(\n handler(req, res, (err?: unknown) => (err ? next(err) : dispatch(i + 1))),\n ).catch(next);\n } catch (err) {\n next(err);\n }\n }\n\n dispatch(0);\n };\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
|
-
import { S as Simplify, I as InferSchema, b as InferCreateInput, M as ModelSchema, c as ModelOptions, d as InferredModel, e as TableSchema, f as TableOptions, g as SortDirection, h as InferRecord, C as CollectionSchema, R as RouteEntry, E as EFCConfig } from './types-
|
|
3
|
-
export { A as AuthStrategy, i as CacheConfig, j as CollectionFieldDefinition, k as CorsConfig, D as DatabaseEngine, l as DatabasePoolConfig, m as DefaultOperator, F as FieldDefinition, n as Filter, o as FilterOperators, p as FindOptions, G as GeoPoint, q as IndexDefinition, r as InferCreate, L as LoggingConfig, s as MigrationContext, t as ModelCRUD, u as ModelQueryOptions, v as ModelRecord, Q as QueryLogConfig,
|
|
2
|
+
import { S as Simplify, I as InferSchema, b as InferCreateInput, M as ModelSchema, c as ModelOptions, d as InferredModel, e as TableSchema, f as TableOptions, g as SortDirection, h as InferRecord, C as CollectionSchema, R as RouteEntry, E as EFCConfig } from './types-D3QmZgeX.cjs';
|
|
3
|
+
export { A as AuthStrategy, i as CacheConfig, j as CollectionFieldDefinition, k as CorsConfig, D as DatabaseEngine, l as DatabasePoolConfig, m as DefaultOperator, F as FieldDefinition, n as Filter, o as FilterOperators, p as FindOptions, G as GeoPoint, q as IndexDefinition, r as InferCreate, J as JSONSchema, L as LoggingConfig, s as MigrationContext, t as ModelCRUD, u as ModelQueryOptions, v as ModelRecord, O as OpenAPIDocument, w as OpenAPIOptions, Q as QueryLogConfig, x as RequestSchema, y as RouteMeta, z as RouteMethodMeta, B as RouteSchema, H as ScalarKeys, K as SchemaField, N as TableFieldDefinition, P as TableRelation, U as TableSchemaField, a as TaskDefinition, T as TaskOptions, V as Update, W as ValidationIssue, X as Validator, Y as WebSocketHandler, Z as WebSocketOptions, _ as attachWebSockets, $ as closeWebSockets, a0 as generateOpenAPI } from './types-D3QmZgeX.cjs';
|
|
4
4
|
import { Logger } from 'pino';
|
|
5
5
|
import { Request, RequestHandler } from 'express';
|
|
6
6
|
export { listTasks } from './tasks/index.cjs';
|
|
7
|
+
import 'ws';
|
|
7
8
|
|
|
8
9
|
/** `id`'s type from `options.id`: uuid → string, serial → number, bigserial → bigint. */
|
|
9
10
|
type IdOf<O> = O extends {
|
|
@@ -653,6 +654,30 @@ declare module 'express-serve-static-core' {
|
|
|
653
654
|
}
|
|
654
655
|
}
|
|
655
656
|
|
|
657
|
+
/** Aggregated per-process model operation statistics; never contains SQL/parameter values. */
|
|
658
|
+
interface QueryMetric {
|
|
659
|
+
model: string;
|
|
660
|
+
op: string;
|
|
661
|
+
calls: number;
|
|
662
|
+
errors: number;
|
|
663
|
+
statements: number;
|
|
664
|
+
totalMs: number;
|
|
665
|
+
minMs: number;
|
|
666
|
+
maxMs: number;
|
|
667
|
+
meanMs: number;
|
|
668
|
+
slow: number;
|
|
669
|
+
}
|
|
670
|
+
interface QueryMetricsSnapshot {
|
|
671
|
+
enabled: boolean;
|
|
672
|
+
since: number;
|
|
673
|
+
dropped: number;
|
|
674
|
+
entries: ReadonlyArray<QueryMetric>;
|
|
675
|
+
}
|
|
676
|
+
/** Returns detached, deterministically ordered counters; no logs or SQL are exposed. */
|
|
677
|
+
declare function getQueryMetrics(): QueryMetricsSnapshot;
|
|
678
|
+
/** Clears this process's counters/window; does not disable collection. */
|
|
679
|
+
declare function resetQueryMetrics(): void;
|
|
680
|
+
|
|
656
681
|
interface CacheSetOptions {
|
|
657
682
|
/** Seconds until the entry expires. Omit for no expiry. */
|
|
658
683
|
ttl?: number;
|
|
@@ -1166,4 +1191,4 @@ declare function workerCount(): number;
|
|
|
1166
1191
|
declare function ignite(config: EFCConfig): Promise<http.Server | undefined>;
|
|
1167
1192
|
declare function gracefulShutdown(server: http.Server | undefined, timeoutMs?: number): void;
|
|
1168
1193
|
|
|
1169
|
-
export { type Accumulator, type CollectionBulkOp, type CollectionBulkResult, type CollectionChange, type CollectionChangeStream, type CollectionFilter, type CollectionFindOptions, type CollectionModel, type CollectionOptions, CollectionSchema, type CollectionUpdate, type CollectionWriteResult, EFCConfig, type FieldRef, type GroupResult, HttpError, InferCreateInput, InferRecord, InferSchema, type InferTableRecord, type JsonFilter, type ListFilter, type LookedUp, type LookupTarget, ModelOptions, ModelSchema, ModelValidationError, Pipeline, type RateLimitOptions, RouteEntry, type ScalarFilter, SortDirection, type StringFilter, type TableAggregateArgs, type TableAggregateResult, type TableCreateData, type TableCreateInput, type TableFindManyArgs, type TableGroupByArgs, type TableInclude, type TableModel, TableOptions, type TableOrderBy, type TableRecord, type TableResult, TableSchema, type TableSelect, type TableUpdateData, type TableUpdateInput, type TableWhere, type TableWhereUnique, type Tables, cache, cacheResponse, compose, db, defineCollection, defineModel, defineTable, getDbClient, getLogger, gracefulShutdown, ignite, isHttpError, logger, rateLimit, scanDir, setDbClient, transaction, workerCount };
|
|
1194
|
+
export { type Accumulator, type CollectionBulkOp, type CollectionBulkResult, type CollectionChange, type CollectionChangeStream, type CollectionFilter, type CollectionFindOptions, type CollectionModel, type CollectionOptions, CollectionSchema, type CollectionUpdate, type CollectionWriteResult, EFCConfig, type FieldRef, type GroupResult, HttpError, InferCreateInput, InferRecord, InferSchema, type InferTableRecord, type JsonFilter, type ListFilter, type LookedUp, type LookupTarget, ModelOptions, ModelSchema, ModelValidationError, Pipeline, type QueryMetric, type QueryMetricsSnapshot, type RateLimitOptions, RouteEntry, type ScalarFilter, SortDirection, type StringFilter, type TableAggregateArgs, type TableAggregateResult, type TableCreateData, type TableCreateInput, type TableFindManyArgs, type TableGroupByArgs, type TableInclude, type TableModel, TableOptions, type TableOrderBy, type TableRecord, type TableResult, TableSchema, type TableSelect, type TableUpdateData, type TableUpdateInput, type TableWhere, type TableWhereUnique, type Tables, cache, cacheResponse, compose, db, defineCollection, defineModel, defineTable, getDbClient, getLogger, getQueryMetrics, gracefulShutdown, ignite, isHttpError, logger, rateLimit, resetQueryMetrics, scanDir, setDbClient, transaction, workerCount };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
|
-
import { S as Simplify, I as InferSchema, b as InferCreateInput, M as ModelSchema, c as ModelOptions, d as InferredModel, e as TableSchema, f as TableOptions, g as SortDirection, h as InferRecord, C as CollectionSchema, R as RouteEntry, E as EFCConfig } from './types-
|
|
3
|
-
export { A as AuthStrategy, i as CacheConfig, j as CollectionFieldDefinition, k as CorsConfig, D as DatabaseEngine, l as DatabasePoolConfig, m as DefaultOperator, F as FieldDefinition, n as Filter, o as FilterOperators, p as FindOptions, G as GeoPoint, q as IndexDefinition, r as InferCreate, L as LoggingConfig, s as MigrationContext, t as ModelCRUD, u as ModelQueryOptions, v as ModelRecord, Q as QueryLogConfig,
|
|
2
|
+
import { S as Simplify, I as InferSchema, b as InferCreateInput, M as ModelSchema, c as ModelOptions, d as InferredModel, e as TableSchema, f as TableOptions, g as SortDirection, h as InferRecord, C as CollectionSchema, R as RouteEntry, E as EFCConfig } from './types-D3QmZgeX.js';
|
|
3
|
+
export { A as AuthStrategy, i as CacheConfig, j as CollectionFieldDefinition, k as CorsConfig, D as DatabaseEngine, l as DatabasePoolConfig, m as DefaultOperator, F as FieldDefinition, n as Filter, o as FilterOperators, p as FindOptions, G as GeoPoint, q as IndexDefinition, r as InferCreate, J as JSONSchema, L as LoggingConfig, s as MigrationContext, t as ModelCRUD, u as ModelQueryOptions, v as ModelRecord, O as OpenAPIDocument, w as OpenAPIOptions, Q as QueryLogConfig, x as RequestSchema, y as RouteMeta, z as RouteMethodMeta, B as RouteSchema, H as ScalarKeys, K as SchemaField, N as TableFieldDefinition, P as TableRelation, U as TableSchemaField, a as TaskDefinition, T as TaskOptions, V as Update, W as ValidationIssue, X as Validator, Y as WebSocketHandler, Z as WebSocketOptions, _ as attachWebSockets, $ as closeWebSockets, a0 as generateOpenAPI } from './types-D3QmZgeX.js';
|
|
4
4
|
import { Logger } from 'pino';
|
|
5
5
|
import { Request, RequestHandler } from 'express';
|
|
6
6
|
export { listTasks } from './tasks/index.js';
|
|
7
|
+
import 'ws';
|
|
7
8
|
|
|
8
9
|
/** `id`'s type from `options.id`: uuid → string, serial → number, bigserial → bigint. */
|
|
9
10
|
type IdOf<O> = O extends {
|
|
@@ -653,6 +654,30 @@ declare module 'express-serve-static-core' {
|
|
|
653
654
|
}
|
|
654
655
|
}
|
|
655
656
|
|
|
657
|
+
/** Aggregated per-process model operation statistics; never contains SQL/parameter values. */
|
|
658
|
+
interface QueryMetric {
|
|
659
|
+
model: string;
|
|
660
|
+
op: string;
|
|
661
|
+
calls: number;
|
|
662
|
+
errors: number;
|
|
663
|
+
statements: number;
|
|
664
|
+
totalMs: number;
|
|
665
|
+
minMs: number;
|
|
666
|
+
maxMs: number;
|
|
667
|
+
meanMs: number;
|
|
668
|
+
slow: number;
|
|
669
|
+
}
|
|
670
|
+
interface QueryMetricsSnapshot {
|
|
671
|
+
enabled: boolean;
|
|
672
|
+
since: number;
|
|
673
|
+
dropped: number;
|
|
674
|
+
entries: ReadonlyArray<QueryMetric>;
|
|
675
|
+
}
|
|
676
|
+
/** Returns detached, deterministically ordered counters; no logs or SQL are exposed. */
|
|
677
|
+
declare function getQueryMetrics(): QueryMetricsSnapshot;
|
|
678
|
+
/** Clears this process's counters/window; does not disable collection. */
|
|
679
|
+
declare function resetQueryMetrics(): void;
|
|
680
|
+
|
|
656
681
|
interface CacheSetOptions {
|
|
657
682
|
/** Seconds until the entry expires. Omit for no expiry. */
|
|
658
683
|
ttl?: number;
|
|
@@ -1166,4 +1191,4 @@ declare function workerCount(): number;
|
|
|
1166
1191
|
declare function ignite(config: EFCConfig): Promise<http.Server | undefined>;
|
|
1167
1192
|
declare function gracefulShutdown(server: http.Server | undefined, timeoutMs?: number): void;
|
|
1168
1193
|
|
|
1169
|
-
export { type Accumulator, type CollectionBulkOp, type CollectionBulkResult, type CollectionChange, type CollectionChangeStream, type CollectionFilter, type CollectionFindOptions, type CollectionModel, type CollectionOptions, CollectionSchema, type CollectionUpdate, type CollectionWriteResult, EFCConfig, type FieldRef, type GroupResult, HttpError, InferCreateInput, InferRecord, InferSchema, type InferTableRecord, type JsonFilter, type ListFilter, type LookedUp, type LookupTarget, ModelOptions, ModelSchema, ModelValidationError, Pipeline, type RateLimitOptions, RouteEntry, type ScalarFilter, SortDirection, type StringFilter, type TableAggregateArgs, type TableAggregateResult, type TableCreateData, type TableCreateInput, type TableFindManyArgs, type TableGroupByArgs, type TableInclude, type TableModel, TableOptions, type TableOrderBy, type TableRecord, type TableResult, TableSchema, type TableSelect, type TableUpdateData, type TableUpdateInput, type TableWhere, type TableWhereUnique, type Tables, cache, cacheResponse, compose, db, defineCollection, defineModel, defineTable, getDbClient, getLogger, gracefulShutdown, ignite, isHttpError, logger, rateLimit, scanDir, setDbClient, transaction, workerCount };
|
|
1194
|
+
export { type Accumulator, type CollectionBulkOp, type CollectionBulkResult, type CollectionChange, type CollectionChangeStream, type CollectionFilter, type CollectionFindOptions, type CollectionModel, type CollectionOptions, CollectionSchema, type CollectionUpdate, type CollectionWriteResult, EFCConfig, type FieldRef, type GroupResult, HttpError, InferCreateInput, InferRecord, InferSchema, type InferTableRecord, type JsonFilter, type ListFilter, type LookedUp, type LookupTarget, ModelOptions, ModelSchema, ModelValidationError, Pipeline, type QueryMetric, type QueryMetricsSnapshot, type RateLimitOptions, RouteEntry, type ScalarFilter, SortDirection, type StringFilter, type TableAggregateArgs, type TableAggregateResult, type TableCreateData, type TableCreateInput, type TableFindManyArgs, type TableGroupByArgs, type TableInclude, type TableModel, TableOptions, type TableOrderBy, type TableRecord, type TableResult, TableSchema, type TableSelect, type TableUpdateData, type TableUpdateInput, type TableWhere, type TableWhereUnique, type Tables, cache, cacheResponse, compose, db, defineCollection, defineModel, defineTable, getDbClient, getLogger, getQueryMetrics, gracefulShutdown, ignite, isHttpError, logger, rateLimit, resetQueryMetrics, scanDir, setDbClient, transaction, workerCount };
|