@parsrun/server 0.1.27 → 0.1.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/app.js.map +1 -1
- package/dist/context.d.ts +21 -1
- package/dist/context.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/middleware/index.d.ts +7 -771
- package/dist/middleware/index.js.map +1 -1
- package/dist/module-loader.js.map +1 -1
- package/dist/quota-enforcement-CN3z5bfc.d.ts +744 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/validation/index.js.map +1 -1
- package/package.json +25 -15
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hasan YILDIZ
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/app.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/app.ts","../src/context.ts"],"sourcesContent":["/**\n * @parsrun/server - App Factory\n * Create and configure Hono server instances\n */\n\nimport { Hono } from \"hono\";\nimport { createLogger } from \"@parsrun/core\";\nimport type {\n ServerConfig,\n ServerContextVariables,\n HonoApp,\n} from \"./context.js\";\nimport { generateRequestId } from \"./context.js\";\n\n/**\n * Extended server options\n */\nexport interface CreateServerOptions extends ServerConfig {\n /** Enable request logging */\n logging?: boolean;\n /** Enable request ID generation */\n requestId?: boolean;\n /** Base path for all routes */\n basePath?: string;\n /** Strict mode - trailing slashes matter */\n strict?: boolean;\n}\n\n/**\n * Create a new Pars server instance\n *\n * @example\n * ```typescript\n * const app = createServer({\n * database: db,\n * cors: { origin: '*' },\n * logging: true,\n * });\n *\n * app.get('/health', (c) => c.json({ status: 'ok' }));\n *\n * export default app;\n * ```\n */\nexport function createServer(options: CreateServerOptions): HonoApp {\n const app = new Hono<{ Variables: ServerContextVariables }>({\n strict: options.strict ?? false,\n });\n\n const logger = options.logger ?? createLogger({ name: \"pars-server\" });\n\n // Initialize context for all requests\n app.use(\"*\", async (c, next) => {\n // Set core context variables\n c.set(\"db\", options.database);\n c.set(\"config\", options);\n c.set(\"logger\", logger);\n c.set(\"enabledModules\", new Set<string>());\n c.set(\"cookiePrefix\", options.cookiePrefix);\n c.set(\"custom\", options.custom ?? {});\n\n // Generate request ID if enabled\n if (options.requestId !== false) {\n const requestId = c.req.header(\"x-request-id\") ?? generateRequestId();\n c.set(\"requestId\", requestId);\n c.header(\"x-request-id\", requestId);\n }\n\n await next();\n });\n\n return app;\n}\n\n/**\n * Create a router (sub-app) with shared context\n *\n * @example\n * ```typescript\n * const usersRouter = createRouter();\n *\n * usersRouter.get('/', async (c) => {\n * const users = await getUsers(c.get('db'));\n * return c.json(success(users));\n * });\n *\n * usersRouter.post('/', async (c) => {\n * // ...\n * });\n *\n * app.route('/api/users', usersRouter);\n * ```\n */\nexport function createRouter(): HonoApp {\n return new Hono<{ Variables: ServerContextVariables }>();\n}\n\n/**\n * Create a versioned API router\n *\n * @example\n * ```typescript\n * const v1 = createVersionedRouter('v1');\n * v1.get('/users', handler);\n *\n * app.route('/api', v1); // Results in /api/v1/users\n * ```\n */\nexport function createVersionedRouter(version: string): HonoApp {\n const router = new Hono<{ Variables: ServerContextVariables }>();\n\n // Add version to all routes\n const versionedRouter = new Hono<{ Variables: ServerContextVariables }>();\n versionedRouter.route(`/${version}`, router);\n\n return versionedRouter;\n}\n\n/**\n * Create a module router with prefix\n *\n * @example\n * ```typescript\n * const inventoryModule = createModuleRouter('inventory', {\n * routes: (router) => {\n * router.get('/items', listItems);\n * router.post('/items', createItem);\n * },\n * });\n *\n * app.route('/api', inventoryModule);\n * ```\n */\nexport function createModuleRouter(\n moduleName: string,\n options: {\n routes: (router: HonoApp) => void;\n middleware?: Array<(c: import(\"hono\").Context, next: () => Promise<void>) => Promise<Response | void>>;\n }\n): HonoApp {\n const moduleRouter = new Hono<{ Variables: ServerContextVariables }>();\n\n // Apply module-specific middleware\n if (options.middleware) {\n for (const mw of options.middleware) {\n moduleRouter.use(\"*\", mw);\n }\n }\n\n // Register routes\n options.routes(moduleRouter);\n\n // Wrap in module path\n const wrappedRouter = new Hono<{ Variables: ServerContextVariables }>();\n wrappedRouter.route(`/${moduleName}`, moduleRouter);\n\n return wrappedRouter;\n}\n","/**\n * @parsrun/server - Server Context\n * Type definitions for server context and configuration\n */\n\nimport type { Logger } from \"@parsrun/core\";\n\n/**\n * Database adapter interface\n * Implement this for your database (Drizzle, Prisma, etc.)\n */\nexport interface DatabaseAdapter {\n /** Execute raw SQL query */\n execute(sql: string): Promise<unknown>;\n /** Check connection */\n ping?(): Promise<boolean>;\n}\n\n/**\n * Module manifest for registering modules\n */\nexport interface ModuleManifest {\n /** Unique module name */\n name: string;\n /** Module version */\n version: string;\n /** Module description */\n description: string;\n /** Required permissions for this module */\n permissions: Record<string, string[]>;\n /** Module dependencies (other module names) */\n dependencies?: string[];\n /** Register routes for this module */\n registerRoutes: (app: HonoApp) => void;\n /** Called when module is enabled */\n onEnable?: () => Promise<void>;\n /** Called when module is disabled */\n onDisable?: () => Promise<void>;\n}\n\n/**\n * Server configuration\n */\nexport interface ServerConfig {\n /** Database adapter */\n database: DatabaseAdapter;\n /** CORS configuration */\n cors?: CorsConfig;\n /** Base path for API */\n basePath?: string;\n /** Cookie prefix for all cookies */\n cookiePrefix?: string;\n /** Logger instance */\n logger?: Logger;\n /** Custom context data */\n custom?: Record<string, unknown>;\n}\n\n/**\n * CORS configuration\n */\nexport interface CorsConfig {\n /** Allowed origins */\n origin: string | string[] | ((origin: string) => boolean);\n /** Allow credentials */\n credentials?: boolean;\n /** Allowed methods */\n methods?: string[];\n /** Allowed headers */\n allowedHeaders?: string[];\n /** Exposed headers */\n exposedHeaders?: string[];\n /** Max age in seconds */\n maxAge?: number;\n}\n\n/**\n * User information in context\n */\nexport interface ContextUser {\n id: string;\n email: string | undefined;\n tenantId: string | undefined;\n role: string | undefined;\n permissions: string[];\n}\n\n/**\n * Tenant information in context\n */\nexport interface ContextTenant {\n id: string;\n slug: string | undefined;\n name: string | undefined;\n status: string;\n}\n\n/**\n * Server context variables\n * Available in Hono context via c.get()\n */\nexport interface ServerContextVariables {\n /** Database adapter */\n db: DatabaseAdapter;\n /** Server configuration */\n config: ServerConfig;\n /** Enabled modules set */\n enabledModules: Set<string>;\n /** Current user (if authenticated) */\n user: ContextUser | undefined;\n /** Current tenant (if resolved) */\n tenant: ContextTenant | undefined;\n /** Request logger */\n logger: Logger;\n /** Request ID */\n requestId: string;\n /** Cookie prefix */\n cookiePrefix: string | undefined;\n /** Custom context data */\n custom: Record<string, unknown>;\n}\n\n/**\n * Hono app type with server context\n */\nexport type HonoApp = import(\"hono\").Hono<{ Variables: ServerContextVariables }>;\n\n/**\n * Hono context type with server context\n */\nexport type HonoContext = import(\"hono\").Context<{ Variables: ServerContextVariables }>;\n\n/**\n * Middleware next function\n */\nexport type HonoNext = () => Promise<void>;\n\n/**\n * Middleware function type\n */\nexport type Middleware = (c: HonoContext, next: HonoNext) => Promise<Response | void>;\n\n/**\n * Route handler function type\n */\nexport type RouteHandler = (c: HonoContext) => Promise<Response> | Response;\n\n/**\n * Permission check input\n */\nexport interface PermissionCheck {\n /** Resource name (e.g., \"users\", \"items\") */\n resource: string;\n /** Action name (e.g., \"read\", \"create\", \"update\", \"delete\") */\n action: string;\n /** Permission scope */\n scope?: \"tenant\" | \"global\" | \"own\";\n}\n\n/**\n * Permission definition\n */\nexport interface PermissionDefinition {\n /** Permission name (e.g., \"users:read\") */\n name: string;\n /** Resource part */\n resource: string;\n /** Action part */\n action: string;\n /** Description */\n description?: string;\n /** Scope */\n scope?: \"tenant\" | \"global\" | \"own\";\n}\n\n/**\n * Role definition\n */\nexport interface RoleDefinition {\n /** Role name */\n name: string;\n /** Display name */\n displayName?: string;\n /** Description */\n description?: string;\n /** Permissions assigned to this role */\n permissions: string[];\n /** Is this a system role */\n isSystem?: boolean;\n}\n\n/**\n * Standard API response structure\n */\nexport interface ApiResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: {\n code: string;\n message: string;\n details?: Record<string, unknown> | undefined;\n };\n meta?: {\n page?: number | undefined;\n limit?: number | undefined;\n total?: number | undefined;\n requestId?: string | undefined;\n } | undefined;\n}\n\n/**\n * Create a success response\n */\nexport function success<T>(data: T, meta?: ApiResponse[\"meta\"]): ApiResponse<T> {\n return {\n success: true,\n data,\n meta: meta ?? undefined,\n };\n}\n\n/**\n * Create an error response\n */\nexport function error(\n code: string,\n message: string,\n details?: Record<string, unknown>\n): ApiResponse<never> {\n return {\n success: false,\n error: { code, message, details: details ?? undefined },\n };\n}\n\n/**\n * Generate a request ID\n */\nexport function generateRequestId(): string {\n return crypto.randomUUID();\n}\n"],"mappings":";AAKA,SAAS,YAAY;AACrB,SAAS,oBAAoB;;;ACwOtB,SAAS,oBAA4B;AAC1C,SAAO,OAAO,WAAW;AAC3B;;;ADpMO,SAAS,aAAa,SAAuC;AAClE,QAAM,MAAM,IAAI,KAA4C;AAAA,IAC1D,QAAQ,QAAQ,UAAU;AAAA,EAC5B,CAAC;AAED,QAAM,SAAS,QAAQ,UAAU,aAAa,EAAE,MAAM,cAAc,CAAC;AAGrE,MAAI,IAAI,KAAK,OAAO,GAAG,SAAS;AAE9B,MAAE,IAAI,MAAM,QAAQ,QAAQ;AAC5B,MAAE,IAAI,UAAU,OAAO;AACvB,MAAE,IAAI,UAAU,MAAM;AACtB,MAAE,IAAI,kBAAkB,oBAAI,IAAY,CAAC;AACzC,MAAE,IAAI,gBAAgB,QAAQ,YAAY;AAC1C,MAAE,IAAI,UAAU,QAAQ,UAAU,CAAC,CAAC;AAGpC,QAAI,QAAQ,cAAc,OAAO;AAC/B,YAAM,YAAY,EAAE,IAAI,OAAO,cAAc,KAAK,kBAAkB;AACpE,QAAE,IAAI,aAAa,SAAS;AAC5B,QAAE,OAAO,gBAAgB,SAAS;AAAA,IACpC;AAEA,UAAM,KAAK;AAAA,EACb,CAAC;AAED,SAAO;AACT;AAqBO,SAAS,eAAwB;AACtC,SAAO,IAAI,KAA4C;AACzD;AAaO,SAAS,sBAAsB,SAA0B;AAC9D,QAAM,SAAS,IAAI,KAA4C;AAG/D,QAAM,kBAAkB,IAAI,KAA4C;AACxE,kBAAgB,MAAM,IAAI,OAAO,IAAI,MAAM;AAE3C,SAAO;AACT;AAiBO,SAAS,mBACd,YACA,SAIS;AACT,QAAM,eAAe,IAAI,KAA4C;AAGrE,MAAI,QAAQ,YAAY;AACtB,eAAW,MAAM,QAAQ,YAAY;AACnC,mBAAa,IAAI,KAAK,EAAE;AAAA,IAC1B;AAAA,EACF;AAGA,UAAQ,OAAO,YAAY;AAG3B,QAAM,gBAAgB,IAAI,KAA4C;AACtE,gBAAc,MAAM,IAAI,UAAU,IAAI,YAAY;AAElD,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/app.ts","../src/context.ts"],"sourcesContent":["/**\n * @parsrun/server - App Factory\n * Create and configure Hono server instances\n */\n\nimport { Hono } from \"hono\";\nimport { createLogger } from \"@parsrun/core\";\nimport type {\n ServerConfig,\n ServerContextVariables,\n HonoApp,\n} from \"./context.js\";\nimport { generateRequestId } from \"./context.js\";\n\n/**\n * Extended server options\n */\nexport interface CreateServerOptions extends ServerConfig {\n /** Enable request logging */\n logging?: boolean;\n /** Enable request ID generation */\n requestId?: boolean;\n /** Base path for all routes */\n basePath?: string;\n /** Strict mode - trailing slashes matter */\n strict?: boolean;\n}\n\n/**\n * Create a new Pars server instance\n *\n * @example\n * ```typescript\n * const app = createServer({\n * database: db,\n * cors: { origin: '*' },\n * logging: true,\n * });\n *\n * app.get('/health', (c) => c.json({ status: 'ok' }));\n *\n * export default app;\n * ```\n */\nexport function createServer(options: CreateServerOptions): HonoApp {\n const app = new Hono<{ Variables: ServerContextVariables }>({\n strict: options.strict ?? false,\n });\n\n const logger = options.logger ?? createLogger({ name: \"pars-server\" });\n\n // Initialize context for all requests\n app.use(\"*\", async (c, next) => {\n // Set core context variables\n c.set(\"db\", options.database);\n c.set(\"config\", options);\n c.set(\"logger\", logger);\n c.set(\"enabledModules\", new Set<string>());\n c.set(\"cookiePrefix\", options.cookiePrefix);\n c.set(\"custom\", options.custom ?? {});\n\n // Generate request ID if enabled\n if (options.requestId !== false) {\n const requestId = c.req.header(\"x-request-id\") ?? generateRequestId();\n c.set(\"requestId\", requestId);\n c.header(\"x-request-id\", requestId);\n }\n\n await next();\n });\n\n return app;\n}\n\n/**\n * Create a router (sub-app) with shared context\n *\n * @example\n * ```typescript\n * const usersRouter = createRouter();\n *\n * usersRouter.get('/', async (c) => {\n * const users = await getUsers(c.get('db'));\n * return c.json(success(users));\n * });\n *\n * usersRouter.post('/', async (c) => {\n * // ...\n * });\n *\n * app.route('/api/users', usersRouter);\n * ```\n */\nexport function createRouter(): HonoApp {\n return new Hono<{ Variables: ServerContextVariables }>();\n}\n\n/**\n * Create a versioned API router\n *\n * @example\n * ```typescript\n * const v1 = createVersionedRouter('v1');\n * v1.get('/users', handler);\n *\n * app.route('/api', v1); // Results in /api/v1/users\n * ```\n */\nexport function createVersionedRouter(version: string): HonoApp {\n const router = new Hono<{ Variables: ServerContextVariables }>();\n\n // Add version to all routes\n const versionedRouter = new Hono<{ Variables: ServerContextVariables }>();\n versionedRouter.route(`/${version}`, router);\n\n return versionedRouter;\n}\n\n/**\n * Create a module router with prefix\n *\n * @example\n * ```typescript\n * const inventoryModule = createModuleRouter('inventory', {\n * routes: (router) => {\n * router.get('/items', listItems);\n * router.post('/items', createItem);\n * },\n * });\n *\n * app.route('/api', inventoryModule);\n * ```\n */\nexport function createModuleRouter(\n moduleName: string,\n options: {\n routes: (router: HonoApp) => void;\n middleware?: Array<(c: import(\"hono\").Context, next: () => Promise<void>) => Promise<Response | void>>;\n }\n): HonoApp {\n const moduleRouter = new Hono<{ Variables: ServerContextVariables }>();\n\n // Apply module-specific middleware\n if (options.middleware) {\n for (const mw of options.middleware) {\n moduleRouter.use(\"*\", mw);\n }\n }\n\n // Register routes\n options.routes(moduleRouter);\n\n // Wrap in module path\n const wrappedRouter = new Hono<{ Variables: ServerContextVariables }>();\n wrappedRouter.route(`/${moduleName}`, moduleRouter);\n\n return wrappedRouter;\n}\n","/**\n * @parsrun/server - Server Context\n * Type definitions for server context and configuration\n */\n\nimport type { Logger } from \"@parsrun/core\";\n\n/**\n * Database adapter interface\n * Implement this for your database (Drizzle, Prisma, etc.)\n */\nexport interface DatabaseAdapter {\n /** Execute raw SQL query */\n execute(sql: string): Promise<unknown>;\n /** Check connection */\n ping?(): Promise<boolean>;\n}\n\n/**\n * Module manifest for registering modules\n */\nexport interface ModuleManifest {\n /** Unique module name */\n name: string;\n /** Module version */\n version: string;\n /** Module description */\n description: string;\n /** Required permissions for this module */\n permissions: Record<string, string[]>;\n /** Module dependencies (other module names) */\n dependencies?: string[];\n /** Register routes for this module */\n registerRoutes: (app: HonoApp) => void;\n /** Called when module is enabled */\n onEnable?: () => Promise<void>;\n /** Called when module is disabled */\n onDisable?: () => Promise<void>;\n}\n\n/**\n * Server configuration\n */\nexport interface ServerConfig {\n /** Database adapter */\n database: DatabaseAdapter;\n /** CORS configuration */\n cors?: CorsConfig;\n /** Base path for API */\n basePath?: string;\n /** Cookie prefix for all cookies */\n cookiePrefix?: string;\n /** Logger instance */\n logger?: Logger;\n /** Custom context data */\n custom?: Record<string, unknown>;\n}\n\n/**\n * CORS configuration\n */\nexport interface CorsConfig {\n /** Allowed origins */\n origin: string | string[] | ((origin: string) => boolean);\n /** Allow credentials */\n credentials?: boolean;\n /** Allowed methods */\n methods?: string[];\n /** Allowed headers */\n allowedHeaders?: string[];\n /** Exposed headers */\n exposedHeaders?: string[];\n /** Max age in seconds */\n maxAge?: number;\n}\n\n/**\n * User information in context\n */\nexport interface ContextUser {\n id: string;\n email: string | undefined;\n tenantId: string | undefined;\n role: string | undefined;\n permissions: string[];\n}\n\n/**\n * Tenant information in context\n */\nexport interface ContextTenant {\n id: string;\n slug: string | undefined;\n name: string | undefined;\n status: string;\n}\n\n/**\n * Server context variables\n * Available in Hono context via c.get()\n */\n/**\n * W3C Trace Context - Parsed traceparent header\n * Format: {version}-{trace-id}-{parent-id}-{trace-flags}\n */\nexport interface TraceContext {\n /** Trace version (currently \"00\") */\n version: string;\n /** 32 hex character trace ID */\n traceId: string;\n /** 16 hex character parent span ID */\n parentId: string;\n /** Trace flags (sampled, etc.) */\n traceFlags: number;\n}\n\nexport interface ServerContextVariables {\n /** Database adapter */\n db: DatabaseAdapter;\n /** Server configuration */\n config: ServerConfig;\n /** Enabled modules set */\n enabledModules: Set<string>;\n /** Current user (if authenticated) */\n user: ContextUser | undefined;\n /** Current tenant (if resolved) */\n tenant: ContextTenant | undefined;\n /** Request logger */\n logger: Logger;\n /** Request ID */\n requestId: string;\n /** Cookie prefix */\n cookiePrefix: string | undefined;\n /** Custom context data */\n custom: Record<string, unknown>;\n /** W3C trace context (if propagation is enabled) */\n traceContext?: TraceContext;\n /** Current span ID for this request */\n spanId?: string;\n /** Tracestate header value (for forwarding) */\n traceState?: string;\n}\n\n/**\n * Hono app type with server context\n */\nexport type HonoApp = import(\"hono\").Hono<{ Variables: ServerContextVariables }>;\n\n/**\n * Hono context type with server context\n */\nexport type HonoContext = import(\"hono\").Context<{ Variables: ServerContextVariables }>;\n\n/**\n * Middleware next function\n */\nexport type HonoNext = () => Promise<void>;\n\n/**\n * Middleware function type\n */\nexport type Middleware = (c: HonoContext, next: HonoNext) => Promise<Response | void>;\n\n/**\n * Route handler function type\n */\nexport type RouteHandler = (c: HonoContext) => Promise<Response> | Response;\n\n/**\n * Permission check input\n */\nexport interface PermissionCheck {\n /** Resource name (e.g., \"users\", \"items\") */\n resource: string;\n /** Action name (e.g., \"read\", \"create\", \"update\", \"delete\") */\n action: string;\n /** Permission scope */\n scope?: \"tenant\" | \"global\" | \"own\";\n}\n\n/**\n * Permission definition\n */\nexport interface PermissionDefinition {\n /** Permission name (e.g., \"users:read\") */\n name: string;\n /** Resource part */\n resource: string;\n /** Action part */\n action: string;\n /** Description */\n description?: string;\n /** Scope */\n scope?: \"tenant\" | \"global\" | \"own\";\n}\n\n/**\n * Role definition\n */\nexport interface RoleDefinition {\n /** Role name */\n name: string;\n /** Display name */\n displayName?: string;\n /** Description */\n description?: string;\n /** Permissions assigned to this role */\n permissions: string[];\n /** Is this a system role */\n isSystem?: boolean;\n}\n\n/**\n * Standard API response structure\n */\nexport interface ApiResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: {\n code: string;\n message: string;\n details?: Record<string, unknown> | undefined;\n };\n meta?: {\n page?: number | undefined;\n limit?: number | undefined;\n total?: number | undefined;\n requestId?: string | undefined;\n } | undefined;\n}\n\n/**\n * Create a success response\n */\nexport function success<T>(data: T, meta?: ApiResponse[\"meta\"]): ApiResponse<T> {\n return {\n success: true,\n data,\n meta: meta ?? undefined,\n };\n}\n\n/**\n * Create an error response\n */\nexport function error(\n code: string,\n message: string,\n details?: Record<string, unknown>\n): ApiResponse<never> {\n return {\n success: false,\n error: { code, message, details: details ?? undefined },\n };\n}\n\n/**\n * Generate a request ID\n */\nexport function generateRequestId(): string {\n return crypto.randomUUID();\n}\n"],"mappings":";AAKA,SAAS,YAAY;AACrB,SAAS,oBAAoB;;;AC6PtB,SAAS,oBAA4B;AAC1C,SAAO,OAAO,WAAW;AAC3B;;;ADzNO,SAAS,aAAa,SAAuC;AAClE,QAAM,MAAM,IAAI,KAA4C;AAAA,IAC1D,QAAQ,QAAQ,UAAU;AAAA,EAC5B,CAAC;AAED,QAAM,SAAS,QAAQ,UAAU,aAAa,EAAE,MAAM,cAAc,CAAC;AAGrE,MAAI,IAAI,KAAK,OAAO,GAAG,SAAS;AAE9B,MAAE,IAAI,MAAM,QAAQ,QAAQ;AAC5B,MAAE,IAAI,UAAU,OAAO;AACvB,MAAE,IAAI,UAAU,MAAM;AACtB,MAAE,IAAI,kBAAkB,oBAAI,IAAY,CAAC;AACzC,MAAE,IAAI,gBAAgB,QAAQ,YAAY;AAC1C,MAAE,IAAI,UAAU,QAAQ,UAAU,CAAC,CAAC;AAGpC,QAAI,QAAQ,cAAc,OAAO;AAC/B,YAAM,YAAY,EAAE,IAAI,OAAO,cAAc,KAAK,kBAAkB;AACpE,QAAE,IAAI,aAAa,SAAS;AAC5B,QAAE,OAAO,gBAAgB,SAAS;AAAA,IACpC;AAEA,UAAM,KAAK;AAAA,EACb,CAAC;AAED,SAAO;AACT;AAqBO,SAAS,eAAwB;AACtC,SAAO,IAAI,KAA4C;AACzD;AAaO,SAAS,sBAAsB,SAA0B;AAC9D,QAAM,SAAS,IAAI,KAA4C;AAG/D,QAAM,kBAAkB,IAAI,KAA4C;AACxE,kBAAgB,MAAM,IAAI,OAAO,IAAI,MAAM;AAE3C,SAAO;AACT;AAiBO,SAAS,mBACd,YACA,SAIS;AACT,QAAM,eAAe,IAAI,KAA4C;AAGrE,MAAI,QAAQ,YAAY;AACtB,eAAW,MAAM,QAAQ,YAAY;AACnC,mBAAa,IAAI,KAAK,EAAE;AAAA,IAC1B;AAAA,EACF;AAGA,UAAQ,OAAO,YAAY;AAG3B,QAAM,gBAAgB,IAAI,KAA4C;AACtE,gBAAc,MAAM,IAAI,UAAU,IAAI,YAAY;AAElD,SAAO;AACT;","names":[]}
|
package/dist/context.d.ts
CHANGED
|
@@ -89,6 +89,20 @@ interface ContextTenant {
|
|
|
89
89
|
* Server context variables
|
|
90
90
|
* Available in Hono context via c.get()
|
|
91
91
|
*/
|
|
92
|
+
/**
|
|
93
|
+
* W3C Trace Context - Parsed traceparent header
|
|
94
|
+
* Format: {version}-{trace-id}-{parent-id}-{trace-flags}
|
|
95
|
+
*/
|
|
96
|
+
interface TraceContext {
|
|
97
|
+
/** Trace version (currently "00") */
|
|
98
|
+
version: string;
|
|
99
|
+
/** 32 hex character trace ID */
|
|
100
|
+
traceId: string;
|
|
101
|
+
/** 16 hex character parent span ID */
|
|
102
|
+
parentId: string;
|
|
103
|
+
/** Trace flags (sampled, etc.) */
|
|
104
|
+
traceFlags: number;
|
|
105
|
+
}
|
|
92
106
|
interface ServerContextVariables {
|
|
93
107
|
/** Database adapter */
|
|
94
108
|
db: DatabaseAdapter;
|
|
@@ -108,6 +122,12 @@ interface ServerContextVariables {
|
|
|
108
122
|
cookiePrefix: string | undefined;
|
|
109
123
|
/** Custom context data */
|
|
110
124
|
custom: Record<string, unknown>;
|
|
125
|
+
/** W3C trace context (if propagation is enabled) */
|
|
126
|
+
traceContext?: TraceContext;
|
|
127
|
+
/** Current span ID for this request */
|
|
128
|
+
spanId?: string;
|
|
129
|
+
/** Tracestate header value (for forwarding) */
|
|
130
|
+
traceState?: string;
|
|
111
131
|
}
|
|
112
132
|
/**
|
|
113
133
|
* Hono app type with server context
|
|
@@ -205,4 +225,4 @@ declare function error(code: string, message: string, details?: Record<string, u
|
|
|
205
225
|
*/
|
|
206
226
|
declare function generateRequestId(): string;
|
|
207
227
|
|
|
208
|
-
export { type ApiResponse, type ContextTenant, type ContextUser, type CorsConfig, type DatabaseAdapter, type HonoApp, type HonoContext, type HonoNext, type Middleware, type ModuleManifest, type PermissionCheck, type PermissionDefinition, type RoleDefinition, type RouteHandler, type ServerConfig, type ServerContextVariables, error, generateRequestId, success };
|
|
228
|
+
export { type ApiResponse, type ContextTenant, type ContextUser, type CorsConfig, type DatabaseAdapter, type HonoApp, type HonoContext, type HonoNext, type Middleware, type ModuleManifest, type PermissionCheck, type PermissionDefinition, type RoleDefinition, type RouteHandler, type ServerConfig, type ServerContextVariables, type TraceContext, error, generateRequestId, success };
|
package/dist/context.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context.ts"],"sourcesContent":["/**\n * @parsrun/server - Server Context\n * Type definitions for server context and configuration\n */\n\nimport type { Logger } from \"@parsrun/core\";\n\n/**\n * Database adapter interface\n * Implement this for your database (Drizzle, Prisma, etc.)\n */\nexport interface DatabaseAdapter {\n /** Execute raw SQL query */\n execute(sql: string): Promise<unknown>;\n /** Check connection */\n ping?(): Promise<boolean>;\n}\n\n/**\n * Module manifest for registering modules\n */\nexport interface ModuleManifest {\n /** Unique module name */\n name: string;\n /** Module version */\n version: string;\n /** Module description */\n description: string;\n /** Required permissions for this module */\n permissions: Record<string, string[]>;\n /** Module dependencies (other module names) */\n dependencies?: string[];\n /** Register routes for this module */\n registerRoutes: (app: HonoApp) => void;\n /** Called when module is enabled */\n onEnable?: () => Promise<void>;\n /** Called when module is disabled */\n onDisable?: () => Promise<void>;\n}\n\n/**\n * Server configuration\n */\nexport interface ServerConfig {\n /** Database adapter */\n database: DatabaseAdapter;\n /** CORS configuration */\n cors?: CorsConfig;\n /** Base path for API */\n basePath?: string;\n /** Cookie prefix for all cookies */\n cookiePrefix?: string;\n /** Logger instance */\n logger?: Logger;\n /** Custom context data */\n custom?: Record<string, unknown>;\n}\n\n/**\n * CORS configuration\n */\nexport interface CorsConfig {\n /** Allowed origins */\n origin: string | string[] | ((origin: string) => boolean);\n /** Allow credentials */\n credentials?: boolean;\n /** Allowed methods */\n methods?: string[];\n /** Allowed headers */\n allowedHeaders?: string[];\n /** Exposed headers */\n exposedHeaders?: string[];\n /** Max age in seconds */\n maxAge?: number;\n}\n\n/**\n * User information in context\n */\nexport interface ContextUser {\n id: string;\n email: string | undefined;\n tenantId: string | undefined;\n role: string | undefined;\n permissions: string[];\n}\n\n/**\n * Tenant information in context\n */\nexport interface ContextTenant {\n id: string;\n slug: string | undefined;\n name: string | undefined;\n status: string;\n}\n\n/**\n * Server context variables\n * Available in Hono context via c.get()\n */\nexport interface ServerContextVariables {\n /** Database adapter */\n db: DatabaseAdapter;\n /** Server configuration */\n config: ServerConfig;\n /** Enabled modules set */\n enabledModules: Set<string>;\n /** Current user (if authenticated) */\n user: ContextUser | undefined;\n /** Current tenant (if resolved) */\n tenant: ContextTenant | undefined;\n /** Request logger */\n logger: Logger;\n /** Request ID */\n requestId: string;\n /** Cookie prefix */\n cookiePrefix: string | undefined;\n /** Custom context data */\n custom: Record<string, unknown>;\n}\n\n/**\n * Hono app type with server context\n */\nexport type HonoApp = import(\"hono\").Hono<{ Variables: ServerContextVariables }>;\n\n/**\n * Hono context type with server context\n */\nexport type HonoContext = import(\"hono\").Context<{ Variables: ServerContextVariables }>;\n\n/**\n * Middleware next function\n */\nexport type HonoNext = () => Promise<void>;\n\n/**\n * Middleware function type\n */\nexport type Middleware = (c: HonoContext, next: HonoNext) => Promise<Response | void>;\n\n/**\n * Route handler function type\n */\nexport type RouteHandler = (c: HonoContext) => Promise<Response> | Response;\n\n/**\n * Permission check input\n */\nexport interface PermissionCheck {\n /** Resource name (e.g., \"users\", \"items\") */\n resource: string;\n /** Action name (e.g., \"read\", \"create\", \"update\", \"delete\") */\n action: string;\n /** Permission scope */\n scope?: \"tenant\" | \"global\" | \"own\";\n}\n\n/**\n * Permission definition\n */\nexport interface PermissionDefinition {\n /** Permission name (e.g., \"users:read\") */\n name: string;\n /** Resource part */\n resource: string;\n /** Action part */\n action: string;\n /** Description */\n description?: string;\n /** Scope */\n scope?: \"tenant\" | \"global\" | \"own\";\n}\n\n/**\n * Role definition\n */\nexport interface RoleDefinition {\n /** Role name */\n name: string;\n /** Display name */\n displayName?: string;\n /** Description */\n description?: string;\n /** Permissions assigned to this role */\n permissions: string[];\n /** Is this a system role */\n isSystem?: boolean;\n}\n\n/**\n * Standard API response structure\n */\nexport interface ApiResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: {\n code: string;\n message: string;\n details?: Record<string, unknown> | undefined;\n };\n meta?: {\n page?: number | undefined;\n limit?: number | undefined;\n total?: number | undefined;\n requestId?: string | undefined;\n } | undefined;\n}\n\n/**\n * Create a success response\n */\nexport function success<T>(data: T, meta?: ApiResponse[\"meta\"]): ApiResponse<T> {\n return {\n success: true,\n data,\n meta: meta ?? undefined,\n };\n}\n\n/**\n * Create an error response\n */\nexport function error(\n code: string,\n message: string,\n details?: Record<string, unknown>\n): ApiResponse<never> {\n return {\n success: false,\n error: { code, message, details: details ?? undefined },\n };\n}\n\n/**\n * Generate a request ID\n */\nexport function generateRequestId(): string {\n return crypto.randomUUID();\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../src/context.ts"],"sourcesContent":["/**\n * @parsrun/server - Server Context\n * Type definitions for server context and configuration\n */\n\nimport type { Logger } from \"@parsrun/core\";\n\n/**\n * Database adapter interface\n * Implement this for your database (Drizzle, Prisma, etc.)\n */\nexport interface DatabaseAdapter {\n /** Execute raw SQL query */\n execute(sql: string): Promise<unknown>;\n /** Check connection */\n ping?(): Promise<boolean>;\n}\n\n/**\n * Module manifest for registering modules\n */\nexport interface ModuleManifest {\n /** Unique module name */\n name: string;\n /** Module version */\n version: string;\n /** Module description */\n description: string;\n /** Required permissions for this module */\n permissions: Record<string, string[]>;\n /** Module dependencies (other module names) */\n dependencies?: string[];\n /** Register routes for this module */\n registerRoutes: (app: HonoApp) => void;\n /** Called when module is enabled */\n onEnable?: () => Promise<void>;\n /** Called when module is disabled */\n onDisable?: () => Promise<void>;\n}\n\n/**\n * Server configuration\n */\nexport interface ServerConfig {\n /** Database adapter */\n database: DatabaseAdapter;\n /** CORS configuration */\n cors?: CorsConfig;\n /** Base path for API */\n basePath?: string;\n /** Cookie prefix for all cookies */\n cookiePrefix?: string;\n /** Logger instance */\n logger?: Logger;\n /** Custom context data */\n custom?: Record<string, unknown>;\n}\n\n/**\n * CORS configuration\n */\nexport interface CorsConfig {\n /** Allowed origins */\n origin: string | string[] | ((origin: string) => boolean);\n /** Allow credentials */\n credentials?: boolean;\n /** Allowed methods */\n methods?: string[];\n /** Allowed headers */\n allowedHeaders?: string[];\n /** Exposed headers */\n exposedHeaders?: string[];\n /** Max age in seconds */\n maxAge?: number;\n}\n\n/**\n * User information in context\n */\nexport interface ContextUser {\n id: string;\n email: string | undefined;\n tenantId: string | undefined;\n role: string | undefined;\n permissions: string[];\n}\n\n/**\n * Tenant information in context\n */\nexport interface ContextTenant {\n id: string;\n slug: string | undefined;\n name: string | undefined;\n status: string;\n}\n\n/**\n * Server context variables\n * Available in Hono context via c.get()\n */\n/**\n * W3C Trace Context - Parsed traceparent header\n * Format: {version}-{trace-id}-{parent-id}-{trace-flags}\n */\nexport interface TraceContext {\n /** Trace version (currently \"00\") */\n version: string;\n /** 32 hex character trace ID */\n traceId: string;\n /** 16 hex character parent span ID */\n parentId: string;\n /** Trace flags (sampled, etc.) */\n traceFlags: number;\n}\n\nexport interface ServerContextVariables {\n /** Database adapter */\n db: DatabaseAdapter;\n /** Server configuration */\n config: ServerConfig;\n /** Enabled modules set */\n enabledModules: Set<string>;\n /** Current user (if authenticated) */\n user: ContextUser | undefined;\n /** Current tenant (if resolved) */\n tenant: ContextTenant | undefined;\n /** Request logger */\n logger: Logger;\n /** Request ID */\n requestId: string;\n /** Cookie prefix */\n cookiePrefix: string | undefined;\n /** Custom context data */\n custom: Record<string, unknown>;\n /** W3C trace context (if propagation is enabled) */\n traceContext?: TraceContext;\n /** Current span ID for this request */\n spanId?: string;\n /** Tracestate header value (for forwarding) */\n traceState?: string;\n}\n\n/**\n * Hono app type with server context\n */\nexport type HonoApp = import(\"hono\").Hono<{ Variables: ServerContextVariables }>;\n\n/**\n * Hono context type with server context\n */\nexport type HonoContext = import(\"hono\").Context<{ Variables: ServerContextVariables }>;\n\n/**\n * Middleware next function\n */\nexport type HonoNext = () => Promise<void>;\n\n/**\n * Middleware function type\n */\nexport type Middleware = (c: HonoContext, next: HonoNext) => Promise<Response | void>;\n\n/**\n * Route handler function type\n */\nexport type RouteHandler = (c: HonoContext) => Promise<Response> | Response;\n\n/**\n * Permission check input\n */\nexport interface PermissionCheck {\n /** Resource name (e.g., \"users\", \"items\") */\n resource: string;\n /** Action name (e.g., \"read\", \"create\", \"update\", \"delete\") */\n action: string;\n /** Permission scope */\n scope?: \"tenant\" | \"global\" | \"own\";\n}\n\n/**\n * Permission definition\n */\nexport interface PermissionDefinition {\n /** Permission name (e.g., \"users:read\") */\n name: string;\n /** Resource part */\n resource: string;\n /** Action part */\n action: string;\n /** Description */\n description?: string;\n /** Scope */\n scope?: \"tenant\" | \"global\" | \"own\";\n}\n\n/**\n * Role definition\n */\nexport interface RoleDefinition {\n /** Role name */\n name: string;\n /** Display name */\n displayName?: string;\n /** Description */\n description?: string;\n /** Permissions assigned to this role */\n permissions: string[];\n /** Is this a system role */\n isSystem?: boolean;\n}\n\n/**\n * Standard API response structure\n */\nexport interface ApiResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: {\n code: string;\n message: string;\n details?: Record<string, unknown> | undefined;\n };\n meta?: {\n page?: number | undefined;\n limit?: number | undefined;\n total?: number | undefined;\n requestId?: string | undefined;\n } | undefined;\n}\n\n/**\n * Create a success response\n */\nexport function success<T>(data: T, meta?: ApiResponse[\"meta\"]): ApiResponse<T> {\n return {\n success: true,\n data,\n meta: meta ?? undefined,\n };\n}\n\n/**\n * Create an error response\n */\nexport function error(\n code: string,\n message: string,\n details?: Record<string, unknown>\n): ApiResponse<never> {\n return {\n success: false,\n error: { code, message, details: details ?? undefined },\n };\n}\n\n/**\n * Generate a request ID\n */\nexport function generateRequestId(): string {\n return crypto.randomUUID();\n}\n"],"mappings":";AA0OO,SAAS,QAAW,MAAS,MAA4C;AAC9E,SAAO;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA,MAAM,QAAQ;AAAA,EAChB;AACF;AAKO,SAAS,MACd,MACA,SACA,SACoB;AACpB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,OAAO,EAAE,MAAM,SAAS,SAAS,WAAW,OAAU;AAAA,EACxD;AACF;AAKO,SAAS,oBAA4B;AAC1C,SAAO,OAAO,WAAW;AAC3B;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export { ApiResponse, ContextTenant, ContextUser, CorsConfig, DatabaseAdapter, H
|
|
|
3
3
|
export { ModuleLoader, ModuleLoaderOptions, createModuleLoader, defineModule } from './module-loader.js';
|
|
4
4
|
export { RLSConfig, RLSError, RLSManager, createRLSManager, generateDisableRLS, generateRLSPolicy, rlsMiddleware } from './rls.js';
|
|
5
5
|
export { InMemoryRBAC, PermissionChecker, RBACService, StandardRoles, createInMemoryRBAC, createPermission, createRBACService, crudPermissions, parsePermission, requireAnyPermission, requireAnyRole, requireAuth, requirePermission, requireRole, requireTenantMember } from './rbac.js';
|
|
6
|
-
export { ApiError, AuthMiddlewareOptions, BadRequestError, ConflictError, CsrfOptions, ErrorHandlerOptions, ForbiddenError, InternalError, JwtPayload, JwtVerifier, MemoryRateLimitStorage, NotFoundError, QuotaCheckResult, QuotaEnforcementOptions, QuotaExceededError, QuotaManagerLike, RateLimitError, RateLimitOptions, RateLimitStorage, RequestLoggerOptions, ServiceUnavailableError, UnauthorizedError, UsageServiceLike, UsageTrackingOptions, ValidationError, auth, cors, createAuthMiddleware, createQuotaEnforcement, createRateLimiter, createUsageTracking, csrf, doubleSubmitCookie, errorHandler, multiQuotaEnforcement, notFoundHandler, optionalAuth, quotaEnforcement, rateLimit, requestLogger, usageTracking } from './
|
|
6
|
+
export { h as ApiError, A as AuthMiddlewareOptions, B as BadRequestError, i as ConflictError, C as CsrfOptions, E as ErrorHandlerOptions, F as ForbiddenError, I as InternalError, J as JwtPayload, b as JwtVerifier, M as MemoryRateLimitStorage, N as NotFoundError, D as QuotaCheckResult, y as QuotaEnforcementOptions, Q as QuotaExceededError, z as QuotaManagerLike, R as RateLimitError, k as RateLimitOptions, l as RateLimitStorage, p as RequestLoggerOptions, S as ServiceUnavailableError, U as UnauthorizedError, t as UsageServiceLike, s as UsageTrackingOptions, V as ValidationError, a as auth, d as cors, c as createAuthMiddleware, w as createQuotaEnforcement, j as createRateLimiter, q as createUsageTracking, e as csrf, f as doubleSubmitCookie, g as errorHandler, x as multiQuotaEnforcement, n as notFoundHandler, o as optionalAuth, v as quotaEnforcement, r as rateLimit, m as requestLogger, u as usageTracking } from './quota-enforcement-CN3z5bfc.js';
|
|
7
7
|
export { Infer, ValidateOptions, ValidationTarget, validate, validateBody, validateHeaders, validateParams, validateQuery } from './validation/index.js';
|
|
8
8
|
export { CursorPaginatedResponse, CursorPaginationMeta, CursorPaginationParams, PaginatedResponse, PaginationMeta, PaginationOptions, PaginationParams, accepted, createPaginationMeta, created, cursorPaginate, download, json, jsonError, jsonWithMeta, noContent, paginate, parseCursorPagination, parsePagination, redirect, setPaginationHeaders, sse, stream } from './utils/index.js';
|
|
9
9
|
export { HealthCheck, HealthCheckOptions, HealthCheckResult, HealthResponse, HealthStatus, createHealthRouter, healthHandler } from './health.js';
|