@geekmidas/constructs 10.0.0-alpha.83 → 10.0.0-alpha.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Endpoint-ZJhv68qq.mjs → Endpoint-BG4UJ9oA.mjs} +8 -2
- package/dist/Endpoint-BG4UJ9oA.mjs.map +1 -0
- package/dist/{Endpoint-Ba1PiyuJ.cjs → Endpoint-BoUg8ocM.cjs} +8 -2
- package/dist/Endpoint-BoUg8ocM.cjs.map +1 -0
- package/dist/{Endpoint-DJZkADYh.d.cts → Endpoint-C4PZn_mD.d.cts} +11 -3
- package/dist/Endpoint-C4PZn_mD.d.cts.map +1 -0
- package/dist/{Endpoint-hcHSFhda.d.mts → Endpoint-ViSuXwMB.d.mts} +11 -3
- package/dist/Endpoint-ViSuXwMB.d.mts.map +1 -0
- package/dist/{EndpointFactory-C3QvXMk6.mjs → EndpointFactory-BDtsrEvJ.mjs} +18 -3
- package/dist/EndpointFactory-BDtsrEvJ.mjs.map +1 -0
- package/dist/{EndpointFactory-B5siFRcO.d.mts → EndpointFactory-CLmsBr1G.d.mts} +15 -2
- package/dist/EndpointFactory-CLmsBr1G.d.mts.map +1 -0
- package/dist/{EndpointFactory-BkYuVg8W.d.cts → EndpointFactory-CLnJ2GQ8.d.cts} +15 -2
- package/dist/EndpointFactory-CLnJ2GQ8.d.cts.map +1 -0
- package/dist/{EndpointFactory-B_x2fXWQ.cjs → EndpointFactory-DJ7gXLpR.cjs} +18 -3
- package/dist/EndpointFactory-DJ7gXLpR.cjs.map +1 -0
- package/dist/{HonoEndpointAdaptor-chgcjPmg.mjs → HonoEndpointAdaptor-PtPlbeKY.mjs} +2 -2
- package/dist/{HonoEndpointAdaptor-chgcjPmg.mjs.map → HonoEndpointAdaptor-PtPlbeKY.mjs.map} +1 -1
- package/dist/{HonoEndpointAdaptor-0yLvYunI.cjs → HonoEndpointAdaptor-zVzVLJEO.cjs} +2 -2
- package/dist/{HonoEndpointAdaptor-0yLvYunI.cjs.map → HonoEndpointAdaptor-zVzVLJEO.cjs.map} +1 -1
- package/dist/adaptors/aws.cjs +2 -2
- package/dist/adaptors/aws.cjs.map +1 -1
- package/dist/adaptors/aws.d.cts +2 -2
- package/dist/adaptors/aws.d.mts +2 -2
- package/dist/adaptors/aws.mjs +2 -2
- package/dist/adaptors/aws.mjs.map +1 -1
- package/dist/adaptors/hono.cjs +1 -1
- package/dist/adaptors/hono.d.cts +1 -1
- package/dist/adaptors/hono.d.mts +1 -1
- package/dist/adaptors/hono.mjs +1 -1
- package/dist/adaptors/testing.cjs +3 -3
- package/dist/adaptors/testing.d.cts +2 -2
- package/dist/adaptors/testing.d.mts +2 -2
- package/dist/adaptors/testing.mjs +3 -3
- package/dist/{auth-XtDcvQxV.d.mts → auth-CYFghDZw.d.mts} +23 -4
- package/dist/auth-CYFghDZw.d.mts.map +1 -0
- package/dist/{auth-CuCozjsh.d.cts → auth-CwYlcogd.d.cts} +23 -4
- package/dist/auth-CwYlcogd.d.cts.map +1 -0
- package/dist/auth.cjs +70 -10
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +2 -2
- package/dist/auth.d.mts +2 -2
- package/dist/auth.mjs +71 -12
- package/dist/auth.mjs.map +1 -1
- package/dist/database/kysely.cjs +1 -1
- package/dist/database/kysely.d.cts +1 -1
- package/dist/database/kysely.d.mts +1 -1
- package/dist/database/kysely.mjs +1 -1
- package/dist/endpoints/index.cjs +2 -2
- package/dist/endpoints/index.d.cts +2 -2
- package/dist/endpoints/index.d.mts +2 -2
- package/dist/endpoints/index.mjs +2 -2
- package/dist/external-api.cjs +1 -1
- package/dist/external-api.mjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/{kysely-DN88k0gD.mjs → kysely-Bii4l6eP.mjs} +19 -7
- package/dist/kysely-Bii4l6eP.mjs.map +1 -0
- package/dist/{kysely-H7L1YDgE.cjs → kysely-CO_Dk43W.cjs} +18 -6
- package/dist/kysely-CO_Dk43W.cjs.map +1 -0
- package/dist/{kysely-BEm5sDlU.d.cts → kysely-D0bpzgPs.d.cts} +4 -2
- package/dist/kysely-D0bpzgPs.d.cts.map +1 -0
- package/dist/{kysely-CjuvdXEV.d.mts → kysely-DUqC3Ie0.d.mts} +4 -2
- package/dist/kysely-DUqC3Ie0.d.mts.map +1 -0
- package/dist/{telemetry-DGcFlVpB.d.cts → lambdaTelemetry-8vnmVZQ5.d.cts} +2 -2
- package/dist/lambdaTelemetry-8vnmVZQ5.d.cts.map +1 -0
- package/dist/{telemetry-DGcFlVpB.d.mts → lambdaTelemetry-8vnmVZQ5.d.mts} +2 -2
- package/dist/lambdaTelemetry-8vnmVZQ5.d.mts.map +1 -0
- package/dist/rest-api.cjs +5 -1
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.d.cts +15 -2
- package/dist/rest-api.d.cts.map +1 -1
- package/dist/rest-api.d.mts +15 -2
- package/dist/rest-api.d.mts.map +1 -1
- package/dist/rest-api.mjs +5 -1
- package/dist/rest-api.mjs.map +1 -1
- package/dist/site.cjs +1 -0
- package/dist/site.cjs.map +1 -1
- package/dist/site.d.cts +8 -0
- package/dist/site.d.cts.map +1 -1
- package/dist/site.d.mts +8 -0
- package/dist/site.d.mts.map +1 -1
- package/dist/site.mjs +1 -0
- package/dist/site.mjs.map +1 -1
- package/dist/telemetry-B48RLjyk.d.cts +40 -0
- package/dist/telemetry-B48RLjyk.d.cts.map +1 -0
- package/dist/telemetry-DRtT1_0A.d.mts +40 -0
- package/dist/telemetry-DRtT1_0A.d.mts.map +1 -0
- package/dist/telemetry.cjs +56 -0
- package/dist/telemetry.cjs.map +1 -0
- package/dist/telemetry.d.cts +2 -0
- package/dist/telemetry.d.mts +2 -0
- package/dist/telemetry.mjs +55 -0
- package/dist/telemetry.mjs.map +1 -0
- package/dist/{tracing-DbcPuhEy.mjs → tracing-CxaZ98IB.mjs} +28 -5
- package/dist/tracing-CxaZ98IB.mjs.map +1 -0
- package/dist/{tracing-3PpqRX07.cjs → tracing-DPMidF_r.cjs} +32 -3
- package/dist/tracing-DPMidF_r.cjs.map +1 -0
- package/dist/worker.cjs +1 -0
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +7 -0
- package/dist/worker.d.cts.map +1 -1
- package/dist/worker.d.mts +7 -0
- package/dist/worker.d.mts.map +1 -1
- package/dist/worker.mjs +1 -0
- package/dist/worker.mjs.map +1 -1
- package/package.json +41 -31
- package/dist/Endpoint-Ba1PiyuJ.cjs.map +0 -1
- package/dist/Endpoint-DJZkADYh.d.cts.map +0 -1
- package/dist/Endpoint-ZJhv68qq.mjs.map +0 -1
- package/dist/Endpoint-hcHSFhda.d.mts.map +0 -1
- package/dist/EndpointFactory-B5siFRcO.d.mts.map +0 -1
- package/dist/EndpointFactory-B_x2fXWQ.cjs.map +0 -1
- package/dist/EndpointFactory-BkYuVg8W.d.cts.map +0 -1
- package/dist/EndpointFactory-C3QvXMk6.mjs.map +0 -1
- package/dist/auth-CuCozjsh.d.cts.map +0 -1
- package/dist/auth-XtDcvQxV.d.mts.map +0 -1
- package/dist/kysely-BEm5sDlU.d.cts.map +0 -1
- package/dist/kysely-CjuvdXEV.d.mts.map +0 -1
- package/dist/kysely-DN88k0gD.mjs.map +0 -1
- package/dist/kysely-H7L1YDgE.cjs.map +0 -1
- package/dist/telemetry-DGcFlVpB.d.cts.map +0 -1
- package/dist/telemetry-DGcFlVpB.d.mts.map +0 -1
- package/dist/tracing-3PpqRX07.cjs.map +0 -1
- package/dist/tracing-DbcPuhEy.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"EndpointFactory-C3QvXMk6.mjs","names":["uniqBy","uniqBy"],"sources":["../src/endpoints/Authorizer.ts","../src/endpoints/rls.ts","../src/endpoints/EndpointBuilder.ts","../src/endpoints/EndpointFactory.ts"],"sourcesContent":["/**\n * OpenAPI 3.1 compliant security scheme definition.\n * @see https://spec.openapis.org/oas/v3.1.0#security-scheme-object\n */\nexport interface SecurityScheme {\n\t/** The type of the security scheme */\n\ttype: 'apiKey' | 'http' | 'mutualTLS' | 'oauth2' | 'openIdConnect';\n\t/** A description for security scheme */\n\tdescription?: string;\n\t/** Required for apiKey. The name of the header, query or cookie parameter */\n\tname?: string;\n\t/** Required for apiKey. The location of the API key */\n\tin?: 'query' | 'header' | 'cookie';\n\t/** Required for http. The name of the HTTP Authorization scheme (e.g., 'bearer') */\n\tscheme?: string;\n\t/** Optional for http bearer. A hint to the format of the bearer token */\n\tbearerFormat?: string;\n\t/** Required for oauth2. An object containing configuration for the flow types */\n\tflows?: OAuthFlows;\n\t/** Required for openIdConnect. The URL to discover OAuth2 configuration */\n\topenIdConnectUrl?: string;\n\t/** Vendor extensions (e.g., x-amazon-apigateway-authtype) */\n\t[key: `x-${string}`]: unknown;\n}\n\n/**\n * OAuth2 flow configuration\n */\nexport interface OAuthFlows {\n\timplicit?: OAuthFlow;\n\tpassword?: OAuthFlow;\n\tclientCredentials?: OAuthFlow;\n\tauthorizationCode?: OAuthFlow;\n}\n\nexport interface OAuthFlow {\n\tauthorizationUrl?: string;\n\ttokenUrl?: string;\n\trefreshUrl?: string;\n\tscopes: Record<string, string>;\n}\n\n/**\n * Built-in security schemes available by default.\n * Users can use these without defining them via .securitySchemes().\n */\nexport const BUILT_IN_SECURITY_SCHEMES = {\n\tjwt: {\n\t\ttype: 'http',\n\t\tscheme: 'bearer',\n\t\tbearerFormat: 'JWT',\n\t\tdescription: 'JWT Bearer token authentication',\n\t},\n\tbearer: {\n\t\ttype: 'http',\n\t\tscheme: 'bearer',\n\t\tdescription: 'Bearer token authentication',\n\t},\n\tapiKey: {\n\t\ttype: 'apiKey',\n\t\tin: 'header',\n\t\tname: 'X-API-Key',\n\t\tdescription: 'API key authentication via header',\n\t},\n\toauth2: {\n\t\ttype: 'oauth2',\n\t\tflows: {},\n\t\tdescription: 'OAuth 2.0 authentication',\n\t},\n\toidc: {\n\t\ttype: 'openIdConnect',\n\t\topenIdConnectUrl: '',\n\t\tdescription: 'OpenID Connect authentication',\n\t},\n\tiam: {\n\t\ttype: 'apiKey',\n\t\tin: 'header',\n\t\tname: 'Authorization',\n\t\tdescription: 'AWS IAM Signature Version 4 authentication',\n\t\t'x-amazon-apigateway-authtype': 'awsSigv4',\n\t},\n} as const satisfies Record<string, SecurityScheme>;\n\n/** Names of built-in security schemes */\nexport type BuiltInSecuritySchemeId = keyof typeof BUILT_IN_SECURITY_SCHEMES;\n\n/**\n * Represents an authorizer configuration for endpoints\n */\nexport interface Authorizer {\n\t/**\n\t * Unique identifier for the authorizer\n\t */\n\tname: string;\n\t/**\n\t * The OpenAPI security scheme definition for this authorizer\n\t */\n\tsecurityScheme?: SecurityScheme;\n\t/**\n\t * Type of authorizer (e.g., 'iam', 'jwt', 'custom')\n\t * @deprecated Use securityScheme.type instead\n\t */\n\ttype?: string;\n\t/**\n\t * Description of what this authorizer does\n\t * @deprecated Use securityScheme.description instead\n\t */\n\tdescription?: string;\n\t/**\n\t * Additional metadata specific to the authorizer type\n\t * @deprecated Use securityScheme with x-* extensions instead\n\t */\n\tmetadata?: Record<string, unknown>;\n}\n\n/**\n * Helper to create an authorizer configuration\n */\nexport function createAuthorizer(\n\tname: string,\n\toptions?: Omit<Authorizer, 'name'>,\n): Authorizer {\n\treturn {\n\t\tname,\n\t\t...options,\n\t};\n}\n\n/**\n * Check if a name is a built-in security scheme\n */\nexport function isBuiltInSecurityScheme(\n\tname: string,\n): name is BuiltInSecuritySchemeId {\n\treturn name in BUILT_IN_SECURITY_SCHEMES;\n}\n\n/**\n * Get a security scheme by name (built-in or custom)\n */\nexport function getSecurityScheme(\n\tname: string,\n\tcustomSchemes?: Record<string, SecurityScheme>,\n): SecurityScheme | undefined {\n\tif (customSchemes && name in customSchemes) {\n\t\treturn customSchemes[name];\n\t}\n\tif (isBuiltInSecurityScheme(name)) {\n\t\treturn BUILT_IN_SECURITY_SCHEMES[name];\n\t}\n\treturn undefined;\n}\n","import type { Logger } from '@geekmidas/logger';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport type { CookieFn, HeaderFn } from './Endpoint';\n\n/**\n * RLS context - key-value pairs to set as PostgreSQL session variables.\n * Keys become `prefix.key` (e.g., `app.user_id`).\n */\nexport interface RlsContext {\n\t[key: string]: string | number | boolean | null | undefined;\n}\n\n/**\n * Function type for extracting RLS context from request context.\n *\n * @template TServices - Available service dependencies\n * @template TSession - Session data type\n * @template TLogger - Logger type\n *\n * @example\n * ```ts\n * const extractor: RlsContextExtractor<[], UserSession> = ({ session }) => ({\n * user_id: session.userId,\n * tenant_id: session.tenantId,\n * roles: session.roles.join(','),\n * });\n * ```\n */\nexport type RlsContextExtractor<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n> = (ctx: {\n\tservices: ServiceRecord<TServices>;\n\tsession: TSession;\n\theader: HeaderFn;\n\tcookie: CookieFn;\n\tlogger: TLogger;\n}) => RlsContext | Promise<RlsContext>;\n\n/**\n * Configuration for RLS on an endpoint or factory.\n *\n * @template TServices - Available service dependencies\n * @template TSession - Session data type\n * @template TLogger - Logger type\n */\nexport interface RlsConfig<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n> {\n\t/** Function to extract RLS context from request */\n\textractor: RlsContextExtractor<TServices, TSession, TLogger>;\n\t/** Prefix for PostgreSQL session variables (default: 'app') */\n\tprefix?: string;\n}\n\n/**\n * Symbol used to bypass RLS for an endpoint.\n */\nexport const RLS_BYPASS = Symbol.for('geekmidas.rls.bypass');\n\n/**\n * Type for RLS bypass marker.\n */\nexport type RlsBypass = typeof RLS_BYPASS;\n","import type {\n\tAuditableAction,\n\tAuditStorage,\n\tExtractStorageAuditAction,\n} from '@geekmidas/audit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { RateLimitConfig } from '@geekmidas/rate-limit';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport uniqBy from 'lodash.uniqby';\nimport { ConstructType } from '../Construct';\nimport { cloneWith } from '../clone';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tserviceOf,\n\tservicesOf,\n} from '../construct-interface';\nimport { BaseFunctionBuilder } from '../functions';\nimport type { EventFor } from '../publisher';\nimport type { Topic } from '../topic/Topic';\nimport type { HttpMethod } from '../types';\nimport type { Authorizer, SecurityScheme } from './Authorizer';\nimport { getSecurityScheme } from './Authorizer';\nimport type { ActorExtractor, MappedAudit } from './audit';\nimport type {\n\tAuthorizeFn,\n\tEndpointHandler,\n\tSessionFn,\n\tSuccessStatus,\n} from './Endpoint';\nimport {\n\tEndpoint,\n\ttype EndpointSchemas,\n\ttype EndpointSurface,\n} from './Endpoint';\nimport type { RlsBypass, RlsConfig } from './rls';\nimport { RLS_BYPASS } from './rls';\n\nexport class EndpointBuilder<\n\tTRoute extends string,\n\tTMethod extends HttpMethod,\n\tTInput extends EndpointSchemas = {},\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTSession = unknown,\n\tTAuthorizers extends readonly string[] = readonly string[],\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n> extends BaseFunctionBuilder<\n\tTInput,\n\tOutSchema,\n\tTServices,\n\tTLogger,\n\tTAuditStorage,\n\tTAuditStorageServiceName,\n\tTDatabase,\n\tTDatabaseServiceName\n> {\n\tprotected schemas: TInput = {} as TInput;\n\tprotected _description?: string;\n\tprotected _status?: SuccessStatus;\n\tprotected _tags?: string[];\n\tprotected _memorySize?: number;\n\tprotected _responseType: string = 'application/json';\n\t/** Set by a factory's `.session()`; absent, the endpoint reads none. */\n\t_getSession?: SessionFn<TServices, TLogger, TSession, TDatabase>;\n\t_authorize: AuthorizeFn<TServices, TLogger, TSession, TInput, TDatabase> =\n\t\t() => true;\n\t_rateLimit?: RateLimitConfig;\n\t_availableAuthorizers: Authorizer[] = [];\n\t_authorizerName?: TAuthorizers[number];\n\t_actorExtractor?: ActorExtractor<TServices, TSession, TLogger>;\n\t_audits: MappedAudit<TAuditAction, OutSchema>[] = [];\n\t/**\n\t * Internal: the surface this builder came from, carried to the endpoint.\n\t *\n\t * Assigned by the factory before the builder is handed out, which is the\n\t * only way a builder is ever created.\n\t */\n\t_surface!: EndpointSurface;\n\t_customSecuritySchemes: Record<string, SecurityScheme> = {};\n\t_rlsConfig?: RlsConfig<TServices, TSession, TLogger>;\n\t_rlsBypass?: boolean;\n\n\tconstructor(\n\t\treadonly route: TRoute,\n\t\treadonly method: TMethod,\n\t) {\n\t\tsuper(ConstructType.Endpoint);\n\t}\n\n\t// Internal setter for EndpointFactory to set default auditor storage\n\t_setAuditorStorage(\n\t\tstorage: Service<TAuditStorageServiceName, TAuditStorage>,\n\t) {\n\t\tthis._auditorStorage = storage;\n\t}\n\n\t// Internal setter for EndpointFactory to set default database service\n\t_setDatabaseService(service: Service<TDatabaseServiceName, TDatabase>) {\n\t\tthis._databaseService = service;\n\t}\n\n\tdescription(description: string): this {\n\t\treturn cloneWith(this, { _description: description });\n\t}\n\n\tstatus(status: SuccessStatus): this {\n\t\treturn cloneWith(this, { _status: status });\n\t}\n\n\t/**\n\t * Publish `event` to `topic` once the handler has succeeded — repeatable,\n\t * one call per event, to as many topics as the endpoint names. The topic\n\t * becomes a dependency as with `.dependsOn([topic])`, so `services.<topic>`\n\t * is there for events the handler decides on itself.\n\t *\n\t * @example\n\t * ```ts\n\t * router.post('/users')\n\t * .event(users, {\n\t * type: 'user.created',\n\t * payload: (user) => ({ userId: user.id, email: user.email }),\n\t * })\n\t * ```\n\t */\n\tevent<TTopic extends Topic<any, any>>(\n\t\ttopic: TTopic,\n\t\tevent: EventFor<TTopic, InferStandardSchema<OutSchema>>,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\t[...TServices, TTopic['service']],\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\treturn this.withEvent(topic, event as never) as unknown as EndpointBuilder<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\t[...TServices, TTopic['service']],\n\t\t\tTLogger,\n\t\t\tOutSchema,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>;\n\t}\n\n\ttags(tags: string[]): this {\n\t\treturn cloneWith(this, { _tags: tags });\n\t}\n\n\tmemorySize(memorySize: number): this {\n\t\treturn cloneWith(this, { _memorySize: memorySize });\n\t}\n\n\t/**\n\t * Set the response content type for this endpoint.\n\t *\n\t * Defaults to `'application/json'`. When set to any other value\n\t * (e.g. `'text/html'`, `'text/plain'`), the response body is emitted\n\t * as-is rather than JSON-serialized, and the `Content-Type` header\n\t * reflects the declared value. Runtime overrides via `r.header()` still win.\n\t *\n\t * @param type - The MIME type to return (e.g. `'text/html'`)\n\t *\n\t * @example\n\t * ```typescript\n\t * api.get('/checkout-page')\n\t * .output(z.string())\n\t * .responseType('text/html')\n\t * .handle(async () => '<html>...</html>');\n\t * ```\n\t */\n\tresponseType(type: string): this {\n\t\treturn cloneWith(this, { _responseType: type });\n\t}\n\n\tbody<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tOmit<TInput, 'body'> & { body: T },\n\t\tTServices,\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\tthis.schemas.body = schema as unknown as T;\n\t\t// @ts-expect-error\n\t\treturn this;\n\t}\n\n\tsearch<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tOmit<TInput, 'query'> & { query: T },\n\t\tTServices,\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\tthis.schemas.query = schema as unknown as T;\n\t\t// @ts-expect-error\n\t\treturn this;\n\t}\n\n\tquery<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tOmit<TInput, 'query'> & { query: T },\n\t\tTServices,\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\treturn this.search(schema);\n\t}\n\n\tparams<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tOmit<TInput, 'params'> & { params: T },\n\t\tTServices,\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\tthis.schemas.params = schema as unknown as T;\n\t\t// @ts-expect-error\n\t\treturn this;\n\t}\n\n\tauthorize(\n\t\tfn: AuthorizeFn<TServices, TLogger, TSession, TInput, TDatabase>,\n\t): this {\n\t\treturn cloneWith(this, { _authorize: fn });\n\t}\n\n\trateLimit(config: RateLimitConfig): this {\n\t\treturn cloneWith(this, { _rateLimit: config });\n\t}\n\n\tauthorizer(\n\t\tname: TAuthorizers[number] | 'none',\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\tTServices,\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\t// Special case: 'none' explicitly marks endpoint as having no authorizer\n\t\tif (name === 'none') {\n\t\t\treturn cloneWith(this, { _authorizerName: undefined });\n\t\t}\n\n\t\t// Validate that the authorizer exists in available authorizers\n\t\tconst authorizerExists = this._availableAuthorizers.some(\n\t\t\t(a) => a.name === name,\n\t\t);\n\t\tif (!authorizerExists && this._availableAuthorizers.length > 0) {\n\t\t\tconst available = this._availableAuthorizers\n\t\t\t\t.map((a) => a.name)\n\t\t\t\t.join(', ');\n\t\t\tthrow new Error(\n\t\t\t\t`Authorizer \"${name as string}\" not found in available authorizers: ${available}`,\n\t\t\t);\n\t\t}\n\n\t\treturn cloneWith(this, { _authorizerName: name });\n\t}\n\n\t/**\n\t * Depend on constructs — a database, a bucket, a mail sender, a queue, a\n\t * topic.\n\t *\n\t * It records the edge and dissolves each construct's client into the\n\t * handler's service record under the construct's own id, so\n\t * `.dependsOn([uploads])` is what makes `services.uploads` exist and type.\n\t *\n\t * Constructs only. A `Service` does not match the shape, which is what keeps\n\t * env sniffing confined to `.services()` and the explicit lift.\n\t */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\t[...TServices, ...ServicesOf<T>],\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\t// Both halves of the edge, from one call and one clone: the services the\n\t\t// handler runs with, and the ids the manifest records. Recording them\n\t\t// separately is what let them drift apart.\n\t\t//\n\t\t// `servicesOf` is the half that validates, so it runs first — recording\n\t\t// ids ahead of it left a caught `NotAConstruct` with `undefined` already\n\t\t// on a `string[]`.\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\n\t\treturn cloneWith(this, {\n\t\t\t_services: uniqBy(\n\t\t\t\t[...this._services, ...services],\n\t\t\t\t(service: Service) => service.serviceName,\n\t\t\t),\n\t\t\t_constructs: idsOf(constructs, this._constructs),\n\t\t}) as unknown as EndpointBuilder<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\t[...TServices, ...ServicesOf<T>],\n\t\t\tTLogger,\n\t\t\tOutSchema,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>;\n\t}\n\n\tservices<T extends Service[]>(\n\t\tservices: T,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\t[...TServices, ...T],\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\treturn cloneWith(this, {\n\t\t\t_services: uniqBy(\n\t\t\t\t[...this._services, ...services],\n\t\t\t\t(s) => s.serviceName,\n\t\t\t) as TServices,\n\t\t}) as unknown as EndpointBuilder<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\t[...TServices, ...T],\n\t\t\tTLogger,\n\t\t\tOutSchema,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>;\n\t}\n\n\tlogger<T extends Logger>(\n\t\tlogger: T,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\tTServices,\n\t\tT,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\treturn cloneWith(this, {\n\t\t\t_logger: logger as unknown as TLogger,\n\t\t}) as unknown as EndpointBuilder<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tT,\n\t\t\tOutSchema,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>;\n\t}\n\n\toutput<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\tTServices,\n\t\tTLogger,\n\t\tT,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\treturn cloneWith(this, {\n\t\t\toutputSchema: schema as unknown as OutSchema,\n\t\t}) as unknown as EndpointBuilder<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tT,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>;\n\t}\n\n\t/**\n\t * Set the auditor storage service for this endpoint.\n\t * This enables audit functionality and makes `auditor` available in the handler context.\n\t * The audit action type is automatically inferred from the storage's generic parameter.\n\t */\n\toverride auditor<T extends AuditStorage<any>, TName extends string>(\n\t\tstorage: Service<TName, T>,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\tTServices,\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tT,\n\t\tTName,\n\t\tExtractStorageAuditAction<T>,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\treturn cloneWith(this, {\n\t\t\t_auditorStorage: storage as unknown as Service<\n\t\t\t\tTAuditStorageServiceName,\n\t\t\t\tTAuditStorage\n\t\t\t>,\n\t\t}) as unknown as EndpointBuilder<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tOutSchema,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tT,\n\t\t\tTName,\n\t\t\tExtractStorageAuditAction<T>,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>;\n\t}\n\n\t/**\n\t * Set the actor extractor function for audit records.\n\t * The actor is extracted from the request context and attached to all audits.\n\t */\n\tactor(\n\t\textractor: ActorExtractor<TServices, TSession, TLogger>,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\tTServices,\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\treturn cloneWith(this, { _actorExtractor: extractor });\n\t}\n\n\t/**\n\t * Add declarative audit definitions that are processed after the handler executes.\n\t * Similar to `.event()` for events, but for audits.\n\t *\n\t * @example\n\t * ```typescript\n\t * .audit<AppAuditAction>([\n\t * {\n\t * type: 'user.created',\n\t * payload: (response) => ({ userId: response.id, email: response.email }),\n\t * when: (response) => response.active,\n\t * entityId: (response) => response.id,\n\t * table: 'users',\n\t * },\n\t * ])\n\t * ```\n\t */\n\taudit(audits: MappedAudit<TAuditAction, OutSchema>[]): this {\n\t\treturn cloneWith(this, { _audits: audits });\n\t}\n\n\t/**\n\t * Set the database service for this endpoint.\n\t * The database will be available in the handler context as `db`.\n\t * When audit storage is configured and uses the same database,\n\t * `db` will automatically be the transaction for ACID compliance.\n\t *\n\t * @example\n\t * ```typescript\n\t * .database(databaseService)\n\t * .handle(async ({ db }) => {\n\t * // db is the raw database or transaction (when auditor uses same db)\n\t * return await db.selectFrom('users').selectAll().execute();\n\t * })\n\t * ```\n\t */\n\toverride database<T, TName extends string>(\n\t\tsource: Consumable<TName, T> | Service<TName, T>,\n\t): EndpointBuilder<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\tTServices,\n\t\tTLogger,\n\t\tOutSchema,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tT,\n\t\tTName\n\t> {\n\t\tconst service = serviceOf(source);\n\n\t\treturn cloneWith(this, {\n\t\t\t_databaseService: service as unknown as Service<\n\t\t\t\tTDatabaseServiceName,\n\t\t\t\tTDatabase\n\t\t\t>,\n\t\t}) as unknown as EndpointBuilder<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tOutSchema,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tT,\n\t\t\tTName\n\t\t>;\n\t}\n\n\t/**\n\t * Configure RLS (Row-Level Security) context for this endpoint.\n\t * Pass `false` or `RLS_BYPASS` to explicitly bypass RLS for this endpoint.\n\t *\n\t * @example\n\t * ```typescript\n\t * // Custom RLS config for this endpoint\n\t * .rls({\n\t * extractor: ({ session }) => ({\n\t * user_id: session.userId,\n\t * tenant_id: session.tenantId,\n\t * }),\n\t * prefix: 'app',\n\t * })\n\t *\n\t * // Bypass RLS (for admin endpoints)\n\t * .rls(false)\n\t * ```\n\t */\n\trls(\n\t\tconfig: RlsConfig<TServices, TSession, TLogger> | false | RlsBypass,\n\t): this {\n\t\tif (config === false || config === RLS_BYPASS) {\n\t\t\tthis._rlsBypass = true;\n\t\t\tthis._rlsConfig = undefined;\n\t\t} else {\n\t\t\tthis._rlsConfig = config;\n\t\t\tthis._rlsBypass = false;\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Explicitly bypass RLS for this endpoint.\n\t * Useful for admin operations that need unrestricted database access.\n\t *\n\t * @example\n\t * ```typescript\n\t * .rlsBypass()\n\t * .handle(async ({ db }) => {\n\t * // Full access, no RLS filtering\n\t * return db.selectFrom('orders').selectAll().execute();\n\t * })\n\t * ```\n\t */\n\trlsBypass(): this {\n\t\treturn cloneWith(this, { _rlsBypass: true, _rlsConfig: undefined });\n\t}\n\n\t// EndpointBuilder doesn't have a generic input method - it uses body, query, params instead\n\tinput(_schema: any): any {\n\t\tthrow new Error(\n\t\t\t'EndpointBuilder does not support generic input. Use body(), query(), or params() instead.',\n\t\t);\n\t}\n\n\thandle(\n\t\tfn: EndpointHandler<\n\t\t\tTInput,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tOutSchema,\n\t\t\tTSession,\n\t\t\tTDatabase,\n\t\t\tTAuditStorage,\n\t\t\tTAuditAction\n\t\t>,\n\t): Endpoint<\n\t\tTRoute,\n\t\tTMethod,\n\t\tTInput,\n\t\tOutSchema,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\t// Find authorizer metadata if name is set\n\t\t// If the authorizer name is set but not in availableAuthorizers, create a simple authorizer object\n\t\tlet authorizer: Authorizer | undefined;\n\t\tif (this._authorizerName) {\n\t\t\tconst existingAuthorizer = this._availableAuthorizers.find(\n\t\t\t\t(a) => a.name === this._authorizerName,\n\t\t\t);\n\n\t\t\tif (existingAuthorizer) {\n\t\t\t\tauthorizer = existingAuthorizer;\n\t\t\t} else {\n\t\t\t\t// Create authorizer with security scheme if available (built-in or custom)\n\t\t\t\tconst securityScheme = getSecurityScheme(\n\t\t\t\t\tthis._authorizerName as string,\n\t\t\t\t\tthis._customSecuritySchemes,\n\t\t\t\t);\n\t\t\t\tauthorizer = {\n\t\t\t\t\tname: this._authorizerName as string,\n\t\t\t\t\tsecurityScheme,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tconst endpoint = new Endpoint({\n\t\t\tfn,\n\t\t\tmethod: this.method,\n\t\t\troute: this.route,\n\t\t\tdescription: this._description,\n\t\t\ttags: this._tags,\n\t\t\tinput: this.schemas,\n\t\t\toutput: this.outputSchema,\n\t\t\tservices: this._services,\n\t\t\tconstructs: this._constructs,\n\t\t\tlogger: this._logger,\n\t\t\ttimeout: this._timeout,\n\t\t\tmemorySize: this._memorySize,\n\t\t\tauthorize: this._authorize,\n\t\t\tstatus: this._status,\n\t\t\tgetSession: this._getSession,\n\t\t\trateLimit: this._rateLimit,\n\t\t\tevents: this._events,\n\t\t\tauthorizer,\n\t\t\tsurface: this._surface,\n\t\t\tauditorStorageService: this._auditorStorage,\n\t\t\tactorExtractor: this._actorExtractor,\n\t\t\taudits: this._audits,\n\t\t\tdatabaseService: this._databaseService,\n\t\t\trlsConfig: this._rlsConfig,\n\t\t\trlsBypass: this._rlsBypass,\n\t\t\tresponseType: this._responseType,\n\t\t});\n\n\t\t// One field says which process runs a construct, whatever its kind. An\n\t\t// endpoint's is its surface; a cron's is the worker that handed out the\n\t\t// factory. The build partitions on this rather than on directories.\n\t\tendpoint.owner = this._surface?.id;\n\n\t\treturn endpoint;\n\t}\n}\n","import type {\n\tAuditableAction,\n\tAuditStorage,\n\tExtractStorageAuditAction,\n} from '@geekmidas/audit';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport type { Service } from '@geekmidas/services';\nimport uniqBy from 'lodash.uniqby';\nimport {\n\ttype Consumable,\n\tidsOf,\n\tisConsumable,\n\ttype ServicesOf,\n\tserviceOf,\n\tservicesOf,\n} from '../construct-interface';\nimport type { HttpMethod } from '../types';\nimport {\n\ttype Authorizer,\n\ttype BuiltInSecuritySchemeId,\n\tgetSecurityScheme,\n\ttype SecurityScheme,\n} from './Authorizer';\nimport type { ActorExtractor } from './audit';\nimport type { AuthorizeFn, EndpointSurface, SessionFn } from './Endpoint';\nimport { EndpointBuilder } from './EndpointBuilder';\nimport type { RlsConfig } from './rls';\n\n// Re-export SecurityScheme to make the type portable in declaration files\nexport type { SecurityScheme } from './Authorizer';\n\nexport class EndpointFactory<\n\tTServices extends Service[] = [],\n\tTBasePath extends string = '',\n\tTLogger extends Logger = Logger,\n\tTSession = unknown,\n\tTAuthorizers extends readonly string[] = readonly string[],\n\tTAuditStorage extends AuditStorage<any> | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<\n\t\tstring,\n\t\tunknown\n\t> = ExtractStorageAuditAction<NonNullable<TAuditStorage>>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n\tTSecuritySchemes extends Record<string, SecurityScheme> = Record<\n\t\tstring,\n\t\tSecurityScheme\n\t>,\n\tTRlsConfig extends\n\t\t| RlsConfig<TServices, TSession, TLogger>\n\t\t| undefined = undefined,\n> {\n\tprivate defaultServices: TServices = [] as unknown as TServices;\n\t/**\n\t * The constructs `.dependsOn()` was given, kept alongside the services they\n\t * dissolve into.\n\t *\n\t * `.dependsOn()` collapses straight into `.services()`, which is right for\n\t * *running* — a handler wants clients, not ids — and loses the one thing the\n\t * manifest needs: which constructs this endpoint reaches. Keeping the ids\n\t * here is what lets a route declare its edges, and lets a target derive its\n\t * environment from the graph rather than from sniffing what the code touched.\n\t */\n\tprivate defaultConstructs: string[] = [];\n\tprivate basePath: TBasePath = '' as TBasePath;\n\tprivate defaultAuthorizeFn?: AuthorizeFn<\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tundefined,\n\t\tTDatabase\n\t>;\n\tprivate defaultSessionExtractor?: SessionFn<\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTDatabase\n\t>;\n\tprivate defaultLogger: TLogger;\n\t/**\n\t * The surface this factory belongs to, stamped onto everything it builds.\n\t *\n\t * Set only by `RestApi`, which is the only thing that has one. A factory\n\t * with no surface produces endpoints that carry none, which is what a\n\t * standalone endpoint has always been.\n\t */\n\tprivate surface: EndpointSurface;\n\tprivate availableAuthorizers: Authorizer[];\n\tprivate defaultAuthorizerName?: TAuthorizers[number];\n\tprivate defaultAuditorStorage:\n\t\t| Service<TAuditStorageServiceName, TAuditStorage>\n\t\t| undefined;\n\tprivate defaultDatabaseService:\n\t\t| Service<TDatabaseServiceName, TDatabase>\n\t\t| undefined;\n\tprivate defaultActorExtractor?: ActorExtractor<TServices, TSession, TLogger>;\n\tprivate customSecuritySchemes: TSecuritySchemes;\n\tprivate defaultRlsConfig?: TRlsConfig;\n\n\tconstructor({\n\t\tbasePath,\n\t\tdefaultAuthorizeFn,\n\t\tdefaultLogger = DEFAULT_LOGGER as TLogger,\n\t\tdefaultSessionExtractor,\n\t\t// @ts-expect-error\n\t\tdefaultServices = [] as TServices,\n\t\tdefaultConstructs = [] as string[],\n\t\tavailableAuthorizers = [],\n\t\tdefaultAuthorizerName,\n\t\tdefaultAuditorStorage,\n\t\tdefaultDatabaseService,\n\t\tdefaultActorExtractor,\n\t\tcustomSecuritySchemes = {} as TSecuritySchemes,\n\t\tdefaultRlsConfig,\n\t\tsurface,\n\t}: EndpointFactoryOptions<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tTRlsConfig\n\t>) {\n\t\t// Initialize default services\n\t\tthis.defaultConstructs = [...new Set(defaultConstructs)];\n\t\tthis.defaultServices = uniqBy(\n\t\t\tdefaultServices,\n\t\t\t(s) => s.serviceName,\n\t\t) as TServices;\n\n\t\tthis.basePath = basePath || ('' as TBasePath);\n\t\tthis.defaultAuthorizeFn = defaultAuthorizeFn;\n\t\tthis.defaultLogger = defaultLogger;\n\t\tthis.defaultSessionExtractor = defaultSessionExtractor;\n\t\tthis.availableAuthorizers = availableAuthorizers;\n\t\tthis.defaultAuthorizerName = defaultAuthorizerName;\n\t\tthis.defaultAuditorStorage = defaultAuditorStorage;\n\t\tthis.defaultDatabaseService = defaultDatabaseService;\n\t\tthis.defaultActorExtractor = defaultActorExtractor;\n\t\tthis.customSecuritySchemes = customSecuritySchemes;\n\t\tthis.defaultRlsConfig = defaultRlsConfig;\n\t\tthis.surface = surface;\n\t}\n\n\tstatic joinPaths<TBasePath extends string, P extends string>(\n\t\tpath: P,\n\t\tbasePath: TBasePath = '' as TBasePath,\n\t): JoinPaths<TBasePath, P> {\n\t\t// Handle empty cases\n\t\tif (!basePath && !path) return '/' as JoinPaths<TBasePath, P>;\n\t\tif (!basePath)\n\t\t\treturn (path.startsWith('/') ? path : `/${path}`) as JoinPaths<\n\t\t\t\tTBasePath,\n\t\t\t\tP\n\t\t\t>;\n\t\tif (!path)\n\t\t\treturn (\n\t\t\t\tbasePath.startsWith('/') ? basePath : `/${basePath}`\n\t\t\t) as JoinPaths<TBasePath, P>;\n\n\t\tconst base = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath;\n\t\tconst segment = path.startsWith('/') ? path : `/${path}`;\n\n\t\tlet result = base + segment;\n\n\t\t// Ensure leading slash\n\t\tif (!result.startsWith('/')) {\n\t\t\tresult = `/${result}`;\n\t\t}\n\n\t\t// Normalize multiple slashes (except in the middle of the path where they might be intentional)\n\t\tresult = result.replace(/^\\/+/g, '/');\n\n\t\t// Remove trailing slash unless it's the root path \"/\"\n\t\tif (result.length > 1 && result.endsWith('/')) {\n\t\t\tresult = result.slice(0, -1);\n\t\t}\n\n\t\treturn result as JoinPaths<TBasePath, P>;\n\t}\n\n\t// Configure available authorizers\n\tauthorizers<const T extends readonly string[]>(\n\t\tauthorizers: T,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tT,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tTRlsConfig\n\t> {\n\t\tconst authorizerConfigs = authorizers.map((name) => ({\n\t\t\tname,\n\t\t\tsecurityScheme: getSecurityScheme(name, this.customSecuritySchemes),\n\t\t}));\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tT,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tTRlsConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor,\n\t\t\tavailableAuthorizers: authorizerConfigs,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this.defaultActorExtractor,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig,\n\t\t});\n\t}\n\n\t/**\n\t * Define custom security schemes for this factory.\n\t * These extend the built-in schemes (jwt, bearer, apiKey, oauth2, oidc).\n\t *\n\t * @example\n\t * ```typescript\n\t * const router = e.securitySchemes({\n\t * awsIamSigV4: {\n\t * type: 'apiKey',\n\t * in: 'header',\n\t * name: 'Authorization',\n\t * 'x-amazon-apigateway-authtype': 'awsSigv4',\n\t * },\n\t * });\n\t * ```\n\t */\n\tsecuritySchemes<T extends Record<string, SecurityScheme>>(\n\t\tschemes: T,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes & T,\n\t\tTRlsConfig\n\t> {\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes & T,\n\t\t\tTRlsConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this.defaultActorExtractor,\n\t\t\tcustomSecuritySchemes: {\n\t\t\t\t...this.customSecuritySchemes,\n\t\t\t\t...schemes,\n\t\t\t} as TSecuritySchemes & T,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig,\n\t\t});\n\t}\n\n\t/**\n\t * Set the default authorizer for all endpoints created from this factory.\n\t * Individual endpoints can override this by calling `.authorizer()` on the builder.\n\t * Use `'none'` to explicitly disable authorization for all endpoints.\n\t *\n\t * Accepts:\n\t * - Built-in security scheme names: 'jwt', 'bearer', 'apiKey', 'oauth2', 'oidc'\n\t * - Custom security scheme names defined via `.securitySchemes()`\n\t * - 'none' to disable authorization\n\t */\n\tauthorizer(\n\t\tname:\n\t\t\t| BuiltInSecuritySchemeId\n\t\t\t| keyof TSecuritySchemes\n\t\t\t| TAuthorizers[number]\n\t\t\t| 'none',\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tTRlsConfig\n\t> {\n\t\t// Validate that the authorizer exists in available authorizers (if authorizers() was called)\n\t\tif (name !== 'none' && this.availableAuthorizers.length > 0) {\n\t\t\tconst authorizerExists = this.availableAuthorizers.some(\n\t\t\t\t(a) => a.name === name,\n\t\t\t);\n\t\t\tif (!authorizerExists) {\n\t\t\t\tconst available = this.availableAuthorizers\n\t\t\t\t\t.map((a) => a.name)\n\t\t\t\t\t.join(', ');\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authorizer \"${name as string}\" not found in available authorizers: ${available}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tTRlsConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName:\n\t\t\t\tname === 'none' ? undefined : (name as TAuthorizers[number]),\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this.defaultActorExtractor,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig,\n\t\t});\n\t}\n\n\t// Create a sub-router with a path prefix\n\troute<TPath extends string>(\n\t\tpath: TPath,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tJoinPaths<TBasePath, TPath>,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tTRlsConfig\n\t> {\n\t\tconst newBasePath = EndpointFactory.joinPaths(path, this.basePath);\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tJoinPaths<TBasePath, TPath>,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tTRlsConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: newBasePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this.defaultActorExtractor,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig,\n\t\t});\n\t}\n\n\t// Create a new factory with authorization\n\tauthorize(\n\t\tfn: AuthorizeFn<TServices, TLogger, TSession, undefined, TDatabase>,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tTRlsConfig\n\t> {\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tTRlsConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: fn,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this.defaultActorExtractor,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig,\n\t\t});\n\t}\n\n\t// Create a new factory with services\n\t/**\n\t * Depend on constructs — a database, a bucket, a mail sender, a queue, a\n\t * topic.\n\t *\n\t * It records the edge and dissolves each construct's client into the\n\t * handler's service record under the construct's own id, so\n\t * `.dependsOn([uploads])` is what makes `services.uploads` exist and type.\n\t *\n\t * Constructs only. A `Service` does not match the shape, which is what keeps\n\t * env sniffing confined to `.services()` and the explicit lift.\n\t */\n\tdependsOn<const S extends readonly Consumable[]>(\n\t\tconstructs: S,\n\t): EndpointFactory<\n\t\t[...ServicesOf<S>, ...TServices],\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tRlsConfig<[...ServicesOf<S>, ...TServices], TSession, TLogger> | undefined\n\t> {\n\t\t// The services are what a handler *runs* with; the ids are what the\n\t\t// manifest needs. Dissolving to services alone is what lost the edges —\n\t\t// the same information, one of the two forms discarded.\n\t\tconst next = this.services(servicesOf(constructs) as unknown as Service[]);\n\t\tnext.defaultConstructs = [\n\t\t\t...new Set([\n\t\t\t\t...this.defaultConstructs,\n\t\t\t\t...constructs.map((construct) => construct.id),\n\t\t\t]),\n\t\t];\n\n\t\treturn next as unknown as EndpointFactory<\n\t\t\t[...ServicesOf<S>, ...TServices],\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tRlsConfig<[...ServicesOf<S>, ...TServices], TSession, TLogger> | undefined\n\t\t>;\n\t}\n\n\tservices<S extends Service[]>(\n\t\tservices: S,\n\t): EndpointFactory<\n\t\t[...S, ...TServices],\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tRlsConfig<[...S, ...TServices], TSession, TLogger> | undefined\n\t> {\n\t\treturn new EndpointFactory<\n\t\t\t[...S, ...TServices],\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tRlsConfig<[...S, ...TServices], TSession, TLogger> | undefined\n\t\t>({\n\t\t\tdefaultServices: [...services, ...this.defaultServices],\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn as unknown as AuthorizeFn<\n\t\t\t\t[...S, ...TServices],\n\t\t\t\tTLogger,\n\t\t\t\tTSession\n\t\t\t>,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor as unknown as\n\t\t\t\t| SessionFn<[...S, ...TServices], TLogger, TSession, TDatabase>\n\t\t\t\t| undefined,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this.defaultActorExtractor as unknown as\n\t\t\t\t| ActorExtractor<[...S, ...TServices], TSession, TLogger>\n\t\t\t\t| undefined,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig as unknown as\n\t\t\t\t| RlsConfig<[...S, ...TServices], TSession, TLogger>\n\t\t\t\t| undefined,\n\t\t});\n\t}\n\n\tlogger<L extends Logger>(\n\t\tlogger: L,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tL,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tRlsConfig<TServices, TSession, L> | undefined\n\t> {\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tL,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tRlsConfig<TServices, TSession, L> | undefined\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn as unknown as AuthorizeFn<\n\t\t\t\tTServices,\n\t\t\t\tL,\n\t\t\t\tTSession\n\t\t\t>,\n\t\t\tdefaultLogger: logger,\n\t\t\tdefaultSessionExtractor: this\n\t\t\t\t.defaultSessionExtractor as unknown as SessionFn<\n\t\t\t\tTServices,\n\t\t\t\tL,\n\t\t\t\tTSession\n\t\t\t>,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this\n\t\t\t\t.defaultActorExtractor as unknown as ActorExtractor<\n\t\t\t\tTServices,\n\t\t\t\tTSession,\n\t\t\t\tL\n\t\t\t>,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig as unknown as\n\t\t\t\t| RlsConfig<TServices, TSession, L>\n\t\t\t\t| undefined,\n\t\t});\n\t}\n\n\tsession<T>(\n\t\tsession: SessionFn<TServices, TLogger, T, TDatabase>,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tT,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tRlsConfig<TServices, T, TLogger> | undefined\n\t> {\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tT,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tRlsConfig<TServices, T, TLogger> | undefined\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn as unknown as AuthorizeFn<\n\t\t\t\tTServices,\n\t\t\t\tTLogger,\n\t\t\t\tT\n\t\t\t>,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: session,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this\n\t\t\t\t.defaultActorExtractor as unknown as ActorExtractor<\n\t\t\t\tTServices,\n\t\t\t\tT,\n\t\t\t\tTLogger\n\t\t\t>,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig as unknown as\n\t\t\t\t| RlsConfig<TServices, T, TLogger>\n\t\t\t\t| undefined,\n\t\t});\n\t}\n\n\t/**\n\t * Set the database service for endpoints created from this factory.\n\t * The database will be available in handler context as `db`.\n\t */\n\tdatabase<T, TName extends string>(\n\t\tsource: Consumable<TName, T> | Service<TName, T>,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tT,\n\t\tTName,\n\t\tTSecuritySchemes,\n\t\tTRlsConfig\n\t> {\n\t\tconst service = serviceOf(source);\n\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tT,\n\t\t\tTName,\n\t\t\tTSecuritySchemes,\n\t\t\tTRlsConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\t// The database is an edge like any `.dependsOn()`: without its id here an\n\t\t\t// endpoint built from `api.database(db)` reached a database the\n\t\t\t// manifest never heard of, so nothing composed from the edges — a\n\t\t\t// deploy's grants, an app container's environment — included it.\n\t\t\tdefaultConstructs: isConsumable(source)\n\t\t\t\t? idsOf([source], this.defaultConstructs)\n\t\t\t\t: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn as unknown as\n\t\t\t\t| AuthorizeFn<TServices, TLogger, TSession, undefined, T>\n\t\t\t\t| undefined,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\t// Reset session extractor when database changes - user should call .session() after .database()\n\t\t\t// to get proper type inference for the new database type\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor as unknown as\n\t\t\t\t| SessionFn<TServices, TLogger, TSession, T>\n\t\t\t\t| undefined,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: service,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig,\n\t\t});\n\t}\n\n\t/**\n\t * Set the auditor storage service for endpoints created from this factory.\n\t * This enables audit functionality and makes `auditor` available in handler context.\n\t * The audit action type is automatically inferred from the storage's generic parameter.\n\t */\n\tauditor<T extends AuditStorage<any>, TName extends string>(\n\t\tstorage: Service<TName, T>,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tT,\n\t\tTName,\n\t\tExtractStorageAuditAction<T>,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tTRlsConfig\n\t> {\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tT,\n\t\t\tTName,\n\t\t\tExtractStorageAuditAction<T>,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tTRlsConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: storage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this\n\t\t\t\t.defaultActorExtractor as unknown as ActorExtractor<\n\t\t\t\tTServices,\n\t\t\t\tTSession,\n\t\t\t\tTLogger\n\t\t\t>,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig,\n\t\t});\n\t}\n\n\t/**\n\t * Set the actor extractor function for endpoints created from this factory.\n\t * The actor is extracted from the request context and attached to all audits.\n\t */\n\tactor(\n\t\textractor: ActorExtractor<TServices, TSession, TLogger>,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tTRlsConfig\n\t> {\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tTRlsConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: extractor,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: this.defaultRlsConfig,\n\t\t});\n\t}\n\n\t/**\n\t * Set the RLS (Row-Level Security) configuration for endpoints created from this factory.\n\t * This enables automatic PostgreSQL session variable setting for RLS policies.\n\t *\n\t * @example\n\t * ```typescript\n\t * const api = new EndpointFactory()\n\t * .database(databaseService)\n\t * .session(extractSession)\n\t * .rls({\n\t * extractor: ({ session }) => ({\n\t * user_id: session.userId,\n\t * tenant_id: session.tenantId,\n\t * }),\n\t * prefix: 'app',\n\t * });\n\t * ```\n\t */\n\trls<TConfig extends RlsConfig<TServices, TSession, TLogger>>(\n\t\tconfig: TConfig,\n\t): EndpointFactory<\n\t\tTServices,\n\t\tTBasePath,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName,\n\t\tTSecuritySchemes,\n\t\tTConfig\n\t> {\n\t\treturn new EndpointFactory<\n\t\t\tTServices,\n\t\t\tTBasePath,\n\t\t\tTLogger,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName,\n\t\t\tTSecuritySchemes,\n\t\t\tTConfig\n\t\t>({\n\t\t\tdefaultServices: this.defaultServices,\n\t\t\tdefaultConstructs: this.defaultConstructs,\n\t\t\tbasePath: this.basePath,\n\t\t\tdefaultAuthorizeFn: this.defaultAuthorizeFn,\n\t\t\tdefaultLogger: this.defaultLogger,\n\t\t\tdefaultSessionExtractor: this.defaultSessionExtractor,\n\t\t\tavailableAuthorizers: this.availableAuthorizers,\n\t\t\tdefaultAuthorizerName: this.defaultAuthorizerName,\n\t\t\tdefaultAuditorStorage: this.defaultAuditorStorage,\n\t\t\tdefaultDatabaseService: this.defaultDatabaseService,\n\t\t\tdefaultActorExtractor: this.defaultActorExtractor,\n\t\t\tcustomSecuritySchemes: this.customSecuritySchemes,\n\t\t\tsurface: this.surface,\n\t\t\tdefaultRlsConfig: config,\n\t\t});\n\t}\n\n\tprivate createBuilder<TMethod extends HttpMethod, TPath extends string>(\n\t\tmethod: TMethod,\n\t\tpath: TPath,\n\t): EndpointBuilder<\n\t\tJoinPaths<TBasePath, TPath>,\n\t\tTMethod,\n\t\t{},\n\t\tTServices,\n\t\tTLogger,\n\t\tundefined,\n\t\tTSession,\n\t\tTAuthorizers,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t> {\n\t\tconst fullPath = EndpointFactory.joinPaths(path, this.basePath);\n\t\tconst builder = new EndpointBuilder<\n\t\t\tJoinPaths<TBasePath, TPath>,\n\t\t\tTMethod,\n\t\t\t{},\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tundefined,\n\t\t\tTSession,\n\t\t\tTAuthorizers,\n\t\t\tTAuditStorage,\n\t\t\tTAuditStorageServiceName,\n\t\t\tTAuditAction,\n\t\t\tTDatabase,\n\t\t\tTDatabaseServiceName\n\t\t>(fullPath, method);\n\n\t\tif (this.defaultAuthorizeFn) {\n\t\t\tbuilder._authorize = this.defaultAuthorizeFn as any;\n\t\t}\n\t\tif (this.defaultServices.length) {\n\t\t\t// Create a copy to avoid sharing references between builders\n\t\t\tbuilder._services = [...this.defaultServices] as TServices;\n\t\t}\n\t\tif (this.defaultConstructs.length) {\n\t\t\t// Alongside the services, not instead of them: one is what the handler\n\t\t\t// runs with, the other is what the manifest records it reaches.\n\t\t\tbuilder._constructs = [...this.defaultConstructs];\n\t\t}\n\n\t\tif (this.defaultLogger) {\n\t\t\tbuilder._logger = this.defaultLogger as TLogger;\n\t\t}\n\n\t\tbuilder._surface = this.surface;\n\n\t\tif (this.defaultSessionExtractor) {\n\t\t\tbuilder._getSession = this.defaultSessionExtractor as SessionFn<\n\t\t\t\tTServices,\n\t\t\t\tTLogger,\n\t\t\t\tTSession\n\t\t\t>;\n\t\t}\n\n\t\t// Set available authorizers and default\n\t\tbuilder._availableAuthorizers = this.availableAuthorizers;\n\t\tif (this.defaultAuthorizerName) {\n\t\t\tbuilder._authorizerName = this.defaultAuthorizerName;\n\t\t}\n\n\t\t// Set auditor storage if configured\n\t\tif (this.defaultAuditorStorage) {\n\t\t\tbuilder._setAuditorStorage(this.defaultAuditorStorage as any);\n\t\t}\n\n\t\t// Set database service if configured\n\t\tif (this.defaultDatabaseService) {\n\t\t\tbuilder._setDatabaseService(this.defaultDatabaseService as any);\n\t\t}\n\n\t\t// Set actor extractor if configured\n\t\tif (this.defaultActorExtractor) {\n\t\t\tbuilder._actorExtractor = this.defaultActorExtractor;\n\t\t}\n\n\t\t// Set custom security schemes\n\t\tbuilder._customSecuritySchemes = this.customSecuritySchemes;\n\n\t\t// Set RLS config if configured\n\t\tif (this.defaultRlsConfig) {\n\t\t\tbuilder._rlsConfig = this.defaultRlsConfig as any;\n\t\t}\n\n\t\treturn builder;\n\t}\n\n\tpost<TPath extends string>(path: TPath) {\n\t\treturn this.createBuilder('POST', path);\n\t}\n\n\tget<TPath extends string>(path: TPath) {\n\t\treturn this.createBuilder('GET', path);\n\t}\n\n\tput<TPath extends string>(path: TPath) {\n\t\treturn this.createBuilder('PUT', path);\n\t}\n\n\tdelete<TPath extends string>(path: TPath) {\n\t\treturn this.createBuilder('DELETE', path);\n\t}\n\n\tpatch<TPath extends string>(path: TPath) {\n\t\treturn this.createBuilder('PATCH', path);\n\t}\n\n\toptions<TPath extends string>(path: TPath) {\n\t\treturn this.createBuilder('OPTIONS', path);\n\t}\n}\n\nexport type RemoveTrailingSlash<T extends string> = T extends `${infer Rest}/`\n\t? Rest extends ''\n\t\t? T // Keep \"/\" as is\n\t\t: Rest\n\t: T;\n\nexport type JoinPaths<\n\tTBasePath extends string,\n\tTPath extends string,\n> = RemoveTrailingSlash<\n\tTBasePath extends ''\n\t\t? TPath\n\t\t: TPath extends ''\n\t\t\t? TBasePath\n\t\t\t: TBasePath extends '/'\n\t\t\t\t? TPath extends `/${string}`\n\t\t\t\t\t? TPath\n\t\t\t\t\t: `/${TPath}`\n\t\t\t\t: TBasePath extends `${infer Base}/`\n\t\t\t\t\t? TPath extends `/${infer Rest}`\n\t\t\t\t\t\t? `${Base}/${Rest}`\n\t\t\t\t\t\t: `${Base}/${TPath}`\n\t\t\t\t\t: TPath extends `/${infer Rest}`\n\t\t\t\t\t\t? `${TBasePath}/${Rest}`\n\t\t\t\t\t\t: `${TBasePath}/${TPath}`\n>;\n\nexport interface EndpointFactoryOptions<\n\tTServices extends Service[] = [],\n\tTBasePath extends string = '',\n\tTLogger extends Logger = Logger,\n\tTSession = unknown,\n\tTAuthorizers extends readonly string[] = readonly string[],\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n\tTSecuritySchemes extends Record<string, SecurityScheme> = Record<\n\t\tstring,\n\t\tSecurityScheme\n\t>,\n\tTRlsConfig extends\n\t\t| RlsConfig<TServices, TSession, TLogger>\n\t\t| undefined = undefined,\n> {\n\tdefaultServices?: TServices;\n\t/** Construct ids from `.dependsOn()`, carried so a route can declare edges. */\n\tdefaultConstructs?: string[];\n\tbasePath?: TBasePath;\n\tdefaultAuthorizeFn?: AuthorizeFn<\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tundefined,\n\t\tTDatabase\n\t>;\n\tdefaultLogger?: TLogger;\n\tdefaultSessionExtractor?: SessionFn<TServices, TLogger, TSession, TDatabase>;\n\tavailableAuthorizers?: Authorizer[];\n\tdefaultAuthorizerName?: TAuthorizers[number];\n\tdefaultAuditorStorage?: Service<TAuditStorageServiceName, TAuditStorage>;\n\tdefaultDatabaseService?: Service<TDatabaseServiceName, TDatabase>;\n\tdefaultActorExtractor?: ActorExtractor<TServices, TSession, TLogger>;\n\tcustomSecuritySchemes?: TSecuritySchemes;\n\tdefaultRlsConfig?: TRlsConfig;\n\t/**\n\t * The surface this factory belongs to.\n\t *\n\t * Required. A factory exists to build endpoints for a surface, and an\n\t * endpoint without one has no logger, no env parser and nothing to\n\t * attribute its traffic to — which was survivable only while `e` existed.\n\t *\n\t * Carried through every derived factory, so `api.database(db)`\n\t * still produces endpoints that know which API serves them.\n\t */\n\tsurface: EndpointSurface;\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAa,4BAA4B;CACxC,KAAK;EACJ,MAAM;EACN,QAAQ;EACR,cAAc;EACd,aAAa;CACd;CACA,QAAQ;EACP,MAAM;EACN,QAAQ;EACR,aAAa;CACd;CACA,QAAQ;EACP,MAAM;EACN,IAAI;EACJ,MAAM;EACN,aAAa;CACd;CACA,QAAQ;EACP,MAAM;EACN,OAAO,CAAC;EACR,aAAa;CACd;CACA,MAAM;EACL,MAAM;EACN,kBAAkB;EAClB,aAAa;CACd;CACA,KAAK;EACJ,MAAM;EACN,IAAI;EACJ,MAAM;EACN,aAAa;EACb,gCAAgC;CACjC;AACD;;;;AAqCA,SAAgB,iBACf,MACA,SACa;CACb,OAAO;EACN;EACA,GAAG;CACJ;AACD;;;;AAKA,SAAgB,wBACf,MACkC;CAClC,OAAO,QA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EAFV,YACU,uBACA,aACT;;;;;;;;;;;iBAqBc,WAAW"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kysely-BEm5sDlU.d.cts","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"mappings":";;;;;;;;;;;iBAmGsB,sBAAsB;;;;;;;;;;;;UC3D3B,8BAA8B,KAAK;;;;;;;;EAQnD;;;;;;;;EAQA;;;;;;;;;;;EAWA,UAAU;;;;;;EAMV;;;UAIS;EACT;EACA;EACA;;;;;;;;;cAUY,eAAe,cAAc,0CAC9B,UAAU,OAAO,OAAO;mBAiBjB;WAfT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ,OAAO;;;;;mBAMrC;mBACA;mBACA;mBACA;mBACA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS,uBAC1B,cAAc;EAyBf,WAAW;;;;;;;;;;;;;EAqDX,UAAU,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;EAyBlC,MAAM,2BAA2B,cAChC,KAAI,cAAc,SAClB;IAAW;MACT,MAAM;;;;;;;;;EAeT,OAAO,UAAU,wBAChB,IAAI,cAAc,UAClB,UAAS,wBACP,eAAe,UAAU;;;;;;;;;;;;;MAoBxB,SAAS,WAAW,aAAa,eAAe,OAAO;;;;;;;;;MAgBvD,gBAAgB,KAAK;UAcX;;;;;;;;;;;;;;;;;;;KAuCH,iBAAiB,IAAI,wBAAwB,KACxD,eAAe,IAAI"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kysely-CjuvdXEV.d.mts","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"mappings":";;;;;;;;;;;iBAmGsB,sBAAsB;;;;;;;;;;;;UC3D3B,8BAA8B,KAAK;;;;;;;;EAQnD;;;;;;;;EAQA;;;;;;;;;;;EAWA,UAAU;;;;;;EAMV;;;UAIS;EACT;EACA;EACA;;;;;;;;;cAUY,eAAe,cAAc,0CAC9B,UAAU,OAAO,OAAO;mBAiBjB;WAfT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ,OAAO;;;;;mBAMrC;mBACA;mBACA;mBACA;mBACA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS,uBAC1B,cAAc;EAyBf,WAAW;;;;;;;;;;;;;EAqDX,UAAU,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;EAyBlC,MAAM,2BAA2B,cAChC,KAAI,cAAc,SAClB;IAAW;MACT,MAAM;;;;;;;;;EAeT,OAAO,UAAU,wBAChB,IAAI,cAAc,UAClB,UAAS,wBACP,eAAe,UAAU;;;;;;;;;;;;;MAoBxB,SAAS,WAAW,aAAa,eAAe,OAAO;;;;;;;;;MAgBvD,gBAAgB,KAAK;UAcX;;;;;;;;;;;;;;;;;;;KAuCH,iBAAiB,IAAI,wBAAwB,KACxD,eAAe,IAAI"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kysely-DN88k0gD.mjs","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"sourcesContent":["/**\n * The `pg` pools a database construct opens, and what every one of them gets:\n *\n * - **A name.** `application_name` is what `pg_stat_activity` shows beside a\n * connection. Without one, a database at `max_connections` cannot say who\n * holds them. It is a *fallback*, so `PGAPPNAME` or `?application_name=` in\n * the URL still win.\n * - **Tagged queries.** Inside a request, each query ends in a comment naming\n * what ran it — `/*operation='POST /orders',request_id='…'*\\/` — in the\n * sqlcommenter form. It shows in `pg_stat_activity.query`, in the server's\n * slow-query and `auto_explain` logs, and costs no round trip;\n * `pg_stat_statements` ignores comments, so its grouping is unchanged.\n * - **A listener for idle-client errors.** When the server ends an idle\n * connection (`idle_session_timeout`, a failover, an admin), the pool emits\n * `'error'`. With no listener that is an uncaught exception that kills the\n * process — for a client the pool has already discarded.\n * - **A span per query.** Through the global OpenTelemetry tracer, so a no-op\n * without a provider. `pg` is bundled into a production entry, where no\n * instrumentation can hook its module load — so the client is wrapped here,\n * as the tags are. See {@link traceQueries}.\n * - **A way to close.** {@link closeDatabasePools} ends every pool opened, so a\n * server shutting down releases its connections instead of holding them\n * until the process dies.\n */\n\nimport { currentRequestContext } from '@geekmidas/services';\nimport {\n\ttype Attributes,\n\tcontext,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\nimport pg from 'pg';\nimport { onShutdown } from '../shutdown';\n\nexport interface DatabasePoolOptions {\n\t/** Tag queries run inside a request with what ran them. Default true. */\n\tqueryTags?: boolean;\n}\n\n/** The longest statement text a query span carries. */\nexport const MAX_STATEMENT_LENGTH = 2048;\n\n/** Every pool opened and not yet closed, so a shutdown can end them all. */\nconst open = new Set<pg.Pool>();\nonShutdown(() => closeDatabasePools());\n\n/**\n * A pool for one URL, with its schema actually on the search path.\n *\n * `?search_path=` is not a libpq parameter — a URL carrying it connects\n * happily and then resolves every unqualified name against `public`, which is\n * how a schema tenant silently writes its tables into the database it was\n * separated from. Postgres takes it as a startup option instead, so the URL\n * keeps the readable form the target derives and this turns it into the thing\n * the server understands.\n */\nexport function openPool(\n\turl: string,\n\toptions: DatabasePoolOptions = {},\n): pg.Pool {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tparsed.searchParams.delete('search_path');\n\n\tconst pool = new pg.Pool({\n\t\tconnectionString: parsed.toString(),\n\t\t...(searchPath ? { options: `-c search_path=${searchPath}` } : {}),\n\t\tfallback_application_name: applicationName(),\n\t});\n\n\tpool.on('error', (error) => {\n\t\tconst logger = currentRequestContext()?.logger;\n\t\tif (logger) logger.warn({ err: error }, 'Idle database connection lost');\n\t\telse console.warn('Idle database connection lost:', error.message);\n\t});\n\tconst target = connectionAttributes(parsed);\n\tpool.on('connect', (client) => {\n\t\t// Tags first, so the span wraps them and records the statement as the\n\t\t// application wrote it rather than with the comment on the end.\n\t\tif (options.queryTags !== false) tagQueries(client);\n\t\ttraceQueries(client, target);\n\t});\n\n\topen.add(pool);\n\tconst end = pool.end.bind(pool);\n\tpool.end = (async () => {\n\t\topen.delete(pool);\n\t\tawait end();\n\t}) as typeof pool.end;\n\n\treturn pool;\n}\n\n/**\n * End every pool opened, waiting for checked-out connections to come back.\n * For a server's shutdown, after it has stopped taking requests.\n */\nexport async function closeDatabasePools(): Promise<void> {\n\tawait Promise.all([...open].map((pool) => pool.end()));\n}\n\n/**\n * Who this process is, as Postgres will show it: the Lambda function, else the\n * app — `GKM_APP_NAME` where an entry sets it, `gkm dev`'s app tag otherwise.\n * Postgres keeps 63 bytes of it.\n */\nexport function applicationName(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\treturn (\n\t\tenv.AWS_LAMBDA_FUNCTION_NAME ||\n\t\tenv.GKM_APP_NAME ||\n\t\tenv.GKM_DEV_APP?.split('#').pop() ||\n\t\tundefined\n\t);\n}\n\n/**\n * The comment that says what ran a query, or '' outside a request.\n *\n * Values keep only characters that cannot end a comment or a quoted value —\n * `*` and `'` among those dropped — so a route cannot inject SQL through it.\n */\nexport function queryTag(): string {\n\tconst request = currentRequestContext();\n\tif (!request) return '';\n\n\tconst tags = [\n\t\t['operation', request.operation],\n\t\t['request_id', request.requestId],\n\t].filter((tag): tag is [string, string] => Boolean(tag[1]));\n\tif (tags.length === 0) return '';\n\n\tconst clean = (value: string) => value.replace(/[^\\w ./:{}@-]/g, '');\n\treturn ` /*${tags.map(([key, value]) => `${key}='${clean(value)}'`).join(',')}*/`;\n}\n\n/**\n * Append {@link queryTag} to everything `client` runs: a SQL string — what\n * Kysely sends — or a query object such as a cursor's.\n */\nfunction tagQueries(client: pg.PoolClient): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst tag = queryTag();\n\t\tif (tag && typeof first === 'string') return query(first + tag, ...rest);\n\t\tif (\n\t\t\ttag &&\n\t\t\tfirst &&\n\t\t\ttypeof first === 'object' &&\n\t\t\ttypeof (first as { text?: unknown }).text === 'string'\n\t\t) {\n\t\t\tconst config = first as { text: string };\n\t\t\tconfig.text += tag;\n\t\t}\n\t\treturn query(first, ...rest);\n\t}) as typeof client.query;\n}\n\n/** What every span of one pool says about where it connects. */\nfunction connectionAttributes(url: URL): Attributes {\n\tconst name = decodeURIComponent(url.pathname.slice(1));\n\treturn {\n\t\t'db.system': 'postgresql',\n\t\t...(name && { 'db.name': name }),\n\t\t'server.address': url.hostname,\n\t\t'server.port': Number(url.port || 5432),\n\t};\n}\n\nconst TRACER = '@geekmidas/constructs';\n\n/** `select`, `insert`, … — the first keyword, or `with`'s main statement. */\nconst OPERATION = /^\\s*(?:\\/\\*.*?\\*\\/\\s*)?(\\w+)/s;\n/** The table a statement is about, when it names one where it usually does. */\nconst TABLE =\n\t/\\b(?:from|into|update|join)\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i;\n\n/**\n * What a statement does and to which table, parsed cheaply from its first\n * characters: `select \"orders\"`, `insert \"public\".\"users\"`. A statement the\n * patterns cannot read leaves `table` unset.\n */\nexport function describeStatement(text: string): {\n\toperation?: string;\n\ttable?: string;\n} {\n\tconst head = text.length > 512 ? text.slice(0, 512) : text;\n\tconst operation = OPERATION.exec(head)?.[1]?.toLowerCase();\n\tconst table = TABLE.exec(head)?.[1]?.replace(/\"/g, '');\n\treturn {\n\t\t...(operation && { operation }),\n\t\t...(table && { table }),\n\t};\n}\n\n/**\n * A span around everything `client` runs — `<operation> <table>`, or\n * `db.query` when the statement does not say.\n *\n * The statement text goes on the span only for a parameterized query — values\n * passed separately, as Kysely always does — and truncated. Parameter values\n * never do. A bare string with no values could hold anything a caller\n * concatenated into it, so it gets no text at all.\n */\nfunction traceQueries(client: pg.PoolClient, connection: Attributes): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst config =\n\t\t\tfirst && typeof first === 'object'\n\t\t\t\t? (first as { text?: unknown; values?: unknown })\n\t\t\t\t: undefined;\n\t\tconst text =\n\t\t\ttypeof first === 'string'\n\t\t\t\t? first\n\t\t\t\t: typeof config?.text === 'string'\n\t\t\t\t\t? config.text\n\t\t\t\t\t: undefined;\n\t\tconst values = typeof first === 'string' ? rest[0] : config?.values;\n\t\tconst { operation, table } = text ? describeStatement(text) : {};\n\n\t\tconst span = trace\n\t\t\t.getTracer(TRACER)\n\t\t\t.startSpan(operation && table ? `${operation} ${table}` : 'db.query', {\n\t\t\t\tkind: SpanKind.CLIENT,\n\t\t\t\tattributes: {\n\t\t\t\t\t...connection,\n\t\t\t\t\t...(operation && { 'db.operation': operation }),\n\t\t\t\t\t...(table && { 'db.sql.table': table }),\n\t\t\t\t\t...(text &&\n\t\t\t\t\t\tArray.isArray(values) && {\n\t\t\t\t\t\t\t'db.statement':\n\t\t\t\t\t\t\t\ttext.length > MAX_STATEMENT_LENGTH\n\t\t\t\t\t\t\t\t\t? text.slice(0, MAX_STATEMENT_LENGTH)\n\t\t\t\t\t\t\t\t\t: text,\n\t\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t});\n\t\tconst end = (error?: unknown) => {\n\t\t\tif (error) {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t}\n\t\t\tspan.end();\n\t\t};\n\n\t\t// A callback, as `pg`'s own callback form takes it.\n\t\tconst last = rest[rest.length - 1];\n\t\tif (typeof last === 'function') {\n\t\t\tconst args = [...rest];\n\t\t\targs[args.length - 1] = (error: unknown, ...result: unknown[]) => {\n\t\t\t\tend(error);\n\t\t\t\treturn (last as (...a: unknown[]) => unknown)(error, ...result);\n\t\t\t};\n\t\t\treturn context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...args),\n\t\t\t);\n\t\t}\n\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...rest),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tend(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\t\t(result as Promise<unknown>).then(\n\t\t\t\t() => end(),\n\t\t\t\t(error) => end(error),\n\t\t\t);\n\t\t} else if (\n\t\t\tresult &&\n\t\t\ttypeof (result as { once?: unknown }).once === 'function'\n\t\t) {\n\t\t\t// A submittable — a cursor or a stream — ends when it says so.\n\t\t\tconst emitter = result as {\n\t\t\t\tonce(event: string, fn: (e?: unknown) => void): void;\n\t\t\t};\n\t\t\temitter.once('end', () => end());\n\t\t\temitter.once('error', (error) => end(error));\n\t\t} else {\n\t\t\tend();\n\t\t}\n\t\treturn result;\n\t}) as typeof client.query;\n}\n","/**\n * `KyselyDatabase` — a declared Postgres database, typed by its schema.\n *\n * It declares a logical database, a schema, and the roles that reach it, and\n * hands back a Kysely client built from the one URL the adapter supplied. It\n * names no cloud: `--target=aws` fills that URL from RDS, local dev from the\n * Postgres container.\n *\n * Transactions and RLS context are the execution wrapper's job — it opens the\n * transaction and puts it in `ctx.db`. This construct does not resolve\n * connections per request.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDEFAULT_POSTGRES_VERSION,\n\ttype Declaration,\n\ttype PostgresVersion,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport { Cache } from '../cache';\nimport type { Construct } from '../construct-interface';\nimport { openPool } from './pool';\n\n/** The schema a database uses when it does not say otherwise. */\nconst DEFAULT_SCHEMA = 'app';\n\n/**\n * Everything Kysely takes, plus what this construct declares.\n *\n * `dialect` is omitted because the construct owns it — it is built from the one\n * URL the adapter supplied, which is the whole point of the construct. The rest\n * of `KyselyConfig` (`plugins`, `log`) is the app's business and passes\n * straight through, so anything Kysely adds later arrives without being\n * tracked here.\n */\nexport interface KyselyDatabaseOptions extends Omit<KyselyConfig, 'dialect'> {\n\t/**\n\t * The schema, pinned on both roles' `search_path`.\n\t *\n\t * Defaults to `app` — the role the schema plays, rather than a restatement\n\t * of the database's own name, which reads correctly beside `auth` and\n\t * `pgboss` and keeps the application off `public`.\n\t */\n\tschema?: string;\n\t/**\n\t * Provision the owner/runtime role split. Defaults to on.\n\t *\n\t * Off falls back to the cluster's master credential in both URLs, giving up\n\t * the DDL/DML split and putting credentials that can drop a table into the\n\t * function's environment. A deliberate downgrade, not a default.\n\t */\n\troles?: boolean;\n\t/**\n\t * The Postgres major version to provision.\n\t *\n\t * Declared here so one statement reaches both targets. It was previously\n\t * set in two unrelated places — a container tag locally, nothing at all on\n\t * AWS (so Aurora chose) — which is how local came to run 18 while deployed\n\t * ran 17.7 with nothing recording the difference.\n\t *\n\t * Defaults to {@link DEFAULT_POSTGRES_VERSION}.\n\t */\n\tversion?: PostgresVersion;\n\t/**\n\t * End each query run inside a request with a comment naming what ran it —\n\t * `/*operation='POST /orders',request_id='…'*\\/` — so `pg_stat_activity`\n\t * and the server's logs can tie a query to its endpoint. Defaults to on.\n\t */\n\tqueryTags?: boolean;\n}\n\n/** What makes a construct derived rather than a database in its own right. */\ninterface DerivedFrom {\n\tkind: 'database-reader' | 'database-schema';\n\tof: string;\n\tschema?: string;\n}\n\n/**\n * @typeParam DB - the database's schema.\n * @typeParam TName - the canonical id. TypeScript has no partial\n * type-argument inference, so `new KyselyDatabase<OrdersDB>('orders')` leaves\n * this at its default and the service key widens to `string`. `db` still types\n * through `.database()`, which infers from the service.\n */\nexport class KyselyDatabase<DB = unknown, TName extends string = string>\n\timplements Construct<TName, Kysely<DB>>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, Kysely<DB>>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * build publishes and the key the client reads cannot drift.\n\t */\n\tprivate readonly config: { url: string; ownerUrl: string };\n\tprivate readonly schemaName: string;\n\tprivate readonly roles: boolean;\n\tprivate readonly version: PostgresVersion;\n\tprivate readonly derivedFrom?: DerivedFrom;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: KyselyDatabaseOptions = {},\n\t\tderivedFrom?: DerivedFrom,\n\t) {\n\t\t// Canonicalises, so `orders` and `Orders` are one construct rather than\n\t\t// two that collide. Throws on anything that cannot become a valid id.\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.config = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\townerUrl: provideKey(canonical, 'ownerUrl'),\n\t\t};\n\t\tthis.schemaName = options.schema ?? DEFAULT_SCHEMA;\n\t\tthis.roles = options.roles ?? true;\n\t\tthis.version = options.version ?? DEFAULT_POSTGRES_VERSION;\n\t\tthis.derivedFrom = derivedFrom;\n\n\t\t// A field, not a getter: service discovery caches by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\t// Forwards the whole options object — cherry-picking `envParser` strips\n\t\t\t// `context` and with it the request-scoped logger.\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\tif (this.derivedFrom) {\n\t\t\tconst { kind, of, schema } = this.derivedFrom;\n\n\t\t\treturn [\n\t\t\t\tkind === 'database-schema'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\tschema: schema ?? this.schemaName,\n\t\t\t\t\t\t\t// The runtime key alone — see the note below on the parent.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\t// A reader has no owner URL of its own — nothing migrates\n\t\t\t\t\t\t\t// through a read-only endpoint — so this is the one key.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t},\n\t\t\t];\n\t\t}\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'database',\n\t\t\t\tid: this.id,\n\t\t\t\tengine: 'postgres',\n\t\t\t\tschema: this.schemaName,\n\t\t\t\tversion: this.version,\n\t\t\t\t// One key, the runtime role's. `config` also holds the owner key and\n\t\t\t\t// it is deliberately absent here: a key in `provides` is a key an\n\t\t\t\t// edge can name, and nothing should be able to depend on DDL rights.\n\t\t\t\tprovides: [this.config.url],\n\t\t\t\t...(this.roles ? {} : { roles: false }),\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * A read-only endpoint on this database.\n\t *\n\t * Read-only is enforced by the reader role's grants rather than by which\n\t * endpoint it resolves to, so falling back to the writer where no replica\n\t * exists is safe rather than a silently writable connection behind a name\n\t * that says reader. There is no `writer()`: the database *is* the writer, so\n\t * a replica can never be reached by accident.\n\t *\n\t * The return type is narrower than this class on purpose — see\n\t * {@link ReadOnlyDatabase}.\n\t */\n\treader(): ReadOnlyDatabase<DB, `${TName}Reader`> {\n\t\treturn new KyselyDatabase<DB, `${TName}Reader`>(\n\t\t\t`${this.id}Reader` as ConstructName<`${TName}Reader`>,\n\t\t\tthis.options,\n\t\t\t{ kind: 'database-reader', of: this.id },\n\t\t);\n\t}\n\n\t/**\n\t * A cache that lives in this database.\n\t *\n\t * The same strengthening `schema()` is over a second database: `new\n\t * Cache('Sessions')` says the app caches and leaves where to the deployment,\n\t * while this says it caches *here* — which is a fact about the application\n\t * and so belongs in its code.\n\t *\n\t * What it buys beyond being explicit: the table's schema and the role that\n\t * reaches it come from this database rather than from a second convention,\n\t * and the backend no longer has to guess which database \"the database\" meant\n\t * when an app declares two.\n\t *\n\t * A cache is not a `KyselyDatabase`, so this returns a `Cache` — the client\n\t * is a key/value store, not a query builder, and typing it as the parent\n\t * would be a convenience that lies.\n\t */\n\tcache<TCache extends string = `${TName}Cache`>(\n\t\tid: ConstructName<TCache> = `${this.id}Cache` as ConstructName<TCache>,\n\t\toptions: { table?: string } = {},\n\t): Cache<TCache> {\n\t\treturn new Cache<TCache>(id, {\n\t\t\tof: this.id,\n\t\t\t...(options.table ? { table: options.table } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * A second schema in this database, with its own role(s) and its own URL —\n\t * so this database's role holds no grant on those tables at all.\n\t *\n\t * Typed separately because a tenant has its own tables: the point is that\n\t * `auth.selectFrom('sessions')` type-checks and\n\t * `orders.selectFrom('sessions')` does not.\n\t */\n\tschema<TenantDB, TTenant extends string>(\n\t\tid: ConstructName<TTenant>,\n\t\toptions: KyselyDatabaseOptions = {},\n\t): KyselyDatabase<TenantDB, TTenant> {\n\t\treturn new KyselyDatabase<TenantDB, TTenant>(id, options, {\n\t\t\tkind: 'database-schema',\n\t\t\tof: this.id,\n\t\t\tschema: options.schema ?? (id as string).toLowerCase(),\n\t\t});\n\t}\n\n\t/**\n\t * A connection as the *owner* role — the one that may create, alter and drop.\n\t *\n\t * A `Service` rather than part of the construct, and deliberately so: a\n\t * construct is what `.dependsOn()` accepts, and nothing should be able to\n\t * depend on this. A migrator asks for it by name; a handler cannot ask at\n\t * all, which is the security property the role split exists for.\n\t *\n\t * Falls back to the runtime URL where no owner URL was published — the\n\t * `roles: false` downgrade, where there is only one credential and it is the\n\t * cluster master's.\n\t */\n\tget owner(): Service<`${Uncapitalize<TName>}Owner`, Kysely<DB>> {\n\t\treturn {\n\t\t\tserviceName:\n\t\t\t\t`${serviceKey(this.id)}Owner` as `${Uncapitalize<TName>}Owner`,\n\t\t\tregister: (options) => this.connect(options, { owner: true }),\n\t\t};\n\t}\n\n\t/**\n\t * What this database's clients are built with besides a dialect — the\n\t * plugins and logging it was declared with.\n\t *\n\t * Public so that whatever opens a connection to it outside \\`connect()\\` —\n\t * a test's transaction — builds the same client. A test that dropped the\n\t * plugins would write \\`createdAt\\` where production writes \\`created_at\\`.\n\t */\n\tget clientConfig(): Omit<KyselyConfig, 'dialect'> {\n\t\t// Split what the manifest declared from what Kysely takes, so neither\n\t\t// leaks into the other: \\`schema\\`, \\`roles\\` and \\`version\\` describe\n\t\t// infrastructure and mean nothing to a client.\n\t\tconst {\n\t\t\tschema: _schema,\n\t\t\troles: _roles,\n\t\t\tversion: _version,\n\t\t\tqueryTags: _queryTags,\n\t\t\t...kysely\n\t\t} = this.options;\n\t\treturn kysely;\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Kysely<DB>> {\n\t\tconst { url, ownerUrl } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.config.url).string(),\n\t\t\t\townerUrl: get(this.config.ownerUrl).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\treturn new Kysely<DB>({\n\t\t\t...this.clientConfig,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\tpool: openPool(as.owner ? (ownerUrl ?? url) : url, {\n\t\t\t\t\tqueryTags: this.options.queryTags,\n\t\t\t\t}),\n\t\t\t}),\n\t\t});\n\t}\n}\n\n/**\n * A database you may read through, and derive nothing from.\n *\n * A reader is terminal in the graph, and this is that fact in the type system.\n * `DERIVES_FROM` gives `cache` and `database-schema` no `database-reader`\n * parent, and there is no reader of a reader — so `orders.reader().cache(…)`\n * has always been illegal, but it type-checked and failed later at\n * `assertDerivations`. That is a long way round to learn that a read-only\n * endpoint cannot own a table something writes to.\n *\n * Omitting the three deriving methods rather than making them throw keeps the\n * failure where it costs least: the editor, on the line that wrote it.\n *\n * The result is deliberately not assignable back to `KyselyDatabase` — a\n * reader is not one, and anything that genuinely needs the writer should say\n * so.\n */\nexport type ReadOnlyDatabase<DB, TName extends string> = Omit<\n\tKyselyDatabase<DB, TName>,\n\t'reader' | 'cache' | 'schema'\n>;\nexport { closeDatabasePools } from './pool';\n"],"mappings":";;;;;;;;AA6CA,MAAM,uBAAO,IAAI,IAAa;AAC9B,iBAAiB,mBAAmB,CAAC;;;;;;;;;;;AAYrC,SAAg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M;EAER,OAAO,IAAI,OAAW;GACrB,GAAG,KAAK;GACR,SAAS,IAAI,gBAAgB,EAC5B,MAAM,SAAS,GAAG,QAAS,YAAY,MAAO,KAAK,EAClD,WAAW,KAAK,QAAQ,UACzB,CAAC,EACF,CAAC;EACF,CAAC;CACF;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kysely-H7L1YDgE.cjs","names":["onShutdown","currentRequestContext","trace","SpanKind","SpanStatusCode","context","canonicalId","provideKey","DEFAULT_POSTGRES_VERSION","serviceKey","Cache","kysely","Kysely","PostgresDialect"],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"sourcesContent":["/**\n * The `pg` pools a database construct opens, and what every one of them gets:\n *\n * - **A name.** `application_name` is what `pg_stat_activity` shows beside a\n * connection. Without one, a database at `max_connections` cannot say who\n * holds them. It is a *fallback*, so `PGAPPNAME` or `?application_name=` in\n * the URL still win.\n * - **Tagged queries.** Inside a request, each query ends in a comment naming\n * what ran it — `/*operation='POST /orders',request_id='…'*\\/` — in the\n * sqlcommenter form. It shows in `pg_stat_activity.query`, in the server's\n * slow-query and `auto_explain` logs, and costs no round trip;\n * `pg_stat_statements` ignores comments, so its grouping is unchanged.\n * - **A listener for idle-client errors.** When the server ends an idle\n * connection (`idle_session_timeout`, a failover, an admin), the pool emits\n * `'error'`. With no listener that is an uncaught exception that kills the\n * process — for a client the pool has already discarded.\n * - **A span per query.** Through the global OpenTelemetry tracer, so a no-op\n * without a provider. `pg` is bundled into a production entry, where no\n * instrumentation can hook its module load — so the client is wrapped here,\n * as the tags are. See {@link traceQueries}.\n * - **A way to close.** {@link closeDatabasePools} ends every pool opened, so a\n * server shutting down releases its connections instead of holding them\n * until the process dies.\n */\n\nimport { currentRequestContext } from '@geekmidas/services';\nimport {\n\ttype Attributes,\n\tcontext,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\nimport pg from 'pg';\nimport { onShutdown } from '../shutdown';\n\nexport interface DatabasePoolOptions {\n\t/** Tag queries run inside a request with what ran them. Default true. */\n\tqueryTags?: boolean;\n}\n\n/** The longest statement text a query span carries. */\nexport const MAX_STATEMENT_LENGTH = 2048;\n\n/** Every pool opened and not yet closed, so a shutdown can end them all. */\nconst open = new Set<pg.Pool>();\nonShutdown(() => closeDatabasePools());\n\n/**\n * A pool for one URL, with its schema actually on the search path.\n *\n * `?search_path=` is not a libpq parameter — a URL carrying it connects\n * happily and then resolves every unqualified name against `public`, which is\n * how a schema tenant silently writes its tables into the database it was\n * separated from. Postgres takes it as a startup option instead, so the URL\n * keeps the readable form the target derives and this turns it into the thing\n * the server understands.\n */\nexport function openPool(\n\turl: string,\n\toptions: DatabasePoolOptions = {},\n): pg.Pool {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tparsed.searchParams.delete('search_path');\n\n\tconst pool = new pg.Pool({\n\t\tconnectionString: parsed.toString(),\n\t\t...(searchPath ? { options: `-c search_path=${searchPath}` } : {}),\n\t\tfallback_application_name: applicationName(),\n\t});\n\n\tpool.on('error', (error) => {\n\t\tconst logger = currentRequestContext()?.logger;\n\t\tif (logger) logger.warn({ err: error }, 'Idle database connection lost');\n\t\telse console.warn('Idle database connection lost:', error.message);\n\t});\n\tconst target = connectionAttributes(parsed);\n\tpool.on('connect', (client) => {\n\t\t// Tags first, so the span wraps them and records the statement as the\n\t\t// application wrote it rather than with the comment on the end.\n\t\tif (options.queryTags !== false) tagQueries(client);\n\t\ttraceQueries(client, target);\n\t});\n\n\topen.add(pool);\n\tconst end = pool.end.bind(pool);\n\tpool.end = (async () => {\n\t\topen.delete(pool);\n\t\tawait end();\n\t}) as typeof pool.end;\n\n\treturn pool;\n}\n\n/**\n * End every pool opened, waiting for checked-out connections to come back.\n * For a server's shutdown, after it has stopped taking requests.\n */\nexport async function closeDatabasePools(): Promise<void> {\n\tawait Promise.all([...open].map((pool) => pool.end()));\n}\n\n/**\n * Who this process is, as Postgres will show it: the Lambda function, else the\n * app — `GKM_APP_NAME` where an entry sets it, `gkm dev`'s app tag otherwise.\n * Postgres keeps 63 bytes of it.\n */\nexport function applicationName(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\treturn (\n\t\tenv.AWS_LAMBDA_FUNCTION_NAME ||\n\t\tenv.GKM_APP_NAME ||\n\t\tenv.GKM_DEV_APP?.split('#').pop() ||\n\t\tundefined\n\t);\n}\n\n/**\n * The comment that says what ran a query, or '' outside a request.\n *\n * Values keep only characters that cannot end a comment or a quoted value —\n * `*` and `'` among those dropped — so a route cannot inject SQL through it.\n */\nexport function queryTag(): string {\n\tconst request = currentRequestContext();\n\tif (!request) return '';\n\n\tconst tags = [\n\t\t['operation', request.operation],\n\t\t['request_id', request.requestId],\n\t].filter((tag): tag is [string, string] => Boolean(tag[1]));\n\tif (tags.length === 0) return '';\n\n\tconst clean = (value: string) => value.replace(/[^\\w ./:{}@-]/g, '');\n\treturn ` /*${tags.map(([key, value]) => `${key}='${clean(value)}'`).join(',')}*/`;\n}\n\n/**\n * Append {@link queryTag} to everything `client` runs: a SQL string — what\n * Kysely sends — or a query object such as a cursor's.\n */\nfunction tagQueries(client: pg.PoolClient): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst tag = queryTag();\n\t\tif (tag && typeof first === 'string') return query(first + tag, ...rest);\n\t\tif (\n\t\t\ttag &&\n\t\t\tfirst &&\n\t\t\ttypeof first === 'object' &&\n\t\t\ttypeof (first as { text?: unknown }).text === 'string'\n\t\t) {\n\t\t\tconst config = first as { text: string };\n\t\t\tconfig.text += tag;\n\t\t}\n\t\treturn query(first, ...rest);\n\t}) as typeof client.query;\n}\n\n/** What every span of one pool says about where it connects. */\nfunction connectionAttributes(url: URL): Attributes {\n\tconst name = decodeURIComponent(url.pathname.slice(1));\n\treturn {\n\t\t'db.system': 'postgresql',\n\t\t...(name && { 'db.name': name }),\n\t\t'server.address': url.hostname,\n\t\t'server.port': Number(url.port || 5432),\n\t};\n}\n\nconst TRACER = '@geekmidas/constructs';\n\n/** `select`, `insert`, … — the first keyword, or `with`'s main statement. */\nconst OPERATION = /^\\s*(?:\\/\\*.*?\\*\\/\\s*)?(\\w+)/s;\n/** The table a statement is about, when it names one where it usually does. */\nconst TABLE =\n\t/\\b(?:from|into|update|join)\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i;\n\n/**\n * What a statement does and to which table, parsed cheaply from its first\n * characters: `select \"orders\"`, `insert \"public\".\"users\"`. A statement the\n * patterns cannot read leaves `table` unset.\n */\nexport function describeStatement(text: string): {\n\toperation?: string;\n\ttable?: string;\n} {\n\tconst head = text.length > 512 ? text.slice(0, 512) : text;\n\tconst operation = OPERATION.exec(head)?.[1]?.toLowerCase();\n\tconst table = TABLE.exec(head)?.[1]?.replace(/\"/g, '');\n\treturn {\n\t\t...(operation && { operation }),\n\t\t...(table && { table }),\n\t};\n}\n\n/**\n * A span around everything `client` runs — `<operation> <table>`, or\n * `db.query` when the statement does not say.\n *\n * The statement text goes on the span only for a parameterized query — values\n * passed separately, as Kysely always does — and truncated. Parameter values\n * never do. A bare string with no values could hold anything a caller\n * concatenated into it, so it gets no text at all.\n */\nfunction traceQueries(client: pg.PoolClient, connection: Attributes): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst config =\n\t\t\tfirst && typeof first === 'object'\n\t\t\t\t? (first as { text?: unknown; values?: unknown })\n\t\t\t\t: undefined;\n\t\tconst text =\n\t\t\ttypeof first === 'string'\n\t\t\t\t? first\n\t\t\t\t: typeof config?.text === 'string'\n\t\t\t\t\t? config.text\n\t\t\t\t\t: undefined;\n\t\tconst values = typeof first === 'string' ? rest[0] : config?.values;\n\t\tconst { operation, table } = text ? describeStatement(text) : {};\n\n\t\tconst span = trace\n\t\t\t.getTracer(TRACER)\n\t\t\t.startSpan(operation && table ? `${operation} ${table}` : 'db.query', {\n\t\t\t\tkind: SpanKind.CLIENT,\n\t\t\t\tattributes: {\n\t\t\t\t\t...connection,\n\t\t\t\t\t...(operation && { 'db.operation': operation }),\n\t\t\t\t\t...(table && { 'db.sql.table': table }),\n\t\t\t\t\t...(text &&\n\t\t\t\t\t\tArray.isArray(values) && {\n\t\t\t\t\t\t\t'db.statement':\n\t\t\t\t\t\t\t\ttext.length > MAX_STATEMENT_LENGTH\n\t\t\t\t\t\t\t\t\t? text.slice(0, MAX_STATEMENT_LENGTH)\n\t\t\t\t\t\t\t\t\t: text,\n\t\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t});\n\t\tconst end = (error?: unknown) => {\n\t\t\tif (error) {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t}\n\t\t\tspan.end();\n\t\t};\n\n\t\t// A callback, as `pg`'s own callback form takes it.\n\t\tconst last = rest[rest.length - 1];\n\t\tif (typeof last === 'function') {\n\t\t\tconst args = [...rest];\n\t\t\targs[args.length - 1] = (error: unknown, ...result: unknown[]) => {\n\t\t\t\tend(error);\n\t\t\t\treturn (last as (...a: unknown[]) => unknown)(error, ...result);\n\t\t\t};\n\t\t\treturn context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...args),\n\t\t\t);\n\t\t}\n\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...rest),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tend(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\t\t(result as Promise<unknown>).then(\n\t\t\t\t() => end(),\n\t\t\t\t(error) => end(error),\n\t\t\t);\n\t\t} else if (\n\t\t\tresult &&\n\t\t\ttypeof (result as { once?: unknown }).once === 'function'\n\t\t) {\n\t\t\t// A submittable — a cursor or a stream — ends when it says so.\n\t\t\tconst emitter = result as {\n\t\t\t\tonce(event: string, fn: (e?: unknown) => void): void;\n\t\t\t};\n\t\t\temitter.once('end', () => end());\n\t\t\temitter.once('error', (error) => end(error));\n\t\t} else {\n\t\t\tend();\n\t\t}\n\t\treturn result;\n\t}) as typeof client.query;\n}\n","/**\n * `KyselyDatabase` — a declared Postgres database, typed by its schema.\n *\n * It declares a logical database, a schema, and the roles that reach it, and\n * hands back a Kysely client built from the one URL the adapter supplied. It\n * names no cloud: `--target=aws` fills that URL from RDS, local dev from the\n * Postgres container.\n *\n * Transactions and RLS context are the execution wrapper's job — it opens the\n * transaction and puts it in `ctx.db`. This construct does not resolve\n * connections per request.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDEFAULT_POSTGRES_VERSION,\n\ttype Declaration,\n\ttype PostgresVersion,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport { Cache } from '../cache';\nimport type { Construct } from '../construct-interface';\nimport { openPool } from './pool';\n\n/** The schema a database uses when it does not say otherwise. */\nconst DEFAULT_SCHEMA = 'app';\n\n/**\n * Everything Kysely takes, plus what this construct declares.\n *\n * `dialect` is omitted because the construct owns it — it is built from the one\n * URL the adapter supplied, which is the whole point of the construct. The rest\n * of `KyselyConfig` (`plugins`, `log`) is the app's business and passes\n * straight through, so anything Kysely adds later arrives without being\n * tracked here.\n */\nexport interface KyselyDatabaseOptions extends Omit<KyselyConfig, 'dialect'> {\n\t/**\n\t * The schema, pinned on both roles' `search_path`.\n\t *\n\t * Defaults to `app` — the role the schema plays, rather than a restatement\n\t * of the database's own name, which reads correctly beside `auth` and\n\t * `pgboss` and keeps the application off `public`.\n\t */\n\tschema?: string;\n\t/**\n\t * Provision the owner/runtime role split. Defaults to on.\n\t *\n\t * Off falls back to the cluster's master credential in both URLs, giving up\n\t * the DDL/DML split and putting credentials that can drop a table into the\n\t * function's environment. A deliberate downgrade, not a default.\n\t */\n\troles?: boolean;\n\t/**\n\t * The Postgres major version to provision.\n\t *\n\t * Declared here so one statement reaches both targets. It was previously\n\t * set in two unrelated places — a container tag locally, nothing at all on\n\t * AWS (so Aurora chose) — which is how local came to run 18 while deployed\n\t * ran 17.7 with nothing recording the difference.\n\t *\n\t * Defaults to {@link DEFAULT_POSTGRES_VERSION}.\n\t */\n\tversion?: PostgresVersion;\n\t/**\n\t * End each query run inside a request with a comment naming what ran it —\n\t * `/*operation='POST /orders',request_id='…'*\\/` — so `pg_stat_activity`\n\t * and the server's logs can tie a query to its endpoint. Defaults to on.\n\t */\n\tqueryTags?: boolean;\n}\n\n/** What makes a construct derived rather than a database in its own right. */\ninterface DerivedFrom {\n\tkind: 'database-reader' | 'database-schema';\n\tof: string;\n\tschema?: string;\n}\n\n/**\n * @typeParam DB - the database's schema.\n * @typeParam TName - the canonical id. TypeScript has no partial\n * type-argument inference, so `new KyselyDatabase<OrdersDB>('orders')` leaves\n * this at its default and the service key widens to `string`. `db` still types\n * through `.database()`, which infers from the service.\n */\nexport class KyselyDatabase<DB = unknown, TName extends string = string>\n\timplements Construct<TName, Kysely<DB>>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, Kysely<DB>>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * build publishes and the key the client reads cannot drift.\n\t */\n\tprivate readonly config: { url: string; ownerUrl: string };\n\tprivate readonly schemaName: string;\n\tprivate readonly roles: boolean;\n\tprivate readonly version: PostgresVersion;\n\tprivate readonly derivedFrom?: DerivedFrom;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: KyselyDatabaseOptions = {},\n\t\tderivedFrom?: DerivedFrom,\n\t) {\n\t\t// Canonicalises, so `orders` and `Orders` are one construct rather than\n\t\t// two that collide. Throws on anything that cannot become a valid id.\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.config = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\townerUrl: provideKey(canonical, 'ownerUrl'),\n\t\t};\n\t\tthis.schemaName = options.schema ?? DEFAULT_SCHEMA;\n\t\tthis.roles = options.roles ?? true;\n\t\tthis.version = options.version ?? DEFAULT_POSTGRES_VERSION;\n\t\tthis.derivedFrom = derivedFrom;\n\n\t\t// A field, not a getter: service discovery caches by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\t// Forwards the whole options object — cherry-picking `envParser` strips\n\t\t\t// `context` and with it the request-scoped logger.\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\tif (this.derivedFrom) {\n\t\t\tconst { kind, of, schema } = this.derivedFrom;\n\n\t\t\treturn [\n\t\t\t\tkind === 'database-schema'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\tschema: schema ?? this.schemaName,\n\t\t\t\t\t\t\t// The runtime key alone — see the note below on the parent.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\t// A reader has no owner URL of its own — nothing migrates\n\t\t\t\t\t\t\t// through a read-only endpoint — so this is the one key.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t},\n\t\t\t];\n\t\t}\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'database',\n\t\t\t\tid: this.id,\n\t\t\t\tengine: 'postgres',\n\t\t\t\tschema: this.schemaName,\n\t\t\t\tversion: this.version,\n\t\t\t\t// One key, the runtime role's. `config` also holds the owner key and\n\t\t\t\t// it is deliberately absent here: a key in `provides` is a key an\n\t\t\t\t// edge can name, and nothing should be able to depend on DDL rights.\n\t\t\t\tprovides: [this.config.url],\n\t\t\t\t...(this.roles ? {} : { roles: false }),\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * A read-only endpoint on this database.\n\t *\n\t * Read-only is enforced by the reader role's grants rather than by which\n\t * endpoint it resolves to, so falling back to the writer where no replica\n\t * exists is safe rather than a silently writable connection behind a name\n\t * that says reader. There is no `writer()`: the database *is* the writer, so\n\t * a replica can never be reached by accident.\n\t *\n\t * The return type is narrower than this class on purpose — see\n\t * {@link ReadOnlyDatabase}.\n\t */\n\treader(): ReadOnlyDatabase<DB, `${TName}Reader`> {\n\t\treturn new KyselyDatabase<DB, `${TName}Reader`>(\n\t\t\t`${this.id}Reader` as ConstructName<`${TName}Reader`>,\n\t\t\tthis.options,\n\t\t\t{ kind: 'database-reader', of: this.id },\n\t\t);\n\t}\n\n\t/**\n\t * A cache that lives in this database.\n\t *\n\t * The same strengthening `schema()` is over a second database: `new\n\t * Cache('Sessions')` says the app caches and leaves where to the deployment,\n\t * while this says it caches *here* — which is a fact about the application\n\t * and so belongs in its code.\n\t *\n\t * What it buys beyond being explicit: the table's schema and the role that\n\t * reaches it come from this database rather than from a second convention,\n\t * and the backend no longer has to guess which database \"the database\" meant\n\t * when an app declares two.\n\t *\n\t * A cache is not a `KyselyDatabase`, so this returns a `Cache` — the client\n\t * is a key/value store, not a query builder, and typing it as the parent\n\t * would be a convenience that lies.\n\t */\n\tcache<TCache extends string = `${TName}Cache`>(\n\t\tid: ConstructName<TCache> = `${this.id}Cache` as ConstructName<TCache>,\n\t\toptions: { table?: string } = {},\n\t): Cache<TCache> {\n\t\treturn new Cache<TCache>(id, {\n\t\t\tof: this.id,\n\t\t\t...(options.table ? { table: options.table } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * A second schema in this database, with its own role(s) and its own URL —\n\t * so this database's role holds no grant on those tables at all.\n\t *\n\t * Typed separately because a tenant has its own tables: the point is that\n\t * `auth.selectFrom('sessions')` type-checks and\n\t * `orders.selectFrom('sessions')` does not.\n\t */\n\tschema<TenantDB, TTenant extends string>(\n\t\tid: ConstructName<TTenant>,\n\t\toptions: KyselyDatabaseOptions = {},\n\t): KyselyDatabase<TenantDB, TTenant> {\n\t\treturn new KyselyDatabase<TenantDB, TTenant>(id, options, {\n\t\t\tkind: 'database-schema',\n\t\t\tof: this.id,\n\t\t\tschema: options.schema ?? (id as string).toLowerCase(),\n\t\t});\n\t}\n\n\t/**\n\t * A connection as the *owner* role — the one that may create, alter and drop.\n\t *\n\t * A `Service` rather than part of the construct, and deliberately so: a\n\t * construct is what `.dependsOn()` accepts, and nothing should be able to\n\t * depend on this. A migrator asks for it by name; a handler cannot ask at\n\t * all, which is the security property the role split exists for.\n\t *\n\t * Falls back to the runtime URL where no owner URL was published — the\n\t * `roles: false` downgrade, where there is only one credential and it is the\n\t * cluster master's.\n\t */\n\tget owner(): Service<`${Uncapitalize<TName>}Owner`, Kysely<DB>> {\n\t\treturn {\n\t\t\tserviceName:\n\t\t\t\t`${serviceKey(this.id)}Owner` as `${Uncapitalize<TName>}Owner`,\n\t\t\tregister: (options) => this.connect(options, { owner: true }),\n\t\t};\n\t}\n\n\t/**\n\t * What this database's clients are built with besides a dialect — the\n\t * plugins and logging it was declared with.\n\t *\n\t * Public so that whatever opens a connection to it outside \\`connect()\\` —\n\t * a test's transaction — builds the same client. A test that dropped the\n\t * plugins would write \\`createdAt\\` where production writes \\`created_at\\`.\n\t */\n\tget clientConfig(): Omit<KyselyConfig, 'dialect'> {\n\t\t// Split what the manifest declared from what Kysely takes, so neither\n\t\t// leaks into the other: \\`schema\\`, \\`roles\\` and \\`version\\` describe\n\t\t// infrastructure and mean nothing to a client.\n\t\tconst {\n\t\t\tschema: _schema,\n\t\t\troles: _roles,\n\t\t\tversion: _version,\n\t\t\tqueryTags: _queryTags,\n\t\t\t...kysely\n\t\t} = this.options;\n\t\treturn kysely;\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Kysely<DB>> {\n\t\tconst { url, ownerUrl } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.config.url).string(),\n\t\t\t\townerUrl: get(this.config.ownerUrl).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\treturn new Kysely<DB>({\n\t\t\t...this.clientConfig,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\tpool: openPool(as.owner ? (ownerUrl ?? url) : url, {\n\t\t\t\t\tqueryTags: this.options.queryTags,\n\t\t\t\t}),\n\t\t\t}),\n\t\t});\n\t}\n}\n\n/**\n * A database you may read through, and derive nothing from.\n *\n * A reader is terminal in the graph, and this is that fact in the type system.\n * `DERIVES_FROM` gives `cache` and `database-schema` no `database-reader`\n * parent, and there is no reader of a reader — so `orders.reader().cache(…)`\n * has always been illegal, but it type-checked and failed later at\n * `assertDerivations`. That is a long way round to learn that a read-only\n * endpoint cannot own a table something writes to.\n *\n * Omitting the three deriving methods rather than making them throw keeps the\n * failure where it costs least: the editor, on the line that wrote it.\n *\n * The result is deliberately not assignable back to `KyselyDatabase` — a\n * reader is not one, and anything that genuinely needs the writer should say\n * so.\n */\nexport type ReadOnlyDatabase<DB, TName extends string> = Omit<\n\tKyselyDatabase<DB, TName>,\n\t'reader' | 'cache' | 'schema'\n>;\nexport { closeDatabasePools } from './pool';\n"],"mappings":";;;;;;;;;;AA6CA,MAAM,uBAAO,IAAI,IAAa;AAC9BA,iBAAAA,iBAAiB,mBAAmB,CAAC;;;;;;;;;;;AAYrC,SAAgB,SACf,KACA,UAA+B,CAAC,GACtB;CACV,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,aAAa,OAAO,aAAa,IAAI,aAAa;CACxD,OAAO,aAAa,OAAO,aAAa;CAExC,MAAM,OAAO,IAAI,GAAA,QAAG,KAAK;EACxB,kBAAkB,OAAO,SAAS;EAClC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AAC,OAAO,CAAC,CAAC,SAAS;EACvD,EAAE,CAAC,CACF,MAAM;EAER,OAAO,IAAIC,OAAAA,OAAW;GACrB,GAAG,KAAK;GACR,SAAS,IAAIC,OAAAA,gBAAgB,EAC5B,MAAM,SAAS,GAAG,QAAS,YAAY,MAAO,KAAK,EAClD,WAAW,KAAK,QAAQ,UACzB,CAAC,EACF,CAAC;EACF,CAAC;CACF;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry-DGcFlVpB.d.cts","names":["LambdaContext"],"sources":["../src/telemetry.ts"],"mappings":";;;;;UAWiB;;;;GAIf;;;;;UAMe;;;;EAIhB;;;;EAKA,SAASA;;;;;UAMO;;;;EAIhB;;;;EAKA;;;;EAKA,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;UA4BM;;;;;;;EAOhB,eAAe,SAAS,mBAAmB;;;;;;;EAQ3C,aAAa,KAAK,kBAAkB,UAAU;;;;;;;EAQ9C,eAAe,KAAK,kBAAkB,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry-DGcFlVpB.d.mts","names":["LambdaContext"],"sources":["../src/telemetry.ts"],"mappings":";;;;;UAWiB;;;;GAIf;;;;;UAMe;;;;EAIhB;;;;EAKA,SAASA;;;;;UAMO;;;;EAIhB;;;;EAKA;;;;EAKA,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;UA4BM;;;;;;;EAOhB,eAAe,SAAS,mBAAmB;;;;;;;EAQ3C,aAAa,KAAK,kBAAkB,UAAU;;;;;;;EAQ9C,eAAe,KAAK,kBAAkB,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tracing-3PpqRX07.cjs","names":["carrierFromAttributes","trace","SpanKind","SpanStatusCode"],"sources":["../src/tracing.ts"],"sourcesContent":["/**\n * Where the constructs meet OpenTelemetry, beyond the spans `@geekmidas/events`\n * starts for the brokers: the trace context in a Lambda's records, and the\n * spans around an `ExternalApi`'s client.\n *\n * Everything goes through the global API, so without a registered provider\n * none of it records anything.\n *\n * @module\n */\nimport { carrierFromAttributes, type TraceCarrier } from '@geekmidas/events';\nimport { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';\n\n/**\n * The trace context a Lambda record carries: an SQS record's message\n * attributes, an SNS record's, or those of the SNS envelope an SQS\n * subscription delivers in its body.\n */\nexport function recordCarrier(record: unknown): TraceCarrier | undefined {\n\tconst r = record as {\n\t\tmessageAttributes?: Record<string, unknown>;\n\t\tbody?: string;\n\t\tSns?: { MessageAttributes?: Record<string, unknown> };\n\t};\n\tif (r?.Sns) return carrierFromAttributes(r.Sns.MessageAttributes);\n\n\tconst own = carrierFromAttributes(r?.messageAttributes);\n\tif (own || typeof r?.body !== 'string') return own;\n\ttry {\n\t\tconst body = JSON.parse(r.body);\n\t\treturn body?.Type === 'Notification'\n\t\t\t? carrierFromAttributes(body.MessageAttributes)\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * `client`, with a span around each of its methods: `<api>.<method>`, carrying\n * the API's name. An outbound `fetch` the method makes is traced already, and\n * becomes this span's child, so the name is on the trace without anything\n * knowing which URL belongs to which API.\n *\n * Only the client's own methods: what they return is the client's business.\n * Methods are called on the client itself, never on the proxy, so private\n * fields keep working.\n */\nexport function traceClient<T>(\n\tapi: string,\n\tclient: T,\n\tattributes: Record<string, string> = {},\n): T {\n\tif (!client || (typeof client !== 'object' && typeof client !== 'function')) {\n\t\treturn client;\n\t}\n\tconst wrapped = new Map<PropertyKey, unknown>();\n\treturn new Proxy(client as object, {\n\t\tget(target, property, receiver) {\n\t\t\tconst value = Reflect.get(target, property, receiver);\n\t\t\tif (typeof value !== 'function' || typeof property === 'symbol') {\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\tif (property === 'constructor' || property === 'then') return value;\n\n\t\t\tconst cached = wrapped.get(property);\n\t\t\tif (cached && (cached as { original?: unknown }).original === value) {\n\t\t\t\treturn cached;\n\t\t\t}\n\t\t\tconst traced = Object.assign(\n\t\t\t\t(...args: unknown[]) =>\n\t\t\t\t\tcallTraced(api, property, attributes, () =>\n\t\t\t\t\t\t(value as (...a: unknown[]) => unknown).apply(target, args),\n\t\t\t\t\t),\n\t\t\t\t{ original: value },\n\t\t\t);\n\t\t\twrapped.set(property, traced);\n\t\t\treturn traced;\n\t\t},\n\t}) as T;\n}\n\nfunction callTraced(\n\tapi: string,\n\tmethod: string,\n\tattributes: Record<string, string>,\n\tcall: () => unknown,\n): unknown {\n\treturn trace.getTracer('@geekmidas/constructs').startActiveSpan(\n\t\t`${api}.${method}`,\n\t\t{\n\t\t\tkind: SpanKind.INTERNAL,\n\t\t\tattributes: {\n\t\t\t\t'gkm.external_api.name': api,\n\t\t\t\t'gkm.external_api.method': method,\n\t\t\t\t...attributes,\n\t\t\t},\n\t\t},\n\t\t(span) => {\n\t\t\tconst fail = (error: unknown) => {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\tspan.end();\n\t\t\t};\n\t\t\tlet result: unknown;\n\t\t\ttry {\n\t\t\t\tresult = call();\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// Only a native promise is waited on, and the caller gets it back as\n\t\t\t// it was: a lazy thenable runs on `then`, and a promise subclass has\n\t\t\t// methods a chained promise would not.\n\t\t\tif (result instanceof Promise) {\n\t\t\t\tresult.then(\n\t\t\t\t\t() => span.end(),\n\t\t\t\t\t(error) => fail(error),\n\t\t\t\t);\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tspan.end();\n\t\t\treturn result;\n\t\t},\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAgB,cAAc,QAA2C;CACxE,MAAM,IAAI;CAKV,IAAI,GAAG,KAAK,QAAA,GAAOA,kBAAAA,sBAAAA,CAAsB,EAAE,IAAI,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AAK;GACtD,KAAK,UAAU,EAAE,MAAMC,mBAAAA,eAAe,MAAM,CAAC;GAC7C,KAAK,IAAI;EACV;EACA,IAAI;EACJ,IAAI;GACH,SAAS,KAAK;EACf,SAAS,OAAO;GACf,KAAK,KAAK;GACV,MAAM;EACP;EAIA,IAAI,kBAAkB,SAAS;GAC9B,OAAO,WACA,KAAK,IAAI,IACd,UAAU,KAAK,KAAK,CACtB;GACA,OAAO;EACR;EACA,KAAK,IAAI;EACT,OAAO;CACR,CACD;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tracing-DbcPuhEy.mjs","names":[],"sources":["../src/tracing.ts"],"sourcesContent":["/**\n * Where the constructs meet OpenTelemetry, beyond the spans `@geekmidas/events`\n * starts for the brokers: the trace context in a Lambda's records, and the\n * spans around an `ExternalApi`'s client.\n *\n * Everything goes through the global API, so without a registered provider\n * none of it records anything.\n *\n * @module\n */\nimport { carrierFromAttributes, type TraceCarrier } from '@geekmidas/events';\nimport { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';\n\n/**\n * The trace context a Lambda record carries: an SQS record's message\n * attributes, an SNS record's, or those of the SNS envelope an SQS\n * subscription delivers in its body.\n */\nexport function recordCarrier(record: unknown): TraceCarrier | undefined {\n\tconst r = record as {\n\t\tmessageAttributes?: Record<string, unknown>;\n\t\tbody?: string;\n\t\tSns?: { MessageAttributes?: Record<string, unknown> };\n\t};\n\tif (r?.Sns) return carrierFromAttributes(r.Sns.MessageAttributes);\n\n\tconst own = carrierFromAttributes(r?.messageAttributes);\n\tif (own || typeof r?.body !== 'string') return own;\n\ttry {\n\t\tconst body = JSON.parse(r.body);\n\t\treturn body?.Type === 'Notification'\n\t\t\t? carrierFromAttributes(body.MessageAttributes)\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * `client`, with a span around each of its methods: `<api>.<method>`, carrying\n * the API's name. An outbound `fetch` the method makes is traced already, and\n * becomes this span's child, so the name is on the trace without anything\n * knowing which URL belongs to which API.\n *\n * Only the client's own methods: what they return is the client's business.\n * Methods are called on the client itself, never on the proxy, so private\n * fields keep working.\n */\nexport function traceClient<T>(\n\tapi: string,\n\tclient: T,\n\tattributes: Record<string, string> = {},\n): T {\n\tif (!client || (typeof client !== 'object' && typeof client !== 'function')) {\n\t\treturn client;\n\t}\n\tconst wrapped = new Map<PropertyKey, unknown>();\n\treturn new Proxy(client as object, {\n\t\tget(target, property, receiver) {\n\t\t\tconst value = Reflect.get(target, property, receiver);\n\t\t\tif (typeof value !== 'function' || typeof property === 'symbol') {\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\tif (property === 'constructor' || property === 'then') return value;\n\n\t\t\tconst cached = wrapped.get(property);\n\t\t\tif (cached && (cached as { original?: unknown }).original === value) {\n\t\t\t\treturn cached;\n\t\t\t}\n\t\t\tconst traced = Object.assign(\n\t\t\t\t(...args: unknown[]) =>\n\t\t\t\t\tcallTraced(api, property, attributes, () =>\n\t\t\t\t\t\t(value as (...a: unknown[]) => unknown).apply(target, args),\n\t\t\t\t\t),\n\t\t\t\t{ original: value },\n\t\t\t);\n\t\t\twrapped.set(property, traced);\n\t\t\treturn traced;\n\t\t},\n\t}) as T;\n}\n\nfunction callTraced(\n\tapi: string,\n\tmethod: string,\n\tattributes: Record<string, string>,\n\tcall: () => unknown,\n): unknown {\n\treturn trace.getTracer('@geekmidas/constructs').startActiveSpan(\n\t\t`${api}.${method}`,\n\t\t{\n\t\t\tkind: SpanKind.INTERNAL,\n\t\t\tattributes: {\n\t\t\t\t'gkm.external_api.name': api,\n\t\t\t\t'gkm.external_api.method': method,\n\t\t\t\t...attributes,\n\t\t\t},\n\t\t},\n\t\t(span) => {\n\t\t\tconst fail = (error: unknown) => {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\tspan.end();\n\t\t\t};\n\t\t\tlet result: unknown;\n\t\t\ttry {\n\t\t\t\tresult = call();\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// Only a native promise is waited on, and the caller gets it back as\n\t\t\t// it was: a lazy thenable runs on `then`, and a promise subclass has\n\t\t\t// methods a chained promise would not.\n\t\t\tif (result instanceof Promise) {\n\t\t\t\tresult.then(\n\t\t\t\t\t() => span.end(),\n\t\t\t\t\t(error) => fail(error),\n\t\t\t\t);\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tspan.end();\n\t\t\treturn result;\n\t\t},\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAgB,cAAc,QAA2C;CACxE,MAAM,IAAI;CAKV,IAAI,GAAG,KAAK,OAAO,sBAAsB,EAAE,IAAI,iBAAiB;CAEhE,MAAM,MAAM,sBAAsB,GAAG,iBAAiB;CACtD,IAAI,OAAO,OAAO,GAAG,SAAS,UAAU,OAAO;CAC/C,IAAI;EACH,MAAM,OAAO,KAAK,MAAM,EAAE,IAAI;EAC9B,OAAO,MAAM,SAAS,iBACnB,sBAAsB,KAAK,iBAAiB,IAC5C,KAAA;CACJ,QAAQ;EACP;CACD;AACD;;;;;;;;;;;AAYA,SAAgB,YACf,KACA,QACA,aAAqC,CAAC,GAClC;CACJ,IAAI,CAAC,UAAW,OAAO,WAAW,YAAY,OAAO,WAAW,YAC/D,OAAO;CAER,MAAM,0BAAU,IAAI,IAA0B;CAC9C,OAAO,IAAI,MAAM,QAAkB,EAClC,IAAI,QAAQ,UAAU,UAAU;EAC/B,MAAM,QAAQ,QAAQ,IAAI,QAAQ,UAAU,QAAQ;EACpD,IAAI,OAAO,UAAU,cAAc,OAAO,aAAa,UACtD,OAAO;EAER,IAAI,aAAa,iBAAiB,aAAa,QAAQ,OAAO;EAE9D,MAAM,SAAS,QAAQ,IAAI,QAAQ;EACnC,IAAI,UAAW,OAAkC,aAAa,OAC7D,OAAO;EAER,MAAM,SAAS,OAAO,QACpB,GAAG,SACH,WAA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