express-file-cluster 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/auth/index.cjs +8 -2
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +13 -2
  4. package/dist/auth/index.d.ts +13 -2
  5. package/dist/auth/index.js +9 -3
  6. package/dist/{chunk-2J3HHQKP.cjs → chunk-ANUSWEAP.cjs} +55 -2
  7. package/dist/chunk-ANUSWEAP.cjs.map +1 -0
  8. package/dist/{chunk-RSZB7VAO.js → chunk-ATL4GYFU.js} +54 -1
  9. package/dist/chunk-ATL4GYFU.js.map +1 -0
  10. package/dist/{chunk-2PBMLMO4.js → chunk-QKQZF573.js} +26 -4
  11. package/dist/chunk-QKQZF573.js.map +1 -0
  12. package/dist/{chunk-6QNLN6AI.js → chunk-RRQ2RK5M.js} +353 -3
  13. package/dist/chunk-RRQ2RK5M.js.map +1 -0
  14. package/dist/{chunk-RGTENTDN.cjs → chunk-RTF7PHS2.cjs} +432 -82
  15. package/dist/chunk-RTF7PHS2.cjs.map +1 -0
  16. package/dist/{chunk-66R7S7J3.cjs → chunk-X2US4RAM.cjs} +26 -4
  17. package/dist/chunk-X2US4RAM.cjs.map +1 -0
  18. package/dist/cli/db-runner.cjs +17 -17
  19. package/dist/cli/db-runner.js +2 -2
  20. package/dist/cli/index.cjs +315 -26
  21. package/dist/cli/index.cjs.map +1 -1
  22. package/dist/cli/index.js +295 -6
  23. package/dist/cli/index.js.map +1 -1
  24. package/dist/docs/api-reference/auth.md +35 -0
  25. package/dist/docs/api-reference/collection.md +155 -0
  26. package/dist/docs/cli/add.md +36 -7
  27. package/dist/docs/guides/authentication.md +80 -4
  28. package/dist/docs/guides/coming-from-mongoose.md +60 -0
  29. package/dist/docs/guides/which-api.md +21 -12
  30. package/dist/docs/index.md +4 -2
  31. package/dist/docs/skills/SKILL.md +3 -3
  32. package/dist/docs/skills/api-surface.md +16 -0
  33. package/dist/docs/skills/what-not-to-invent.md +3 -2
  34. package/dist/index.cjs +18 -16
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +193 -3
  37. package/dist/index.d.ts +193 -3
  38. package/dist/index.js +5 -3
  39. package/dist/index.js.map +1 -1
  40. package/dist/registry/index.json +1 -1
  41. package/dist/registry/js-mongo/admin-users.json +1 -1
  42. package/dist/registry/js-mongo/auth.json +1 -1
  43. package/dist/registry/js-mongo/auth@apple.json +1 -1
  44. package/dist/registry/js-mongo/auth@google.json +1 -1
  45. package/dist/registry/js-mongo/email-client.json +1 -1
  46. package/dist/registry/js-mongo/forgot-password.json +1 -1
  47. package/dist/registry/js-pg-model/admin-users.json +1 -1
  48. package/dist/registry/js-pg-model/auth.json +1 -1
  49. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  50. package/dist/registry/js-pg-model/auth@google.json +1 -1
  51. package/dist/registry/js-pg-model/email-client.json +1 -1
  52. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  53. package/dist/registry/js-pg-table/admin-users.json +1 -1
  54. package/dist/registry/js-pg-table/auth.json +1 -1
  55. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  56. package/dist/registry/js-pg-table/auth@google.json +1 -1
  57. package/dist/registry/js-pg-table/email-client.json +1 -1
  58. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  59. package/dist/registry/ts-mongo/admin-users.json +1 -1
  60. package/dist/registry/ts-mongo/auth.json +1 -1
  61. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  62. package/dist/registry/ts-mongo/auth@google.json +1 -1
  63. package/dist/registry/ts-mongo/email-client.json +1 -1
  64. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  65. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  66. package/dist/registry/ts-pg-model/auth.json +1 -1
  67. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  68. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  69. package/dist/registry/ts-pg-model/email-client.json +1 -1
  70. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  71. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  72. package/dist/registry/ts-pg-table/auth.json +1 -1
  73. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  74. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  75. package/dist/registry/ts-pg-table/email-client.json +1 -1
  76. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  77. package/dist/tasks/index.d.cts +1 -1
  78. package/dist/tasks/index.d.ts +1 -1
  79. package/dist/{types-gyvA7BtO.d.ts → types-BY-ObnZH.d.cts} +36 -7
  80. package/dist/{types-gyvA7BtO.d.cts → types-BY-ObnZH.d.ts} +36 -7
  81. package/package.json +3 -3
  82. package/dist/chunk-2J3HHQKP.cjs.map +0 -1
  83. package/dist/chunk-2PBMLMO4.js.map +0 -1
  84. package/dist/chunk-66R7S7J3.cjs.map +0 -1
  85. package/dist/chunk-6QNLN6AI.js.map +0 -1
  86. package/dist/chunk-RGTENTDN.cjs.map +0 -1
  87. package/dist/chunk-RSZB7VAO.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/router/validate.ts","../src/router/mount.ts","../src/cluster/index.ts","../src/tasks/scanner.ts","../src/dashboard.ts","../src/cache/response.ts","../src/compose.ts"],"sourcesContent":["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 { 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 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 // 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 if (database === 'mongodb' && databaseUrl) {\n const conn = await connectMongo(databaseUrl, config.databasePool);\n setDbClient(conn as unknown as Record<string, unknown>);\n } else if (database === 'postgresql' && databaseUrl) {\n const pool = await connectPostgres(databaseUrl, config.databasePool);\n setDbClient(pool as unknown as Record<string, unknown>);\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 const duckTyped =\n err instanceof Error && typeof (err as { statusCode?: unknown }).statusCode === 'number'\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 { cacheResponse } from './cache/response.js';\nexport { compose } from './compose.js';\nexport { db, setDbClient, getDbClient, defineModel, defineTable } from './db/index.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 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,'&amp;').replace(/</g,'&lt;')\n .replace(/>/g,'&gt;').replace(/\"/g,'&quot;');\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\">&quot;' + esc(k) + '&quot;</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 { 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAOA,SAAQ;AACf,OAAO,aAAa;AACpB,OAAO,UAAU;AACjB,OAAO,kBAAkB;AACzB,OAAOC,cAAa;AACpB,OAAO,QAAQ;AACf,OAAOC,WAAU;;;ACJjB,IAAM,YAAY,CAAC,UAAU,SAAS,MAAM;AAW5C,SAAS,gBAAgB,OAAwC;AAC/D,SACE,SAAS,QACT,OAAO,UAAU,YACjB,UAAU,KAAK,CAAC,QAAQ,OAAQ,KAAiC;AAErE;AAGO,SAAS,UACd,QACA,QAC2B;AAC3B,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,WAAY,OAAmC,MAAM;AAC3D,MAAI,gBAAgB,QAAQ,EAAG,QAAO;AACtC,SAAO,gBAAgB,MAAM,IAAI,SAAS;AAC5C;AAIA,SAAS,aAAaC,OAAyB;AAC7C,MAAI,CAACA,MAAM,QAAO;AAClB,SAAOA,MACJ,IAAI,CAAC,MAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,SAAS,IAAI,EAAE,MAAM,CAAE,EAC1E,IAAI,MAAM,EACV,KAAK,GAAG;AACb;AAIA,eAAe,IAAI,WAAsB,OAAyC;AAChF,QAAM,MAAO,UAAsE,WAAW;AAC9F,MAAI,OAAO,OAAO,IAAI,aAAa,YAAY;AAC7C,WAAQ,MAAM,IAAI,SAAS,KAAK;AAAA,EAClC;AACA,QAAM,IAAI;AAIV,QAAM,QAAQ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C;AAAA,MAChB,GAAG,YAAY,GAAK,EAAE,MAAM;AAAA,IAC9B;AAAA,EACF;AACA,UAAQ,GAAG,WAAW,MAAM,SAAS,SAAS,CAAC;AAC/C,UAAQ,GAAG,UAAU,MAAM,SAAS,QAAQ,CAAC;AAC/C;","names":["fs","cluster","path","path","path","fs","cluster"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/router/validate.ts","../src/router/mount.ts","../src/cluster/index.ts","../src/tasks/scanner.ts","../src/dashboard.ts","../src/cache/response.ts","../src/compose.ts"],"sourcesContent":["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 { 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 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 // 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 if (database === 'mongodb' && databaseUrl) {\n const conn = await connectMongo(databaseUrl, config.databasePool);\n setDbClient(conn as unknown as Record<string, unknown>);\n } else if (database === 'postgresql' && databaseUrl) {\n const pool = await connectPostgres(databaseUrl, config.databasePool);\n setDbClient(pool as unknown as Record<string, unknown>);\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 const duckTyped =\n err instanceof Error && typeof (err as { statusCode?: unknown }).statusCode === 'number'\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 { 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 { 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,'&amp;').replace(/</g,'&lt;')\n .replace(/>/g,'&gt;').replace(/\"/g,'&quot;');\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\">&quot;' + esc(k) + '&quot;</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 { 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"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"key": "ts-mongo",
@@ -1 +1 @@
1
- {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false, log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport bcrypt from 'bcrypt';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n if (!name || !email || !password) return res.status(400).json({ error: 'name, email and password are required' });\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await bcrypt.hash(password, 10);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false, log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n if (!name || !email || !password) return res.status(400).json({ error: 'name, email and password are required' });\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken } from 'express-file-cluster/auth';\nimport bcrypt from 'bcrypt';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n}\n\nexport const POST = async (req, res) => {\n const { email, password } = req.body;\n if (!email || !password) return res.status(400).json({ error: 'email and password are required' });\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await bcrypt.compare(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin' });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await bcrypt.compare(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n await issueRefreshToken(res, User, user.id);\n res.json({ message: 'Logged in' });\n};\n"},{"path":"src/api/auth/logout.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import bcrypt from 'bcrypt';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n if (!name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await bcrypt.hash(password, 10);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: __, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{"bcrypt":"^5.1.0"},"devDependencies":{},"env":[]}
1
+ {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n}\n\nexport const POST = async (req, res) => {\n const { email, password } = req.body;\n if (!email || !password) return res.status(400).json({ error: 'email and password are required' });\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin' });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n await issueRefreshToken(res, User, user.id);\n res.json({ message: 'Logged in' });\n};\n"},{"path":"src/api/auth/logout.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n if (!name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: __, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret() {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req, res) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, successRedirect());\n};\n"},{"path":"src/api/auth/apple/index.js","content":"import { randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport bcrypt from 'bcrypt';\nimport { HttpError } from 'express-file-cluster';\nimport { issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await bcrypt.hash(randomToken(), 10),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
1
+ {"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret() {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req, res) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, successRedirect());\n};\n"},{"path":"src/api/auth/apple/index.js","content":"import { randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
@@ -1 +1 @@
1
- {"name":"auth@google","files":[{"path":"src/api/auth/google/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req, res) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true,\n name: payload.name,\n });\n res.redirect(successRedirect());\n};\n"},{"path":"src/api/auth/google/index.js","content":"import { pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport bcrypt from 'bcrypt';\nimport { HttpError } from 'express-file-cluster';\nimport { issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await bcrypt.hash(randomToken(), 10),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
1
+ {"name":"auth@google","files":[{"path":"src/api/auth/google/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req, res) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true,\n name: payload.name,\n });\n res.redirect(successRedirect());\n};\n"},{"path":"src/api/auth/google/index.js","content":"import { pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
@@ -1 +1 @@
1
- {"name":"email-client","files":[{"path":"src/tasks/SendEmail.js","content":"import { defineTask } from 'express-file-cluster/tasks';\nimport nodemailer from 'nodemailer';\n\nconst transporter = nodemailer.createTransport({\n host: process.env.SMTP_HOST,\n port: Number(process.env.SMTP_PORT ?? 587),\n secure: Number(process.env.SMTP_PORT) === 465,\n auth: {\n user: process.env.SMTP_USER,\n pass: process.env.SMTP_PASS,\n },\n});\n\nexport default defineTask(async (payload) => {\n await transporter.sendMail({\n from: process.env.SMTP_FROM ?? process.env.SMTP_USER,\n to: payload.to,\n subject: payload.subject,\n html: payload.body,\n });\n});\n"}],"dependencies":{"nodemailer":"^6.9.0"},"devDependencies":{},"env":[{"key":"APP_URL","value":"http://localhost:3000","example":"http://localhost:3000"},{"key":"SMTP_HOST","value":"smtp.gmail.com","example":"smtp.gmail.com"},{"key":"SMTP_PORT","value":"465","example":"465"},{"key":"SMTP_USER","value":"","example":"your@email.com"},{"key":"SMTP_PASS","value":" # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords","example":"your_16_char_app_password # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords"},{"key":"SMTP_FROM","value":"noreply@example.com","example":"noreply@yourapp.com"}]}
1
+ {"name":"email-client","files":[{"path":"src/tasks/SendEmail.js","content":"import { defineTask } from 'express-file-cluster/tasks';\nimport nodemailer from 'nodemailer';\n\nconst transporter = nodemailer.createTransport({\n host: process.env.SMTP_HOST,\n port: Number(process.env.SMTP_PORT ?? 587),\n secure: Number(process.env.SMTP_PORT) === 465,\n auth: {\n user: process.env.SMTP_USER,\n pass: process.env.SMTP_PASS,\n },\n});\n\nexport default defineTask(async (payload) => {\n await transporter.sendMail({\n from: process.env.SMTP_FROM ?? process.env.SMTP_USER,\n to: payload.to,\n subject: payload.subject,\n html: payload.body,\n });\n});\n"}],"dependencies":{"nodemailer":"^10.2.1"},"devDependencies":{},"env":[{"key":"APP_URL","value":"http://localhost:3000","example":"http://localhost:3000"},{"key":"SMTP_HOST","value":"smtp.gmail.com","example":"smtp.gmail.com"},{"key":"SMTP_PORT","value":"465","example":"465"},{"key":"SMTP_USER","value":"","example":"your@email.com"},{"key":"SMTP_PASS","value":" # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords","example":"your_16_char_app_password # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords"},{"key":"SMTP_FROM","value":"noreply@example.com","example":"noreply@yourapp.com"}]}
@@ -1 +1 @@
1
- {"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.js","content":"import crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req, res) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findOne({ email });\n const admin = user ? null : await Admin.findOne({ email });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { resetToken, resetTokenExpiry });\n else if (admin) await Admin.update(admin.id, { resetToken, resetTokenExpiry });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.js","content":"import bcrypt from 'bcrypt';\nimport { revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { token, password } = req.body;\n if (!token || !password) return res.status(400).json({ error: 'token and password are required' });\n\n const user = await User.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await bcrypt.hash(password, 10);\n if (user) await User.update(user.id, { password: hashed, resetToken: '' });\n else if (admin) await Admin.update(admin.id, { password: hashed, resetToken: '' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.js","content":"import crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req, res) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findOne({ email });\n const admin = user ? null : await Admin.findOne({ email });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { resetToken, resetTokenExpiry });\n else if (admin) await Admin.update(admin.id, { resetToken, resetTokenExpiry });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.js","content":"import { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { token, password } = req.body;\n if (!token || !password) return res.status(400).json({ error: 'token and password are required' });\n\n const user = await User.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n if (user) await User.update(user.id, { password: hashed, resetToken: '' });\n else if (admin) await Admin.update(admin.id, { password: hashed, resetToken: '' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}