@geekmidas/constructs 10.0.0-alpha.53 → 10.0.0-alpha.55
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/{HonoEndpointAdaptor-ZDmoZ5LJ.cjs → HonoEndpointAdaptor-XyxwoFnE.cjs} +4 -3
- package/dist/HonoEndpointAdaptor-XyxwoFnE.cjs.map +1 -0
- package/dist/{HonoEndpointAdaptor-DW4q9db0.mjs → HonoEndpointAdaptor-ja49poBI.mjs} +4 -3
- package/dist/HonoEndpointAdaptor-ja49poBI.mjs.map +1 -0
- package/dist/adaptors/aws.cjs +10 -4
- package/dist/adaptors/aws.cjs.map +1 -1
- package/dist/adaptors/aws.d.cts.map +1 -1
- package/dist/adaptors/aws.d.mts.map +1 -1
- package/dist/adaptors/aws.mjs +10 -4
- package/dist/adaptors/aws.mjs.map +1 -1
- package/dist/adaptors/hono.cjs +1 -1
- package/dist/adaptors/hono.d.cts.map +1 -1
- package/dist/adaptors/hono.d.mts.map +1 -1
- package/dist/adaptors/hono.mjs +1 -1
- package/dist/adaptors/testing.cjs +14 -6
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +1 -1
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +1 -1
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +13 -5
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/crons/index.cjs +3 -2
- package/dist/crons/index.cjs.map +1 -1
- package/dist/crons/index.mjs +3 -2
- package/dist/crons/index.mjs.map +1 -1
- package/dist/database/kysely.cjs +3 -205
- package/dist/database/kysely.d.cts +2 -2
- package/dist/database/kysely.d.mts +2 -2
- package/dist/database/kysely.mjs +2 -203
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +23 -1
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +23 -1
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2 -1
- package/dist/{kysely-DTnkZsub.d.cts → kysely-BEm5sDlU.d.cts} +16 -2
- package/dist/kysely-BEm5sDlU.d.cts.map +1 -0
- package/dist/kysely-BRzzawr2.cjs +301 -0
- package/dist/kysely-BRzzawr2.cjs.map +1 -0
- package/dist/kysely-BYfM6Zby.mjs +288 -0
- package/dist/kysely-BYfM6Zby.mjs.map +1 -0
- package/dist/{kysely-Bqov3fwv.d.mts → kysely-CjuvdXEV.d.mts} +16 -2
- package/dist/kysely-CjuvdXEV.d.mts.map +1 -0
- package/dist/shutdown-BMJmAhSt.cjs +38 -0
- package/dist/shutdown-BMJmAhSt.cjs.map +1 -0
- package/dist/shutdown-C7xa8x9S.mjs +27 -0
- package/dist/shutdown-C7xa8x9S.mjs.map +1 -0
- package/dist/subscribers/index.cjs +2 -1
- package/dist/subscribers/index.cjs.map +1 -1
- package/dist/subscribers/index.mjs +2 -1
- package/dist/subscribers/index.mjs.map +1 -1
- package/package.json +31 -31
- package/dist/HonoEndpointAdaptor-DW4q9db0.mjs.map +0 -1
- package/dist/HonoEndpointAdaptor-ZDmoZ5LJ.cjs.map +0 -1
- package/dist/database/kysely.cjs.map +0 -1
- package/dist/database/kysely.mjs.map +0 -1
- package/dist/kysely-Bqov3fwv.d.mts.map +0 -1
- package/dist/kysely-DTnkZsub.d.cts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-BYfM6Zby.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 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 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/** 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({ error }, 'Idle database connection lost');\n\t\telse console.warn('Idle database connection lost:', error.message);\n\t});\n\tif (options.queryTags !== false) {\n\t\tpool.on('connect', (client) => tagQueries(client));\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 * `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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAM,uBAAO,IAAI,IAAa;AAC9B,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,GAAG,KAAK;EACxB,kBAAkB,OAAO,SAAS;EAClC,GAAI,aAAa,EAAE,SAAS,kBAAkB,aAAa,IAAI,CAAC;EAChE,2BAA2B,gBAAgB;CAC5C,CAAC;CAED,KAAK,GAAG,UAAU,UAAU;EAC3B,MAAM,SAAS,sBAAsB,CAAC,EAAE;EACxC,IAAI,QAAQ,OAAO,KAAK,EAAE,MAAM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, Declaration, PostgresVersion } from "@geekmidas/manifest";
|
|
4
4
|
import { Kysely, KyselyConfig } from "kysely";
|
|
5
5
|
import { Service } from "@geekmidas/services";
|
|
6
|
+
import pg from "pg";
|
|
7
|
+
//#region src/database/pool.d.ts
|
|
8
|
+
/**
|
|
9
|
+
* End every pool opened, waiting for checked-out connections to come back.
|
|
10
|
+
* For a server's shutdown, after it has stopped taking requests.
|
|
11
|
+
*/
|
|
12
|
+
declare function closeDatabasePools(): Promise<void>;
|
|
13
|
+
//#endregion
|
|
6
14
|
//#region src/database/kysely.d.ts
|
|
7
15
|
/**
|
|
8
16
|
* Everything Kysely takes, plus what this construct declares.
|
|
@@ -41,6 +49,12 @@ interface KyselyDatabaseOptions extends Omit<KyselyConfig, 'dialect'> {
|
|
|
41
49
|
* Defaults to {@link DEFAULT_POSTGRES_VERSION}.
|
|
42
50
|
*/
|
|
43
51
|
version?: PostgresVersion;
|
|
52
|
+
/**
|
|
53
|
+
* End each query run inside a request with a comment naming what ran it —
|
|
54
|
+
* `/*operation='POST /orders',request_id='…'*\/` — so `pg_stat_activity`
|
|
55
|
+
* and the server's logs can tie a query to its endpoint. Defaults to on.
|
|
56
|
+
*/
|
|
57
|
+
queryTags?: boolean;
|
|
44
58
|
}
|
|
45
59
|
/** What makes a construct derived rather than a database in its own right. */
|
|
46
60
|
interface DerivedFrom {
|
|
@@ -155,5 +169,5 @@ declare class KyselyDatabase<DB = unknown, TName extends string = string> implem
|
|
|
155
169
|
*/
|
|
156
170
|
type ReadOnlyDatabase<DB, TName extends string> = Omit<KyselyDatabase<DB, TName>, 'reader' | 'cache' | 'schema'>;
|
|
157
171
|
//#endregion
|
|
158
|
-
export { KyselyDatabaseOptions as n, ReadOnlyDatabase as r, KyselyDatabase as t };
|
|
159
|
-
//# sourceMappingURL=kysely-
|
|
172
|
+
export { closeDatabasePools as i, KyselyDatabaseOptions as n, ReadOnlyDatabase as r, KyselyDatabase as t };
|
|
173
|
+
//# sourceMappingURL=kysely-CjuvdXEV.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-CjuvdXEV.d.mts","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"mappings":";;;;;;;;;;;iBAiFsB,sBAAsB;;;;;;;;;;;;UCzC3B,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"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region src/shutdown.ts
|
|
2
|
+
const key = Symbol.for("@geekmidas/constructs/shutdown");
|
|
3
|
+
const registry = globalThis;
|
|
4
|
+
registry[key] ??= /* @__PURE__ */ new Set();
|
|
5
|
+
const hooks = registry[key];
|
|
6
|
+
/** Run `hook` when the server shuts down. Returns a function that removes it. */
|
|
7
|
+
function onShutdown(hook) {
|
|
8
|
+
hooks.add(hook);
|
|
9
|
+
return () => hooks.delete(hook);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Run every registered hook, together, and wait for them. A hook that fails is
|
|
13
|
+
* reported to `onError` and does not stop the others.
|
|
14
|
+
*/
|
|
15
|
+
async function runShutdownHooks(onError = () => {}) {
|
|
16
|
+
await Promise.all([...hooks].map(async (hook) => {
|
|
17
|
+
try {
|
|
18
|
+
await hook();
|
|
19
|
+
} catch (error) {
|
|
20
|
+
onError(error);
|
|
21
|
+
}
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
Object.defineProperty(exports, "onShutdown", {
|
|
26
|
+
enumerable: true,
|
|
27
|
+
get: function() {
|
|
28
|
+
return onShutdown;
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
Object.defineProperty(exports, "runShutdownHooks", {
|
|
32
|
+
enumerable: true,
|
|
33
|
+
get: function() {
|
|
34
|
+
return runShutdownHooks;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=shutdown-BMJmAhSt.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shutdown-BMJmAhSt.cjs","names":[],"sources":["../src/shutdown.ts"],"sourcesContent":["/**\n * What a server releases when it stops: the connections constructs opened.\n *\n * A construct that holds something open — a database's pool — registers how to\n * close it here, and the generated server runs every hook once it has stopped\n * taking requests. Without that, a rolling deploy has the old task and the new\n * one both holding connections until the old process dies.\n *\n * Kept free of any driver import so the server entry can always import it,\n * whether or not the app has a database.\n */\n\ntype ShutdownHook = () => Promise<void> | void;\n\n// On globalThis, as Credentials are: a package loaded twice (ESM and CJS)\n// would otherwise keep two registries, and the server would run the empty one.\nconst key = Symbol.for('@geekmidas/constructs/shutdown');\nconst registry = globalThis as Record<symbol, Set<ShutdownHook> | undefined>;\nregistry[key] ??= new Set<ShutdownHook>();\nconst hooks = registry[key];\n\n/** Run `hook` when the server shuts down. Returns a function that removes it. */\nexport function onShutdown(hook: ShutdownHook): () => void {\n\thooks.add(hook);\n\treturn () => hooks.delete(hook);\n}\n\n/**\n * Run every registered hook, together, and wait for them. A hook that fails is\n * reported to `onError` and does not stop the others.\n */\nexport async function runShutdownHooks(\n\tonError: (error: unknown) => void = () => {},\n): Promise<void> {\n\tawait Promise.all(\n\t\t[...hooks].map(async (hook) => {\n\t\t\ttry {\n\t\t\t\tawait hook();\n\t\t\t} catch (error) {\n\t\t\t\tonError(error);\n\t\t\t}\n\t\t}),\n\t);\n}\n"],"mappings":";AAgBA,MAAM,MAAM,OAAO,IAAI,gCAAgC;AACvD,MAAM,WAAW;AACjB,SAAS,yBAAS,IAAI,IAAkB;AACxC,MAAM,QAAQ,SAAS;;AAGvB,SAAgB,WAAW,MAAgC;CAC1D,MAAM,IAAI,IAAI;CACd,aAAa,MAAM,OAAO,IAAI;AAC/B;;;;;AAMA,eAAsB,iBACrB,gBAA0C,CAAC,GAC3B;CAChB,MAAM,QAAQ,IACb,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,OAAO,SAAS;EAC9B,IAAI;GACH,MAAM,KAAK;EACZ,SAAS,OAAO;GACf,QAAQ,KAAK;EACd;CACD,CAAC,CACF;AACD"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
//#region src/shutdown.ts
|
|
2
|
+
const key = Symbol.for("@geekmidas/constructs/shutdown");
|
|
3
|
+
const registry = globalThis;
|
|
4
|
+
registry[key] ??= /* @__PURE__ */ new Set();
|
|
5
|
+
const hooks = registry[key];
|
|
6
|
+
/** Run `hook` when the server shuts down. Returns a function that removes it. */
|
|
7
|
+
function onShutdown(hook) {
|
|
8
|
+
hooks.add(hook);
|
|
9
|
+
return () => hooks.delete(hook);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Run every registered hook, together, and wait for them. A hook that fails is
|
|
13
|
+
* reported to `onError` and does not stop the others.
|
|
14
|
+
*/
|
|
15
|
+
async function runShutdownHooks(onError = () => {}) {
|
|
16
|
+
await Promise.all([...hooks].map(async (hook) => {
|
|
17
|
+
try {
|
|
18
|
+
await hook();
|
|
19
|
+
} catch (error) {
|
|
20
|
+
onError(error);
|
|
21
|
+
}
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
export { runShutdownHooks as n, onShutdown as t };
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=shutdown-C7xa8x9S.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shutdown-C7xa8x9S.mjs","names":[],"sources":["../src/shutdown.ts"],"sourcesContent":["/**\n * What a server releases when it stops: the connections constructs opened.\n *\n * A construct that holds something open — a database's pool — registers how to\n * close it here, and the generated server runs every hook once it has stopped\n * taking requests. Without that, a rolling deploy has the old task and the new\n * one both holding connections until the old process dies.\n *\n * Kept free of any driver import so the server entry can always import it,\n * whether or not the app has a database.\n */\n\ntype ShutdownHook = () => Promise<void> | void;\n\n// On globalThis, as Credentials are: a package loaded twice (ESM and CJS)\n// would otherwise keep two registries, and the server would run the empty one.\nconst key = Symbol.for('@geekmidas/constructs/shutdown');\nconst registry = globalThis as Record<symbol, Set<ShutdownHook> | undefined>;\nregistry[key] ??= new Set<ShutdownHook>();\nconst hooks = registry[key];\n\n/** Run `hook` when the server shuts down. Returns a function that removes it. */\nexport function onShutdown(hook: ShutdownHook): () => void {\n\thooks.add(hook);\n\treturn () => hooks.delete(hook);\n}\n\n/**\n * Run every registered hook, together, and wait for them. A hook that fails is\n * reported to `onError` and does not stop the others.\n */\nexport async function runShutdownHooks(\n\tonError: (error: unknown) => void = () => {},\n): Promise<void> {\n\tawait Promise.all(\n\t\t[...hooks].map(async (hook) => {\n\t\t\ttry {\n\t\t\t\tawait hook();\n\t\t\t} catch (error) {\n\t\t\t\tonError(error);\n\t\t\t}\n\t\t}),\n\t);\n}\n"],"mappings":";AAgBA,MAAM,MAAM,OAAO,IAAI,gCAAgC;AACvD,MAAM,WAAW;AACjB,SAAS,yBAAS,IAAI,IAAkB;AACxC,MAAM,QAAQ,SAAS;;AAGvB,SAAgB,WAAW,MAAgC;CAC1D,MAAM,IAAI,IAAI;CACd,aAAa,MAAM,OAAO,IAAI;AAC/B;;;;;AAMA,eAAsB,iBACrB,gBAA0C,CAAC,GAC3B;CAChB,MAAM,QAAQ,IACb,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,OAAO,SAAS;EAC9B,IAAI;GACH,MAAM,KAAK;EACZ,SAAS,OAAO;GACf,QAAQ,KAAK;EACd;CACD,CAAC,CACF;AACD"}
|
|
@@ -68,7 +68,8 @@ var SnsPushSubscriberAdaptor = class {
|
|
|
68
68
|
await (0, _geekmidas_services.runWithRequestContext)({
|
|
69
69
|
logger,
|
|
70
70
|
requestId,
|
|
71
|
-
startTime: Date.now()
|
|
71
|
+
startTime: Date.now(),
|
|
72
|
+
operation: `subscriber ${this.subscriber.topicName ?? "sns"}`
|
|
72
73
|
}, async () => {
|
|
73
74
|
try {
|
|
74
75
|
const { services, db } = await require_runSubscriber.subscriberContext(this.subscriber, this.envParser);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["verifySnsMessage","confirmSnsSubscription","runWithRequestContext","subscriberContext","subscribedEvents","toSnsEvent","runSubscriber","wrapError"],"sources":["../../src/subscribers/SnsPushSubscriberAdaptor.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { wrapError } from '@geekmidas/errors';\nimport {\n\tconfirmSnsSubscription,\n\ttype SnsHttpMessage,\n\ttoSnsEvent,\n\tverifySnsMessage,\n} from '@geekmidas/events/sns';\nimport { runWithRequestContext } from '@geekmidas/services';\nimport {\n\trunSubscriber,\n\tsubscribedEvents,\n\tsubscriberContext,\n} from './runSubscriber';\nimport type { Subscriber } from './Subscriber';\n\nexport interface SnsPushOptions {\n\t/** The topic this subscriber is subscribed to. Anything else is refused. */\n\ttopicArn: string;\n\t/**\n\t * Verify each message's signature. Off only against an emulator, which\n\t * signs nothing — decided by the connection string's endpoint, never by\n\t * anything the request says about itself.\n\t */\n\tverify: boolean;\n\t/**\n\t * The emulator's address, as this server was configured with it. An\n\t * emulator names itself in `SubscribeURL` by the port it listens on inside\n\t * its container, which is not the port published to the host — so against\n\t * one, the confirmation is sent here instead. From configuration, never\n\t * from the request.\n\t */\n\temulatorEndpoint?: string;\n}\n\n/** What to answer SNS with. A non-2xx tells SNS to retry. */\nexport interface SnsPushResponse {\n\tstatus: 200 | 400 | 403 | 500;\n\tbody: { status: string; error?: string };\n}\n\n/**\n * A topic subscriber run by SNS pushing to an HTTP endpoint, rather than by a\n * poller.\n *\n * The notification is read as the Lambda event SNS would have invoked a\n * function with, and run through the same parsing, services and handler as the\n * Lambda adaptor — without its middy wrapper, which is Lambda's alone: a\n * server serving this route has no reason to install `@middy/core`.\n */\nexport class SnsPushSubscriberAdaptor {\n\tconstructor(\n\t\tprivate readonly envParser: EnvironmentParser<{}>,\n\t\treadonly subscriber: Subscriber<any, any, any, any, any, any, any>,\n\t\tprivate readonly options: SnsPushOptions,\n\t) {}\n\n\tasync handle(body: unknown): Promise<SnsPushResponse> {\n\t\tconst message = body as SnsHttpMessage;\n\t\tif (typeof message?.Type !== 'string' || !message.TopicArn) {\n\t\t\treturn refuse(400, 'not an SNS message');\n\t\t}\n\t\t// Checked before the signature: a genuine message for another topic is\n\t\t// still not this subscriber's to confirm or to handle.\n\t\tif (message.TopicArn !== this.options.topicArn) {\n\t\t\treturn refuse(403, `not subscribed to ${message.TopicArn}`);\n\t\t}\n\n\t\tif (this.options.verify) {\n\t\t\ttry {\n\t\t\t\tawait verifySnsMessage(message);\n\t\t\t} catch (error) {\n\t\t\t\tthis.subscriber.logger.warn(\n\t\t\t\t\t{ error, topicArn: message.TopicArn },\n\t\t\t\t\t'Refused an SNS message that did not verify',\n\t\t\t\t);\n\t\t\t\treturn refuse(403, (error as Error).name);\n\t\t\t}\n\t\t}\n\n\t\tswitch (message.Type) {\n\t\t\tcase 'SubscriptionConfirmation':\n\t\t\t\tawait confirmSnsSubscription(\n\t\t\t\t\tthis.options.emulatorEndpoint && message.SubscribeURL\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...message,\n\t\t\t\t\t\t\t\tSubscribeURL: throughEndpoint(\n\t\t\t\t\t\t\t\t\tmessage.SubscribeURL,\n\t\t\t\t\t\t\t\t\tthis.options.emulatorEndpoint,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: message,\n\t\t\t\t);\n\t\t\t\tthis.subscriber.logger.info(\n\t\t\t\t\t{ topicArn: message.TopicArn },\n\t\t\t\t\t'Confirmed SNS subscription',\n\t\t\t\t);\n\t\t\t\treturn { status: 200, body: { status: 'confirmed' } };\n\t\t\tcase 'Notification':\n\t\t\t\ttry {\n\t\t\t\t\tawait this.notify(message);\n\t\t\t\t\treturn { status: 200, body: { status: 'ok' } };\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Already logged. A 500 makes SNS retry, which is the point of\n\t\t\t\t\t// answering at all.\n\t\t\t\t\treturn refuse(500, (error as Error).name);\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn { status: 200, body: { status: 'ignored' } };\n\t\t}\n\t}\n\n\tprivate async notify(message: SnsHttpMessage): Promise<void> {\n\t\tconst requestId = message.MessageId;\n\t\tconst logger = this.subscriber.logger.child({ requestId });\n\n\t\tawait runWithRequestContext(\n\t\t\t{
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["verifySnsMessage","confirmSnsSubscription","runWithRequestContext","subscriberContext","subscribedEvents","toSnsEvent","runSubscriber","wrapError"],"sources":["../../src/subscribers/SnsPushSubscriberAdaptor.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { wrapError } from '@geekmidas/errors';\nimport {\n\tconfirmSnsSubscription,\n\ttype SnsHttpMessage,\n\ttoSnsEvent,\n\tverifySnsMessage,\n} from '@geekmidas/events/sns';\nimport { runWithRequestContext } from '@geekmidas/services';\nimport {\n\trunSubscriber,\n\tsubscribedEvents,\n\tsubscriberContext,\n} from './runSubscriber';\nimport type { Subscriber } from './Subscriber';\n\nexport interface SnsPushOptions {\n\t/** The topic this subscriber is subscribed to. Anything else is refused. */\n\ttopicArn: string;\n\t/**\n\t * Verify each message's signature. Off only against an emulator, which\n\t * signs nothing — decided by the connection string's endpoint, never by\n\t * anything the request says about itself.\n\t */\n\tverify: boolean;\n\t/**\n\t * The emulator's address, as this server was configured with it. An\n\t * emulator names itself in `SubscribeURL` by the port it listens on inside\n\t * its container, which is not the port published to the host — so against\n\t * one, the confirmation is sent here instead. From configuration, never\n\t * from the request.\n\t */\n\temulatorEndpoint?: string;\n}\n\n/** What to answer SNS with. A non-2xx tells SNS to retry. */\nexport interface SnsPushResponse {\n\tstatus: 200 | 400 | 403 | 500;\n\tbody: { status: string; error?: string };\n}\n\n/**\n * A topic subscriber run by SNS pushing to an HTTP endpoint, rather than by a\n * poller.\n *\n * The notification is read as the Lambda event SNS would have invoked a\n * function with, and run through the same parsing, services and handler as the\n * Lambda adaptor — without its middy wrapper, which is Lambda's alone: a\n * server serving this route has no reason to install `@middy/core`.\n */\nexport class SnsPushSubscriberAdaptor {\n\tconstructor(\n\t\tprivate readonly envParser: EnvironmentParser<{}>,\n\t\treadonly subscriber: Subscriber<any, any, any, any, any, any, any>,\n\t\tprivate readonly options: SnsPushOptions,\n\t) {}\n\n\tasync handle(body: unknown): Promise<SnsPushResponse> {\n\t\tconst message = body as SnsHttpMessage;\n\t\tif (typeof message?.Type !== 'string' || !message.TopicArn) {\n\t\t\treturn refuse(400, 'not an SNS message');\n\t\t}\n\t\t// Checked before the signature: a genuine message for another topic is\n\t\t// still not this subscriber's to confirm or to handle.\n\t\tif (message.TopicArn !== this.options.topicArn) {\n\t\t\treturn refuse(403, `not subscribed to ${message.TopicArn}`);\n\t\t}\n\n\t\tif (this.options.verify) {\n\t\t\ttry {\n\t\t\t\tawait verifySnsMessage(message);\n\t\t\t} catch (error) {\n\t\t\t\tthis.subscriber.logger.warn(\n\t\t\t\t\t{ error, topicArn: message.TopicArn },\n\t\t\t\t\t'Refused an SNS message that did not verify',\n\t\t\t\t);\n\t\t\t\treturn refuse(403, (error as Error).name);\n\t\t\t}\n\t\t}\n\n\t\tswitch (message.Type) {\n\t\t\tcase 'SubscriptionConfirmation':\n\t\t\t\tawait confirmSnsSubscription(\n\t\t\t\t\tthis.options.emulatorEndpoint && message.SubscribeURL\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...message,\n\t\t\t\t\t\t\t\tSubscribeURL: throughEndpoint(\n\t\t\t\t\t\t\t\t\tmessage.SubscribeURL,\n\t\t\t\t\t\t\t\t\tthis.options.emulatorEndpoint,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: message,\n\t\t\t\t);\n\t\t\t\tthis.subscriber.logger.info(\n\t\t\t\t\t{ topicArn: message.TopicArn },\n\t\t\t\t\t'Confirmed SNS subscription',\n\t\t\t\t);\n\t\t\t\treturn { status: 200, body: { status: 'confirmed' } };\n\t\t\tcase 'Notification':\n\t\t\t\ttry {\n\t\t\t\t\tawait this.notify(message);\n\t\t\t\t\treturn { status: 200, body: { status: 'ok' } };\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Already logged. A 500 makes SNS retry, which is the point of\n\t\t\t\t\t// answering at all.\n\t\t\t\t\treturn refuse(500, (error as Error).name);\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn { status: 200, body: { status: 'ignored' } };\n\t\t}\n\t}\n\n\tprivate async notify(message: SnsHttpMessage): Promise<void> {\n\t\tconst requestId = message.MessageId;\n\t\tconst logger = this.subscriber.logger.child({ requestId });\n\n\t\tawait runWithRequestContext(\n\t\t\t{\n\t\t\t\tlogger,\n\t\t\t\trequestId,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\toperation: `subscriber ${this.subscriber.topicName ?? 'sns'}`,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst { services, db } = await subscriberContext(\n\t\t\t\t\t\tthis.subscriber,\n\t\t\t\t\t\tthis.envParser,\n\t\t\t\t\t);\n\t\t\t\t\tconst events = subscribedEvents(\n\t\t\t\t\t\tthis.subscriber,\n\t\t\t\t\t\ttoSnsEvent(message),\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t);\n\t\t\t\t\tawait runSubscriber(this.subscriber, {\n\t\t\t\t\t\tevents,\n\t\t\t\t\t\tservices,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t\tdb,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error as object, 'Error processing subscriber');\n\t\t\t\t\tthrow wrapError(error);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** `url`, sent to `endpoint`'s origin instead of its own. */\nfunction throughEndpoint(url: string, endpoint: string): string {\n\tconst target = new URL(url);\n\tconst origin = new URL(endpoint);\n\ttarget.protocol = origin.protocol;\n\ttarget.host = origin.host;\n\treturn target.toString();\n}\n\nfunction refuse(\n\tstatus: SnsPushResponse['status'],\n\terror: string,\n): SnsPushResponse {\n\treturn { status, body: { status: 'refused', error } };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkDA,IAAa,2BAAb,MAAsC;CAEnB;CACR;CACQ;CAHlB,YACC,WACA,YACA,SACC;EAHgB,KAAA,YAAA;EACR,KAAA,aAAA;EACQ,KAAA,UAAA;CACf;CAEH,MAAM,OAAO,MAAyC;EACrD,MAAM,UAAU;EAChB,IAAI,OAAO,SAAS,SAAS,YAAY,CAAC,QAAQ,UACjD,OAAO,OAAO,KAAK,oBAAoB;EAIxC,IAAI,QAAQ,aAAa,KAAK,QAAQ,UACrC,OAAO,OAAO,KAAK,qBAAqB,QAAQ,UAAU;EAG3D,IAAI,KAAK,QAAQ,QAChB,IAAI;GACH,OAAA,GAAMA,sBAAAA,iBAAAA,CAAiB,OAAO;EAC/B,SAAS,OAAO;GACf,KAAK,WAAW,OAAO,KACtB;IAAE;IAAO,UAAU,QAAQ;GAAS,GACp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AAGA,SAAS,gBAAgB,KAAa,UAA0B;CAC/D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,SAAS,IAAI,IAAI,QAAQ;CAC/B,OAAO,WAAW,OAAO;CACzB,OAAO,OAAO,OAAO;CACrB,OAAO,OAAO,SAAS;AACxB;AAEA,SAAS,OACR,QACA,OACkB;CAClB,OAAO;EAAE;EAAQ,MAAM;GAAE,QAAQ;GAAW;EAAM;CAAE;AACrD"}
|
|
@@ -67,7 +67,8 @@ var SnsPushSubscriberAdaptor = class {
|
|
|
67
67
|
await runWithRequestContext({
|
|
68
68
|
logger,
|
|
69
69
|
requestId,
|
|
70
|
-
startTime: Date.now()
|
|
70
|
+
startTime: Date.now(),
|
|
71
|
+
operation: `subscriber ${this.subscriber.topicName ?? "sns"}`
|
|
71
72
|
}, async () => {
|
|
72
73
|
try {
|
|
73
74
|
const { services, db } = await subscriberContext(this.subscriber, this.envParser);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/subscribers/SnsPushSubscriberAdaptor.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { wrapError } from '@geekmidas/errors';\nimport {\n\tconfirmSnsSubscription,\n\ttype SnsHttpMessage,\n\ttoSnsEvent,\n\tverifySnsMessage,\n} from '@geekmidas/events/sns';\nimport { runWithRequestContext } from '@geekmidas/services';\nimport {\n\trunSubscriber,\n\tsubscribedEvents,\n\tsubscriberContext,\n} from './runSubscriber';\nimport type { Subscriber } from './Subscriber';\n\nexport interface SnsPushOptions {\n\t/** The topic this subscriber is subscribed to. Anything else is refused. */\n\ttopicArn: string;\n\t/**\n\t * Verify each message's signature. Off only against an emulator, which\n\t * signs nothing — decided by the connection string's endpoint, never by\n\t * anything the request says about itself.\n\t */\n\tverify: boolean;\n\t/**\n\t * The emulator's address, as this server was configured with it. An\n\t * emulator names itself in `SubscribeURL` by the port it listens on inside\n\t * its container, which is not the port published to the host — so against\n\t * one, the confirmation is sent here instead. From configuration, never\n\t * from the request.\n\t */\n\temulatorEndpoint?: string;\n}\n\n/** What to answer SNS with. A non-2xx tells SNS to retry. */\nexport interface SnsPushResponse {\n\tstatus: 200 | 400 | 403 | 500;\n\tbody: { status: string; error?: string };\n}\n\n/**\n * A topic subscriber run by SNS pushing to an HTTP endpoint, rather than by a\n * poller.\n *\n * The notification is read as the Lambda event SNS would have invoked a\n * function with, and run through the same parsing, services and handler as the\n * Lambda adaptor — without its middy wrapper, which is Lambda's alone: a\n * server serving this route has no reason to install `@middy/core`.\n */\nexport class SnsPushSubscriberAdaptor {\n\tconstructor(\n\t\tprivate readonly envParser: EnvironmentParser<{}>,\n\t\treadonly subscriber: Subscriber<any, any, any, any, any, any, any>,\n\t\tprivate readonly options: SnsPushOptions,\n\t) {}\n\n\tasync handle(body: unknown): Promise<SnsPushResponse> {\n\t\tconst message = body as SnsHttpMessage;\n\t\tif (typeof message?.Type !== 'string' || !message.TopicArn) {\n\t\t\treturn refuse(400, 'not an SNS message');\n\t\t}\n\t\t// Checked before the signature: a genuine message for another topic is\n\t\t// still not this subscriber's to confirm or to handle.\n\t\tif (message.TopicArn !== this.options.topicArn) {\n\t\t\treturn refuse(403, `not subscribed to ${message.TopicArn}`);\n\t\t}\n\n\t\tif (this.options.verify) {\n\t\t\ttry {\n\t\t\t\tawait verifySnsMessage(message);\n\t\t\t} catch (error) {\n\t\t\t\tthis.subscriber.logger.warn(\n\t\t\t\t\t{ error, topicArn: message.TopicArn },\n\t\t\t\t\t'Refused an SNS message that did not verify',\n\t\t\t\t);\n\t\t\t\treturn refuse(403, (error as Error).name);\n\t\t\t}\n\t\t}\n\n\t\tswitch (message.Type) {\n\t\t\tcase 'SubscriptionConfirmation':\n\t\t\t\tawait confirmSnsSubscription(\n\t\t\t\t\tthis.options.emulatorEndpoint && message.SubscribeURL\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...message,\n\t\t\t\t\t\t\t\tSubscribeURL: throughEndpoint(\n\t\t\t\t\t\t\t\t\tmessage.SubscribeURL,\n\t\t\t\t\t\t\t\t\tthis.options.emulatorEndpoint,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: message,\n\t\t\t\t);\n\t\t\t\tthis.subscriber.logger.info(\n\t\t\t\t\t{ topicArn: message.TopicArn },\n\t\t\t\t\t'Confirmed SNS subscription',\n\t\t\t\t);\n\t\t\t\treturn { status: 200, body: { status: 'confirmed' } };\n\t\t\tcase 'Notification':\n\t\t\t\ttry {\n\t\t\t\t\tawait this.notify(message);\n\t\t\t\t\treturn { status: 200, body: { status: 'ok' } };\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Already logged. A 500 makes SNS retry, which is the point of\n\t\t\t\t\t// answering at all.\n\t\t\t\t\treturn refuse(500, (error as Error).name);\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn { status: 200, body: { status: 'ignored' } };\n\t\t}\n\t}\n\n\tprivate async notify(message: SnsHttpMessage): Promise<void> {\n\t\tconst requestId = message.MessageId;\n\t\tconst logger = this.subscriber.logger.child({ requestId });\n\n\t\tawait runWithRequestContext(\n\t\t\t{
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/subscribers/SnsPushSubscriberAdaptor.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { wrapError } from '@geekmidas/errors';\nimport {\n\tconfirmSnsSubscription,\n\ttype SnsHttpMessage,\n\ttoSnsEvent,\n\tverifySnsMessage,\n} from '@geekmidas/events/sns';\nimport { runWithRequestContext } from '@geekmidas/services';\nimport {\n\trunSubscriber,\n\tsubscribedEvents,\n\tsubscriberContext,\n} from './runSubscriber';\nimport type { Subscriber } from './Subscriber';\n\nexport interface SnsPushOptions {\n\t/** The topic this subscriber is subscribed to. Anything else is refused. */\n\ttopicArn: string;\n\t/**\n\t * Verify each message's signature. Off only against an emulator, which\n\t * signs nothing — decided by the connection string's endpoint, never by\n\t * anything the request says about itself.\n\t */\n\tverify: boolean;\n\t/**\n\t * The emulator's address, as this server was configured with it. An\n\t * emulator names itself in `SubscribeURL` by the port it listens on inside\n\t * its container, which is not the port published to the host — so against\n\t * one, the confirmation is sent here instead. From configuration, never\n\t * from the request.\n\t */\n\temulatorEndpoint?: string;\n}\n\n/** What to answer SNS with. A non-2xx tells SNS to retry. */\nexport interface SnsPushResponse {\n\tstatus: 200 | 400 | 403 | 500;\n\tbody: { status: string; error?: string };\n}\n\n/**\n * A topic subscriber run by SNS pushing to an HTTP endpoint, rather than by a\n * poller.\n *\n * The notification is read as the Lambda event SNS would have invoked a\n * function with, and run through the same parsing, services and handler as the\n * Lambda adaptor — without its middy wrapper, which is Lambda's alone: a\n * server serving this route has no reason to install `@middy/core`.\n */\nexport class SnsPushSubscriberAdaptor {\n\tconstructor(\n\t\tprivate readonly envParser: EnvironmentParser<{}>,\n\t\treadonly subscriber: Subscriber<any, any, any, any, any, any, any>,\n\t\tprivate readonly options: SnsPushOptions,\n\t) {}\n\n\tasync handle(body: unknown): Promise<SnsPushResponse> {\n\t\tconst message = body as SnsHttpMessage;\n\t\tif (typeof message?.Type !== 'string' || !message.TopicArn) {\n\t\t\treturn refuse(400, 'not an SNS message');\n\t\t}\n\t\t// Checked before the signature: a genuine message for another topic is\n\t\t// still not this subscriber's to confirm or to handle.\n\t\tif (message.TopicArn !== this.options.topicArn) {\n\t\t\treturn refuse(403, `not subscribed to ${message.TopicArn}`);\n\t\t}\n\n\t\tif (this.options.verify) {\n\t\t\ttry {\n\t\t\t\tawait verifySnsMessage(message);\n\t\t\t} catch (error) {\n\t\t\t\tthis.subscriber.logger.warn(\n\t\t\t\t\t{ error, topicArn: message.TopicArn },\n\t\t\t\t\t'Refused an SNS message that did not verify',\n\t\t\t\t);\n\t\t\t\treturn refuse(403, (error as Error).name);\n\t\t\t}\n\t\t}\n\n\t\tswitch (message.Type) {\n\t\t\tcase 'SubscriptionConfirmation':\n\t\t\t\tawait confirmSnsSubscription(\n\t\t\t\t\tthis.options.emulatorEndpoint && message.SubscribeURL\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...message,\n\t\t\t\t\t\t\t\tSubscribeURL: throughEndpoint(\n\t\t\t\t\t\t\t\t\tmessage.SubscribeURL,\n\t\t\t\t\t\t\t\t\tthis.options.emulatorEndpoint,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: message,\n\t\t\t\t);\n\t\t\t\tthis.subscriber.logger.info(\n\t\t\t\t\t{ topicArn: message.TopicArn },\n\t\t\t\t\t'Confirmed SNS subscription',\n\t\t\t\t);\n\t\t\t\treturn { status: 200, body: { status: 'confirmed' } };\n\t\t\tcase 'Notification':\n\t\t\t\ttry {\n\t\t\t\t\tawait this.notify(message);\n\t\t\t\t\treturn { status: 200, body: { status: 'ok' } };\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Already logged. A 500 makes SNS retry, which is the point of\n\t\t\t\t\t// answering at all.\n\t\t\t\t\treturn refuse(500, (error as Error).name);\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn { status: 200, body: { status: 'ignored' } };\n\t\t}\n\t}\n\n\tprivate async notify(message: SnsHttpMessage): Promise<void> {\n\t\tconst requestId = message.MessageId;\n\t\tconst logger = this.subscriber.logger.child({ requestId });\n\n\t\tawait runWithRequestContext(\n\t\t\t{\n\t\t\t\tlogger,\n\t\t\t\trequestId,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\toperation: `subscriber ${this.subscriber.topicName ?? 'sns'}`,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst { services, db } = await subscriberContext(\n\t\t\t\t\t\tthis.subscriber,\n\t\t\t\t\t\tthis.envParser,\n\t\t\t\t\t);\n\t\t\t\t\tconst events = subscribedEvents(\n\t\t\t\t\t\tthis.subscriber,\n\t\t\t\t\t\ttoSnsEvent(message),\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t);\n\t\t\t\t\tawait runSubscriber(this.subscriber, {\n\t\t\t\t\t\tevents,\n\t\t\t\t\t\tservices,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t\tdb,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error as object, 'Error processing subscriber');\n\t\t\t\t\tthrow wrapError(error);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t}\n}\n\n/** `url`, sent to `endpoint`'s origin instead of its own. */\nfunction throughEndpoint(url: string, endpoint: string): string {\n\tconst target = new URL(url);\n\tconst origin = new URL(endpoint);\n\ttarget.protocol = origin.protocol;\n\ttarget.host = origin.host;\n\treturn target.toString();\n}\n\nfunction refuse(\n\tstatus: SnsPushResponse['status'],\n\terror: string,\n): SnsPushResponse {\n\treturn { status, body: { status: 'refused', error } };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkDA,IAAa,2BAAb,MAAsC;CAEnB;CACR;CACQ;CAHlB,YACC,WACA,YACA,SACC;EAHgB,KAAA,YAAA;EACR,KAAA,aAAA;EACQ,KAAA,UAAA;CACf;CAEH,MAAM,OAAO,MAAyC;EACrD,MAAM,UAAU;EAChB,IAAI,OAAO,SAAS,SAAS,YAAY,CAAC,QAAQ,UACjD,OAAO,OAAO,KAAK,oBAAoB;EAIxC,IAAI,QAAQ,aAAa,KAAK,QAAQ,UACrC,OAAO,OAAO,KAAK,qBAAqB,QAAQ,UAAU;EAG3D,IAAI,KAAK,QAAQ,QAChB,IAAI;GACH,MAAM,iBAAiB,OAAO;EAC/B,SAAS,OAAO;GACf,KAAK,WAAW,OAAO,KACtB;IAAE;IAAO,UAAU,QAAQ;GAAS,GACpC,4CACD;GACA,OAAO,OAAO,KAAM,MAAgB,IAAI;EACzC;EAGD,QAAQ,QAAQ,MAAhB;GACC,KAAK;IACJ,MAAM,uBACL,KAAK,QAAQ,oBAAoB,QAAQ,eACtC;KACA,GAAG;KACH,cAAc,gBACb,QAAQ,cACR,KAAK,QAAQ,gBACd;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6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geekmidas/constructs",
|
|
3
|
-
"version": "10.0.0-alpha.
|
|
3
|
+
"version": "10.0.0-alpha.55",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -276,13 +276,13 @@
|
|
|
276
276
|
"lodash.uniqby": "~4.7.0",
|
|
277
277
|
"openapi-types": "~12.1.3",
|
|
278
278
|
"qs": "~6.16.0",
|
|
279
|
-
"@geekmidas/envkit": "^10.0.0-alpha.
|
|
280
|
-
"@geekmidas/errors": "^10.0.0-alpha.
|
|
281
|
-
"@geekmidas/events": "^10.0.0-alpha.
|
|
282
|
-
"@geekmidas/logger": "^10.0.0-alpha.
|
|
283
|
-
"@geekmidas/manifest": "^10.0.0-alpha.
|
|
284
|
-
"@geekmidas/schema": "^10.0.0-alpha.
|
|
285
|
-
"@geekmidas/services": "^10.0.0-alpha.
|
|
279
|
+
"@geekmidas/envkit": "^10.0.0-alpha.55",
|
|
280
|
+
"@geekmidas/errors": "^10.0.0-alpha.55",
|
|
281
|
+
"@geekmidas/events": "^10.0.0-alpha.55",
|
|
282
|
+
"@geekmidas/logger": "^10.0.0-alpha.55",
|
|
283
|
+
"@geekmidas/manifest": "^10.0.0-alpha.55",
|
|
284
|
+
"@geekmidas/schema": "^10.0.0-alpha.55",
|
|
285
|
+
"@geekmidas/services": "^10.0.0-alpha.55"
|
|
286
286
|
},
|
|
287
287
|
"devDependencies": {
|
|
288
288
|
"@aws-sdk/client-kms": "~3.1136.0",
|
|
@@ -299,20 +299,20 @@
|
|
|
299
299
|
"msw": "~2.15.0",
|
|
300
300
|
"pg": "~8.23.0",
|
|
301
301
|
"zod": "~4.6.5",
|
|
302
|
-
"@geekmidas/audit": "^10.0.0-alpha.
|
|
303
|
-
"@geekmidas/auth": "10.0.0-alpha.
|
|
304
|
-
"@geekmidas/cache": "^10.0.0-alpha.
|
|
305
|
-
"@geekmidas/db": "^10.0.0-alpha.
|
|
306
|
-
"@geekmidas/emailkit": "^10.0.0-alpha.
|
|
307
|
-
"@geekmidas/envkit": "^10.0.0-alpha.
|
|
308
|
-
"@geekmidas/errors": "^10.0.0-alpha.
|
|
309
|
-
"@geekmidas/events": "^10.0.0-alpha.
|
|
310
|
-
"@geekmidas/logger": "^10.0.0-alpha.
|
|
311
|
-
"@geekmidas/rate-limit": "^10.0.0-alpha.
|
|
312
|
-
"@geekmidas/schema": "^10.0.0-alpha.
|
|
313
|
-
"@geekmidas/services": "^10.0.0-alpha.
|
|
314
|
-
"@geekmidas/telescope": "10.0.0-alpha.
|
|
315
|
-
"@geekmidas/testkit": "^10.0.0-alpha.
|
|
302
|
+
"@geekmidas/audit": "^10.0.0-alpha.55",
|
|
303
|
+
"@geekmidas/auth": "10.0.0-alpha.55",
|
|
304
|
+
"@geekmidas/cache": "^10.0.0-alpha.55",
|
|
305
|
+
"@geekmidas/db": "^10.0.0-alpha.55",
|
|
306
|
+
"@geekmidas/emailkit": "^10.0.0-alpha.55",
|
|
307
|
+
"@geekmidas/envkit": "^10.0.0-alpha.55",
|
|
308
|
+
"@geekmidas/errors": "^10.0.0-alpha.55",
|
|
309
|
+
"@geekmidas/events": "^10.0.0-alpha.55",
|
|
310
|
+
"@geekmidas/logger": "^10.0.0-alpha.55",
|
|
311
|
+
"@geekmidas/rate-limit": "^10.0.0-alpha.55",
|
|
312
|
+
"@geekmidas/schema": "^10.0.0-alpha.55",
|
|
313
|
+
"@geekmidas/services": "^10.0.0-alpha.55",
|
|
314
|
+
"@geekmidas/telescope": "10.0.0-alpha.55",
|
|
315
|
+
"@geekmidas/testkit": "^10.0.0-alpha.55"
|
|
316
316
|
},
|
|
317
317
|
"peerDependencies": {
|
|
318
318
|
"@aws-sdk/client-kms": ">=3.1136.0",
|
|
@@ -323,15 +323,15 @@
|
|
|
323
323
|
"kysely": "~0.29.6",
|
|
324
324
|
"msw": ">=2.15.0",
|
|
325
325
|
"pg": ">=8.23.0",
|
|
326
|
-
"@geekmidas/audit": "^10.0.0-alpha.
|
|
327
|
-
"@geekmidas/auth": "10.0.0-alpha.
|
|
328
|
-
"@geekmidas/cache": "^10.0.0-alpha.
|
|
329
|
-
"@geekmidas/db": "^10.0.0-alpha.
|
|
330
|
-
"@geekmidas/emailkit": "^10.0.0-alpha.
|
|
331
|
-
"@geekmidas/rate-limit": "^10.0.0-alpha.
|
|
332
|
-
"@geekmidas/storage": "^10.0.0-alpha.
|
|
333
|
-
"@geekmidas/telescope": "10.0.0-alpha.
|
|
334
|
-
"@geekmidas/testkit": "^10.0.0-alpha.
|
|
326
|
+
"@geekmidas/audit": "^10.0.0-alpha.55",
|
|
327
|
+
"@geekmidas/auth": "10.0.0-alpha.55",
|
|
328
|
+
"@geekmidas/cache": "^10.0.0-alpha.55",
|
|
329
|
+
"@geekmidas/db": "^10.0.0-alpha.55",
|
|
330
|
+
"@geekmidas/emailkit": "^10.0.0-alpha.55",
|
|
331
|
+
"@geekmidas/rate-limit": "^10.0.0-alpha.55",
|
|
332
|
+
"@geekmidas/storage": "^10.0.0-alpha.55",
|
|
333
|
+
"@geekmidas/telescope": "10.0.0-alpha.55",
|
|
334
|
+
"@geekmidas/testkit": "^10.0.0-alpha.55"
|
|
335
335
|
},
|
|
336
336
|
"peerDependenciesMeta": {
|
|
337
337
|
"@aws-sdk/client-kms": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"HonoEndpointAdaptor-DW4q9db0.mjs","names":["honoLogger"],"sources":["../src/endpoints/helpers.ts","../src/endpoints/parseHonoQuery.ts","../src/endpoints/HonoEndpointAdaptor.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Service } from '@geekmidas/services';\nimport fg from 'fast-glob';\nimport type { HttpMethod } from '../types';\nimport { Endpoint } from './Endpoint';\n\n// Re-export utility functions\n\n/**\n * Recursively finds the project root directory by looking for lock files.\n * Traverses up the directory tree until it finds a package manager lock file.\n *\n * @param cwd - The current working directory to start searching from\n * @returns Promise resolving to the absolute path of the project root\n *\n * @example\n * ```typescript\n * const projectRoot = await getProjectRoot(process.cwd());\n * console.log(`Project root: ${projectRoot}`);\n * // Output: Project root: /Users/user/my-project\n * ```\n */\nexport async function getProjectRoot(cwd: string): Promise<string> {\n\tif (cwd === '/') {\n\t\treturn cwd;\n\t}\n\n\tconst stream = fg.stream(\n\t\t['yarn.lock', 'pnpm-lock.yaml', 'package-lock.json', 'deno.lock'],\n\t\t{ dot: true, cwd },\n\t);\n\n\tlet isRoot = false;\n\n\tfor await (const _ of stream) {\n\t\tisRoot = true;\n\t\tbreak;\n\t}\n\n\tif (isRoot) {\n\t\treturn cwd;\n\t}\n\n\treturn getProjectRoot(path.resolve(cwd, '..'));\n}\n\n/**\n * Discovers and imports all Endpoint instances from the specified route patterns.\n * Uses fast-glob to find files matching the patterns and extracts exported Endpoints.\n *\n * @template TServices - Array of service types used by the endpoints\n * @param routes - Array of glob patterns to match route files (e.g., ['src/routes/*.ts'])\n * @param cwd - The current working directory to resolve paths from\n * @returns Promise resolving to an array of Endpoint instances found in the matched files\n *\n * @example\n * ```typescript\n * // Find all endpoints in the routes directory\n * const endpoints = await getEndpointsFromRoutes(\n * ['src/routes/**\\/*.ts'],\n * process.cwd()\n * );\n *\n * // Register endpoints with your server\n * for (const endpoint of endpoints) {\n * server.register(endpoint);\n * }\n * ```\n *\n * @remarks\n * - Only exports that are valid Endpoint instances are included\n * - Files are imported dynamically, so they must be valid ES modules\n * - The function filters out non-Endpoint exports automatically\n */\nexport async function getEndpointsFromRoutes<TServices extends Service[]>(\n\troutes: string[],\n\tcwd: string,\n): Promise<Endpoint<string, HttpMethod, any, any, TServices>[]> {\n\tconst stream = fg.stream(routes, { cwd });\n\n\tconst endpoints: Endpoint<string, HttpMethod, any, any, TServices>[] = [];\n\n\tfor await (const f of stream) {\n\t\t// Resolve the absolute path for the route file\n\t\tconst routePath = path.resolve(cwd, f.toString());\n\t\t// Dynamically import the route module\n\t\tconst route = await import(routePath);\n\n\t\t// Filter exported values to find only Endpoint instances\n\t\tconst handlers = Object.values(route).filter((value) => {\n\t\t\treturn Endpoint.isEndpoint(value);\n\t\t}) as unknown as Endpoint<string, HttpMethod, any, any, TServices>[];\n\n\t\tendpoints.push(...handlers);\n\t}\n\n\treturn endpoints;\n}\n","import type { Context } from 'hono';\nimport qs from 'qs';\n\n/**\n * Parse Hono query parameters using qs bracket notation\n * Supports nested objects, arrays, and deep nesting via standard bracket syntax\n */\nexport function parseHonoQuery(c: Context): Record<string, any> {\n\tconst url = c.req.url;\n\tconst queryIndex = url.indexOf('?');\n\tif (queryIndex === -1) {\n\t\treturn {};\n\t}\n\tconst queryString = url.slice(queryIndex + 1);\n\treturn qs.parse(queryString) as Record<string, any>;\n}\n","import type { AuditableAction, AuditStorage } from '@geekmidas/audit';\nimport { withRlsContext } from '@geekmidas/db/rls';\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport { wrapError } from '@geekmidas/errors';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport { checkRateLimit, getRateLimitHeaders } from '@geekmidas/rate-limit';\nimport {\n\trunWithRequestContext,\n\ttype Service,\n\tServiceDiscovery,\n\ttype ServiceRecord,\n} from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { type Context, Hono } from 'hono';\nimport { setCookie } from 'hono/cookie';\nimport { logger as honoLogger } from 'hono/logger';\nimport { timing } from 'hono/timing';\nimport type { ContentfulStatusCode } from 'hono/utils/http-status';\nimport { validator } from 'hono/validator';\nimport { publishConstructEvents } from '../publisher';\nimport type { HttpMethod, LowerHttpMethod } from '../types';\nimport type { MappedAudit } from './audit';\nimport {\n\tEndpoint,\n\ttype EndpointContext,\n\ttype EndpointSchemas,\n\tResponseBuilder,\n} from './Endpoint';\nimport { getEndpointsFromRoutes } from './helpers';\nimport { createHonoCookies, createHonoHeaders } from './lazyAccessors';\nimport { parseHonoQuery } from './parseHonoQuery';\nimport {\n\tcreateAuditContext,\n\texecuteWithAuditTransaction,\n} from './processAudits';\n\nexport interface HonoEndpointOptions {\n\t/**\n\t * Path where OpenAPI documentation will be served.\n\t * Set to false to disable docs route.\n\t * @default '/docs'\n\t */\n\tdocsPath?: string | false;\n\t/**\n\t * OpenAPI schema options\n\t */\n\topenApiOptions?: {\n\t\ttitle?: string;\n\t\tversion?: string;\n\t\tdescription?: string;\n\t};\n}\n\n/**\n * Feature flags for an endpoint, analyzed once at route registration time.\n * This avoids per-request feature detection overhead.\n */\ninterface EndpointFeatures {\n\thasServices: boolean;\n\thasDatabase: boolean;\n\thasBodyValidation: boolean;\n\thasQueryValidation: boolean;\n\thasParamValidation: boolean;\n\thasAudits: boolean;\n\thasEvents: boolean;\n\thasRateLimit: boolean;\n\thasRls: boolean;\n}\n\n/**\n * Case-insensitive check for a `content-type` header in a metadata headers map.\n */\nfunction hasContentTypeHeader(headers: Record<string, string>): boolean {\n\tfor (const key of Object.keys(headers)) {\n\t\tif (key.toLowerCase() === 'content-type') return true;\n\t}\n\treturn false;\n}\n\n/**\n * Analyze endpoint features at registration time (not per-request)\n */\nfunction analyzeEndpointFeatures(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t>,\n): EndpointFeatures {\n\treturn {\n\t\thasServices: endpoint.services.length > 0,\n\t\thasDatabase: !!endpoint.databaseService,\n\t\thasBodyValidation: !!endpoint.input?.body,\n\t\thasQueryValidation: !!endpoint.input?.query,\n\t\thasParamValidation: !!endpoint.input?.params,\n\t\t// Audit context needed if declarative audits OR auditor storage service configured (for manual audits)\n\t\thasAudits:\n\t\t\t(endpoint.audits?.length ?? 0) > 0 || !!endpoint.auditorStorageService,\n\t\thasEvents: (endpoint.events?.length ?? 0) > 0,\n\t\thasRateLimit: !!endpoint.rateLimit,\n\t\thasRls: !!endpoint.rlsConfig && !endpoint.rlsBypass,\n\t};\n}\n\nexport class HonoEndpoint<\n\tTRoute extends string,\n\tTMethod extends HttpMethod,\n\tTInput extends EndpointSchemas = {},\n\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tTSession = unknown,\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> {\n\tconstructor(\n\t\tprivate readonly endpoint: Endpoint<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTOutSchema,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTSession,\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\tstatic isDev = process.env.NODE_ENV === 'development';\n\n\tstatic async validate<T extends StandardSchemaV1>(\n\t\tc: Context<any, string, {}>,\n\t\tdata: unknown,\n\t\tschema?: T,\n\t) {\n\t\tif (!schema) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst parsed = await Endpoint.validate(schema, data);\n\n\t\tif (parsed.issues) {\n\t\t\treturn c.json(parsed.issues, 422);\n\t\t}\n\n\t\treturn parsed.value;\n\t}\n\taddRoute(\n\t\tserviceDiscovery: ServiceDiscovery<ServiceRecord<TServices>>,\n\t\tapp: Hono,\n\t): void {\n\t\tHonoEndpoint.addRoute(this.endpoint, serviceDiscovery, app);\n\t}\n\n\t/**\n\t * @deprecated Global event middleware is no longer used.\n\t * Events are now published per-route only for endpoints that have events configured.\n\t * This method is kept for backward compatibility but does nothing.\n\t */\n\tstatic applyEventMiddleware(\n\t\t_app: Hono,\n\t\t_serviceDiscovery: ServiceDiscovery<any>,\n\t) {\n\t\t// No-op: Event publishing is now handled per-route in addRoute\n\t\t// This avoids running middleware on every request including 404s\n\t}\n\n\tstatic async fromRoutes<TLogger extends Logger, TServices extends Service[]>(\n\t\troutes: string[],\n\t\tenvParser: EnvironmentParser<{}>,\n\t\tapp = new Hono(),\n\t\t_logger: TLogger,\n\t\tcwd = process.cwd(),\n\t\toptions?: HonoEndpointOptions,\n\t): Promise<Hono> {\n\t\tconst endpoints = await getEndpointsFromRoutes<TServices>(routes, cwd);\n\t\tconst serviceDiscovery =\n\t\t\tServiceDiscovery.getInstance<ServiceRecord<TServices>>(envParser);\n\n\t\tHonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, options);\n\n\t\treturn app;\n\t}\n\n\tstatic addRoutes<\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t>(\n\t\tendpoints: Endpoint<string, HttpMethod, any, any, TServices, TLogger>[],\n\t\tserviceDiscovery: ServiceDiscovery<ServiceRecord<TServices>>,\n\t\tapp: Hono,\n\t\toptions?: HonoEndpointOptions,\n\t): void {\n\t\t// Add timing middleware (always enabled)\n\t\tapp.use('*', timing());\n\n\t\t// Add logger middleware in development mode\n\n\t\tif (HonoEndpoint.isDev) {\n\t\t\tapp.use('*', honoLogger());\n\t\t}\n\n\t\t// Add docs route if not disabled\n\t\tconst docsPath =\n\t\t\toptions?.docsPath !== false ? options?.docsPath || '/docs' : null;\n\t\tif (docsPath) {\n\t\t\tHonoEndpoint.addDocsRoute(\n\t\t\t\tendpoints,\n\t\t\t\tapp,\n\t\t\t\tdocsPath,\n\t\t\t\toptions?.openApiOptions,\n\t\t\t);\n\t\t}\n\n\t\t// Sort endpoints to ensure static routes come before dynamic ones\n\t\tconst sortedEndpoints = endpoints.sort((a, b) => {\n\t\t\tconst aSegments = a.route.split('/');\n\t\t\tconst bSegments = b.route.split('/');\n\n\t\t\t// Compare each segment\n\t\t\tfor (let i = 0; i < Math.max(aSegments.length, bSegments.length); i++) {\n\t\t\t\tconst aSegment = aSegments[i] || '';\n\t\t\t\tconst bSegment = bSegments[i] || '';\n\n\t\t\t\t// If one is dynamic and the other is not, static comes first\n\t\t\t\tconst aIsDynamic = aSegment.startsWith(':');\n\t\t\t\tconst bIsDynamic = bSegment.startsWith(':');\n\n\t\t\t\tif (!aIsDynamic && bIsDynamic) return -1;\n\t\t\t\tif (aIsDynamic && !bIsDynamic) return 1;\n\n\t\t\t\t// If both are the same type, compare alphabetically\n\t\t\t\tif (aSegment !== bSegment) {\n\t\t\t\t\treturn aSegment.localeCompare(bSegment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t});\n\n\t\t// Note: Global event middleware removed for performance\n\t\t// Events are now published per-route only for endpoints with events configured\n\t\tfor (const endpoint of sortedEndpoints) {\n\t\t\tHonoEndpoint.addRoute(endpoint, serviceDiscovery, app);\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/useAdjacentOverloadSignatures: not an overload — the instance `addRoute` above registers this adaptor's own endpoint, this one registers any endpoint on a given app. They share a name because they do the same thing to different subjects.\n\tstatic addRoute<\n\t\tTRoute extends string,\n\t\tTMethod extends HttpMethod,\n\t\tTInput extends EndpointSchemas = {},\n\t\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t\tTSession = unknown,\n\t\tTAuditStorage extends AuditStorage | undefined = undefined,\n\t\tTAuditStorageServiceName extends string = string,\n\t\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>,\n\t\tTDatabase = undefined,\n\t\tTDatabaseServiceName extends string = string,\n\t>(\n\t\tendpoint: Endpoint<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTOutSchema,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTSession,\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\tserviceDiscovery: ServiceDiscovery<ServiceRecord<TServices>>,\n\t\tapp: Hono,\n\t): void {\n\t\tconst { route } = endpoint;\n\t\tconst method = endpoint.method.toLowerCase() as LowerHttpMethod<TMethod>;\n\n\t\t// Analyze endpoint features once at registration time (not per-request)\n\t\tconst features = analyzeEndpointFeatures(endpoint);\n\n\t\t// Build validators array - only add validators for schemas that exist\n\t\tconst validators: any[] = [];\n\n\t\tif (features.hasBodyValidation) {\n\t\t\tvalidators.push(\n\t\t\t\tvalidator('json', (value, c) =>\n\t\t\t\t\tHonoEndpoint.validate(c, value, endpoint.input?.body),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\tif (features.hasQueryValidation) {\n\t\t\tvalidators.push(\n\t\t\t\tvalidator('query', (_, c) => {\n\t\t\t\t\tconst parsedQuery = parseHonoQuery(c);\n\t\t\t\t\treturn HonoEndpoint.validate(c, parsedQuery, endpoint.input?.query);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tif (features.hasParamValidation) {\n\t\t\tvalidators.push(\n\t\t\t\tvalidator('param', (params, c) =>\n\t\t\t\t\tHonoEndpoint.validate(c, params, endpoint.input?.params),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\t// Main handler\n\t\tconst handler = async (c: Context) => {\n\t\t\t// Request context setup\n\t\t\tconst startTime = Date.now();\n\t\t\tconst requestId = c.req.header('X-Request-ID') ?? crypto.randomUUID();\n\n\t\t\tconst logger = endpoint.logger.child({\n\t\t\t\trequestId,\n\t\t\t\tendpoint: endpoint.fullPath,\n\t\t\t\troute: endpoint.route,\n\t\t\t\thost: c.req.header('host'),\n\t\t\t\tmethod: endpoint.method,\n\t\t\t\tpath: c.req.path,\n\t\t\t}) as TLogger;\n\n\t\t\t// Set response header\n\t\t\tc.header('X-Request-ID', requestId);\n\n\t\t\t// Wrap entire handler in request context for services to access\n\t\t\treturn runWithRequestContext(\n\t\t\t\t{ logger, requestId, startTime },\n\t\t\t\tasync () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Lazy accessors - no upfront parsing, use native Hono methods\n\t\t\t\t\t\tconst header = createHonoHeaders(c);\n\t\t\t\t\t\tconst cookie = createHonoCookies(c);\n\n\t\t\t\t\t\t// Only register services if endpoint has any\n\t\t\t\t\t\tconst services = features.hasServices\n\t\t\t\t\t\t\t? await serviceDiscovery.register(endpoint.services)\n\t\t\t\t\t\t\t: ({} as ServiceRecord<TServices>);\n\n\t\t\t\t\t\t// Resolve database service only if configured\n\t\t\t\t\t\tconst rawDb = features.hasDatabase\n\t\t\t\t\t\t\t? await serviceDiscovery\n\t\t\t\t\t\t\t\t\t.register([endpoint.databaseService!])\n\t\t\t\t\t\t\t\t\t.then(\n\t\t\t\t\t\t\t\t\t\t(s) =>\n\t\t\t\t\t\t\t\t\t\t\ts[\n\t\t\t\t\t\t\t\t\t\t\t\tendpoint.databaseService?.serviceName as keyof typeof s\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\t// Extract session (defaults to empty object)\n\t\t\t\t\t\tconst session = await endpoint.getSession({\n\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t...(rawDb !== undefined && { db: rawDb }),\n\t\t\t\t\t\t} as any);\n\n\t\t\t\t\t\t// Check authorization (defaults to true)\n\t\t\t\t\t\tconst isAuthorized = await endpoint.authorize({\n\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t...(rawDb !== undefined && { db: rawDb }),\n\t\t\t\t\t\t\tbody: features.hasBodyValidation\n\t\t\t\t\t\t\t\t? (c.req.valid as any)('json')\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\tquery: features.hasQueryValidation\n\t\t\t\t\t\t\t\t? (c.req.valid as any)('query')\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\tparams: features.hasParamValidation\n\t\t\t\t\t\t\t\t? (c.req.valid as any)('param')\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t} as any);\n\n\t\t\t\t\t\tif (!isAuthorized) {\n\t\t\t\t\t\t\tlogger.warn('Forbidden access attempt');\n\t\t\t\t\t\t\treturn c.json({ error: 'Forbidden' }, 403);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Check rate limit only if configured\n\t\t\t\t\t\tif (features.hasRateLimit) {\n\t\t\t\t\t\t\tconst rateLimitInfo = await checkRateLimit(endpoint.rateLimit!, {\n\t\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\tpath: c.req.path,\n\t\t\t\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tconst rateLimitHeaders = getRateLimitHeaders(\n\t\t\t\t\t\t\t\trateLimitInfo,\n\t\t\t\t\t\t\t\tendpoint.rateLimit!,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(rateLimitHeaders)) {\n\t\t\t\t\t\t\t\tif (value) {\n\t\t\t\t\t\t\t\t\tc.header(key, value);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Create audit context only if audits are configured\n\t\t\t\t\t\tconst auditContext = features.hasAudits\n\t\t\t\t\t\t\t? await createAuditContext(\n\t\t\t\t\t\t\t\t\tendpoint as any,\n\t\t\t\t\t\t\t\t\tserviceDiscovery,\n\t\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\tservices: services as Record<string, unknown>,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\tconst audits = features.hasAudits\n\t\t\t\t\t\t\t? (endpoint.audits as MappedAudit<TAuditAction, TOutSchema>[])\n\t\t\t\t\t\t\t: [];\n\n\t\t\t\t\t\t// Warn if declarative audits are configured but no audit storage\n\t\t\t\t\t\tif (features.hasAudits && !auditContext) {\n\t\t\t\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Extract RLS context only if configured and not bypassed\n\t\t\t\t\t\tconst rlsContext =\n\t\t\t\t\t\t\tfeatures.hasRls && rawDb !== undefined\n\t\t\t\t\t\t\t\t? await endpoint.rlsConfig?.extractor({\n\t\t\t\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\t\t\t\tsession: session as TSession,\n\t\t\t\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\t// Execute handler with automatic audit transaction support\n\t\t\t\t\t\tconst result = await executeWithAuditTransaction(\n\t\t\t\t\t\t\tauditContext,\n\t\t\t\t\t\t\tasync (auditor) => {\n\t\t\t\t\t\t\t\tconst sameDatabase =\n\t\t\t\t\t\t\t\t\tauditContext?.storage?.databaseServiceName &&\n\t\t\t\t\t\t\t\t\tauditContext.storage.databaseServiceName ===\n\t\t\t\t\t\t\t\t\t\tendpoint.databaseService?.serviceName;\n\t\t\t\t\t\t\t\tconst baseDb = sameDatabase\n\t\t\t\t\t\t\t\t\t? (auditor?.getTransaction?.() ?? rawDb)\n\t\t\t\t\t\t\t\t\t: rawDb;\n\n\t\t\t\t\t\t\t\tconst executeHandler = async (db: TDatabase | undefined) => {\n\t\t\t\t\t\t\t\t\tconst responseBuilder = new ResponseBuilder();\n\t\t\t\t\t\t\t\t\tconst response = await endpoint.handler(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\t\t\t\tbody: features.hasBodyValidation\n\t\t\t\t\t\t\t\t\t\t\t\t? (c.req.valid as any)('json')\n\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\tquery: features.hasQueryValidation\n\t\t\t\t\t\t\t\t\t\t\t\t? (c.req.valid as any)('query')\n\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\tparams: features.hasParamValidation\n\t\t\t\t\t\t\t\t\t\t\t\t? (c.req.valid as any)('param')\n\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\t\tauditor,\n\t\t\t\t\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\t\t\t\t} as unknown as EndpointContext<\n\t\t\t\t\t\t\t\t\t\t\tTInput,\n\t\t\t\t\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\t\t\t\t\tTLogger,\n\t\t\t\t\t\t\t\t\t\t\tTSession,\n\t\t\t\t\t\t\t\t\t\t\tTAuditAction,\n\t\t\t\t\t\t\t\t\t\t\tTDatabase,\n\t\t\t\t\t\t\t\t\t\t\tTAuditStorage\n\t\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\t\tresponseBuilder,\n\t\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\t\tlet data = response;\n\t\t\t\t\t\t\t\t\tlet metadata = responseBuilder.getMetadata();\n\n\t\t\t\t\t\t\t\t\tif (Endpoint.hasMetadata(response)) {\n\t\t\t\t\t\t\t\t\t\tdata = response.data;\n\t\t\t\t\t\t\t\t\t\tmetadata = response.metadata;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst output = endpoint.outputSchema\n\t\t\t\t\t\t\t\t\t\t? await endpoint.parseOutput(data)\n\t\t\t\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\t\t\t\treturn { output, metadata, responseBuilder };\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tif (features.hasRls && rlsContext && baseDb) {\n\t\t\t\t\t\t\t\t\treturn withRlsContext(\n\t\t\t\t\t\t\t\t\t\tbaseDb as any,\n\t\t\t\t\t\t\t\t\t\trlsContext,\n\t\t\t\t\t\t\t\t\t\tasync (trx) => executeHandler(trx as TDatabase),\n\t\t\t\t\t\t\t\t\t\t{ prefix: endpoint.rlsConfig?.prefix },\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn executeHandler(baseDb as TDatabase | undefined);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tasync (result, auditor) => {\n\t\t\t\t\t\t\t\tif (!audits?.length) return;\n\n\t\t\t\t\t\t\t\tfor (const audit of audits) {\n\t\t\t\t\t\t\t\t\tif (audit.when && !audit.when(result.output as any)) {\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst payload = audit.payload(result.output as any);\n\t\t\t\t\t\t\t\t\tconst entityId = audit.entityId?.(result.output as any);\n\t\t\t\t\t\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\t\t\t\t\t\ttable: audit.table,\n\t\t\t\t\t\t\t\t\t\tentityId,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{ db: rawDb },\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst { output, metadata } = result;\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlet status = endpoint.status as ContentfulStatusCode;\n\n\t\t\t\t\t\t\tif (metadata.status) {\n\t\t\t\t\t\t\t\tstatus = metadata.status as ContentfulStatusCode;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (metadata.headers) {\n\t\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(metadata.headers)) {\n\t\t\t\t\t\t\t\t\tc.header(key, value);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (metadata.cookies) {\n\t\t\t\t\t\t\t\tfor (const [name, { value, options }] of metadata.cookies) {\n\t\t\t\t\t\t\t\t\tsetCookie(c, name, value, options);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Only publish events if configured (no global middleware overhead)\n\t\t\t\t\t\t\tif (features.hasEvents && Endpoint.isSuccessStatus(status)) {\n\t\t\t\t\t\t\t\tawait publishConstructEvents<any>(\n\t\t\t\t\t\t\t\t\tendpoint as any,\n\t\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t\t\tserviceDiscovery,\n\t\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (HonoEndpoint.isDev) {\n\t\t\t\t\t\t\t\tlogger.info({ status, body: output }, 'Outgoing response');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Respect the endpoint's declared responseType. For JSON (default)\n\t\t\t\t\t\t\t// we use c.json() which sets Content-Type and serializes. For any\n\t\t\t\t\t\t\t// other type, emit the body as-is and set the header explicitly —\n\t\t\t\t\t\t\t// metadata.headers (from r.header()) applied above still wins.\n\t\t\t\t\t\t\tif (endpoint.responseType === 'application/json') {\n\t\t\t\t\t\t\t\t// Hono 4.13 types `c.json`'s status well enough that the\n\t\t\t\t\t\t\t\t// suppression here is now itself an error.\n\t\t\t\t\t\t\t\treturn c.json(output, status);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!(metadata.headers && hasContentTypeHeader(metadata.headers))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tc.header('content-type', endpoint.responseType);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn c.body(output as any, status);\n\t\t\t\t\t\t} catch (validationError: any) {\n\t\t\t\t\t\t\tlogger.error(validationError, 'Output validation failed');\n\t\t\t\t\t\t\tconst error = wrapError(\n\t\t\t\t\t\t\t\tvalidationError,\n\t\t\t\t\t\t\t\t422,\n\t\t\t\t\t\t\t\t'Response validation failed',\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (HonoEndpoint.isDev) {\n\t\t\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t\t\t{ status: error.statusCode, body: error },\n\t\t\t\t\t\t\t\t\t'Outgoing response',\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn c.json(error, error.statusCode as ContentfulStatusCode);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e: any) {\n\t\t\t\t\t\tlogger.error(e, 'Error processing endpoint request');\n\t\t\t\t\t\tconst error = wrapError(e, 500, 'Internal Server Error');\n\t\t\t\t\t\tif (HonoEndpoint.isDev) {\n\t\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t\t{ status: error.statusCode, body: error },\n\t\t\t\t\t\t\t\t'Outgoing response',\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn c.json(error, error.statusCode as ContentfulStatusCode);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t};\n\n\t\t// Register route with conditional validators.\n\t\t//\n\t\t// `route` is a generic `TRoute`, and Hono 4.13 overloads `app.get` on\n\t\t// whether the first argument is a path or a handler. A generic that is\n\t\t// only *constrained* to string does not pick the path overload, so it\n\t\t// gets matched against the handler one and reported there. Saying it is a\n\t\t// string chooses the overload that was always intended.\n\t\t//\n\t\t// The spread is why a cast is needed rather than a better type: with\n\t\t// `...validators` of unknown length, the arity is not decidable, so the\n\t\t// first overload is chosen whatever the path argument says. Naming the\n\t\t// shape we are calling states the intent the overloads cannot infer.\n\t\t(\n\t\t\tapp[method] as unknown as (\n\t\t\t\tpath: string,\n\t\t\t\t...handlers: unknown[]\n\t\t\t) => unknown\n\t\t)(route, ...validators, handler);\n\t}\n\n\tstatic addDocsRoute<\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t>(\n\t\tendpoints: Endpoint<string, HttpMethod, any, any, TServices, TLogger>[],\n\t\tapp: Hono,\n\t\tdocsPath: string,\n\t\topenApiOptions?: HonoEndpointOptions['openApiOptions'],\n\t): void {\n\t\tapp.get(docsPath, async (c) => {\n\t\t\ttry {\n\t\t\t\tconst openApiSchema = await Endpoint.buildOpenApiSchema(\n\t\t\t\t\tendpoints,\n\t\t\t\t\topenApiOptions,\n\t\t\t\t);\n\n\t\t\t\treturn c.json(openApiSchema);\n\t\t\t} catch {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: 'Failed to generate OpenAPI documentation' },\n\t\t\t\t\t500,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,eAAsB,uBACrB,QACA,KAC+D;CAC/D,MAAM,SAAS,GAAG,OAAO,QAAQ,EAAE,IAAI,CAAC;CAExC,MAAM,YAAiE,CAAC;CAExE,WAAW,MAAM,KAAK,QAAQ;EAI7B,MAAM,QAAQ,MAAM,OAFF,KAAK,QAAQ,KAAK,EAAE,SAAS,CAEZ;EAGnC,MAAM,WAAW,OAAO,OAAO,KAAK,CAAC,CAAC,QAAQ,UAAU;GACvD,OAAO,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"file":"HonoEndpointAdaptor-ZDmoZ5LJ.cjs","names":["fg","path","Endpoint","Endpoint","Hono","ServiceDiscovery","timing","honoLogger","validator","runWithRequestContext","createHonoHeaders","createHonoCookies","checkRateLimit","getRateLimitHeaders","createAuditContext","executeWithAuditTransaction","ResponseBuilder","withRlsContext","publishConstructEvents","wrapError"],"sources":["../src/endpoints/helpers.ts","../src/endpoints/parseHonoQuery.ts","../src/endpoints/HonoEndpointAdaptor.ts"],"sourcesContent":["import path from 'node:path';\nimport type { Service } from '@geekmidas/services';\nimport fg from 'fast-glob';\nimport type { HttpMethod } from '../types';\nimport { Endpoint } from './Endpoint';\n\n// Re-export utility functions\n\n/**\n * Recursively finds the project root directory by looking for lock files.\n * Traverses up the directory tree until it finds a package manager lock file.\n *\n * @param cwd - The current working directory to start searching from\n * @returns Promise resolving to the absolute path of the project root\n *\n * @example\n * ```typescript\n * const projectRoot = await getProjectRoot(process.cwd());\n * console.log(`Project root: ${projectRoot}`);\n * // Output: Project root: /Users/user/my-project\n * ```\n */\nexport async function getProjectRoot(cwd: string): Promise<string> {\n\tif (cwd === '/') {\n\t\treturn cwd;\n\t}\n\n\tconst stream = fg.stream(\n\t\t['yarn.lock', 'pnpm-lock.yaml', 'package-lock.json', 'deno.lock'],\n\t\t{ dot: true, cwd },\n\t);\n\n\tlet isRoot = false;\n\n\tfor await (const _ of stream) {\n\t\tisRoot = true;\n\t\tbreak;\n\t}\n\n\tif (isRoot) {\n\t\treturn cwd;\n\t}\n\n\treturn getProjectRoot(path.resolve(cwd, '..'));\n}\n\n/**\n * Discovers and imports all Endpoint instances from the specified route patterns.\n * Uses fast-glob to find files matching the patterns and extracts exported Endpoints.\n *\n * @template TServices - Array of service types used by the endpoints\n * @param routes - Array of glob patterns to match route files (e.g., ['src/routes/*.ts'])\n * @param cwd - The current working directory to resolve paths from\n * @returns Promise resolving to an array of Endpoint instances found in the matched files\n *\n * @example\n * ```typescript\n * // Find all endpoints in the routes directory\n * const endpoints = await getEndpointsFromRoutes(\n * ['src/routes/**\\/*.ts'],\n * process.cwd()\n * );\n *\n * // Register endpoints with your server\n * for (const endpoint of endpoints) {\n * server.register(endpoint);\n * }\n * ```\n *\n * @remarks\n * - Only exports that are valid Endpoint instances are included\n * - Files are imported dynamically, so they must be valid ES modules\n * - The function filters out non-Endpoint exports automatically\n */\nexport async function getEndpointsFromRoutes<TServices extends Service[]>(\n\troutes: string[],\n\tcwd: string,\n): Promise<Endpoint<string, HttpMethod, any, any, TServices>[]> {\n\tconst stream = fg.stream(routes, { cwd });\n\n\tconst endpoints: Endpoint<string, HttpMethod, any, any, TServices>[] = [];\n\n\tfor await (const f of stream) {\n\t\t// Resolve the absolute path for the route file\n\t\tconst routePath = path.resolve(cwd, f.toString());\n\t\t// Dynamically import the route module\n\t\tconst route = await import(routePath);\n\n\t\t// Filter exported values to find only Endpoint instances\n\t\tconst handlers = Object.values(route).filter((value) => {\n\t\t\treturn Endpoint.isEndpoint(value);\n\t\t}) as unknown as Endpoint<string, HttpMethod, any, any, TServices>[];\n\n\t\tendpoints.push(...handlers);\n\t}\n\n\treturn endpoints;\n}\n","import type { Context } from 'hono';\nimport qs from 'qs';\n\n/**\n * Parse Hono query parameters using qs bracket notation\n * Supports nested objects, arrays, and deep nesting via standard bracket syntax\n */\nexport function parseHonoQuery(c: Context): Record<string, any> {\n\tconst url = c.req.url;\n\tconst queryIndex = url.indexOf('?');\n\tif (queryIndex === -1) {\n\t\treturn {};\n\t}\n\tconst queryString = url.slice(queryIndex + 1);\n\treturn qs.parse(queryString) as Record<string, any>;\n}\n","import type { AuditableAction, AuditStorage } from '@geekmidas/audit';\nimport { withRlsContext } from '@geekmidas/db/rls';\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport { wrapError } from '@geekmidas/errors';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport { checkRateLimit, getRateLimitHeaders } from '@geekmidas/rate-limit';\nimport {\n\trunWithRequestContext,\n\ttype Service,\n\tServiceDiscovery,\n\ttype ServiceRecord,\n} from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { type Context, Hono } from 'hono';\nimport { setCookie } from 'hono/cookie';\nimport { logger as honoLogger } from 'hono/logger';\nimport { timing } from 'hono/timing';\nimport type { ContentfulStatusCode } from 'hono/utils/http-status';\nimport { validator } from 'hono/validator';\nimport { publishConstructEvents } from '../publisher';\nimport type { HttpMethod, LowerHttpMethod } from '../types';\nimport type { MappedAudit } from './audit';\nimport {\n\tEndpoint,\n\ttype EndpointContext,\n\ttype EndpointSchemas,\n\tResponseBuilder,\n} from './Endpoint';\nimport { getEndpointsFromRoutes } from './helpers';\nimport { createHonoCookies, createHonoHeaders } from './lazyAccessors';\nimport { parseHonoQuery } from './parseHonoQuery';\nimport {\n\tcreateAuditContext,\n\texecuteWithAuditTransaction,\n} from './processAudits';\n\nexport interface HonoEndpointOptions {\n\t/**\n\t * Path where OpenAPI documentation will be served.\n\t * Set to false to disable docs route.\n\t * @default '/docs'\n\t */\n\tdocsPath?: string | false;\n\t/**\n\t * OpenAPI schema options\n\t */\n\topenApiOptions?: {\n\t\ttitle?: string;\n\t\tversion?: string;\n\t\tdescription?: string;\n\t};\n}\n\n/**\n * Feature flags for an endpoint, analyzed once at route registration time.\n * This avoids per-request feature detection overhead.\n */\ninterface EndpointFeatures {\n\thasServices: boolean;\n\thasDatabase: boolean;\n\thasBodyValidation: boolean;\n\thasQueryValidation: boolean;\n\thasParamValidation: boolean;\n\thasAudits: boolean;\n\thasEvents: boolean;\n\thasRateLimit: boolean;\n\thasRls: boolean;\n}\n\n/**\n * Case-insensitive check for a `content-type` header in a metadata headers map.\n */\nfunction hasContentTypeHeader(headers: Record<string, string>): boolean {\n\tfor (const key of Object.keys(headers)) {\n\t\tif (key.toLowerCase() === 'content-type') return true;\n\t}\n\treturn false;\n}\n\n/**\n * Analyze endpoint features at registration time (not per-request)\n */\nfunction analyzeEndpointFeatures(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t>,\n): EndpointFeatures {\n\treturn {\n\t\thasServices: endpoint.services.length > 0,\n\t\thasDatabase: !!endpoint.databaseService,\n\t\thasBodyValidation: !!endpoint.input?.body,\n\t\thasQueryValidation: !!endpoint.input?.query,\n\t\thasParamValidation: !!endpoint.input?.params,\n\t\t// Audit context needed if declarative audits OR auditor storage service configured (for manual audits)\n\t\thasAudits:\n\t\t\t(endpoint.audits?.length ?? 0) > 0 || !!endpoint.auditorStorageService,\n\t\thasEvents: (endpoint.events?.length ?? 0) > 0,\n\t\thasRateLimit: !!endpoint.rateLimit,\n\t\thasRls: !!endpoint.rlsConfig && !endpoint.rlsBypass,\n\t};\n}\n\nexport class HonoEndpoint<\n\tTRoute extends string,\n\tTMethod extends HttpMethod,\n\tTInput extends EndpointSchemas = {},\n\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n\tTSession = unknown,\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> {\n\tconstructor(\n\t\tprivate readonly endpoint: Endpoint<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTOutSchema,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTSession,\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\tstatic isDev = process.env.NODE_ENV === 'development';\n\n\tstatic async validate<T extends StandardSchemaV1>(\n\t\tc: Context<any, string, {}>,\n\t\tdata: unknown,\n\t\tschema?: T,\n\t) {\n\t\tif (!schema) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst parsed = await Endpoint.validate(schema, data);\n\n\t\tif (parsed.issues) {\n\t\t\treturn c.json(parsed.issues, 422);\n\t\t}\n\n\t\treturn parsed.value;\n\t}\n\taddRoute(\n\t\tserviceDiscovery: ServiceDiscovery<ServiceRecord<TServices>>,\n\t\tapp: Hono,\n\t): void {\n\t\tHonoEndpoint.addRoute(this.endpoint, serviceDiscovery, app);\n\t}\n\n\t/**\n\t * @deprecated Global event middleware is no longer used.\n\t * Events are now published per-route only for endpoints that have events configured.\n\t * This method is kept for backward compatibility but does nothing.\n\t */\n\tstatic applyEventMiddleware(\n\t\t_app: Hono,\n\t\t_serviceDiscovery: ServiceDiscovery<any>,\n\t) {\n\t\t// No-op: Event publishing is now handled per-route in addRoute\n\t\t// This avoids running middleware on every request including 404s\n\t}\n\n\tstatic async fromRoutes<TLogger extends Logger, TServices extends Service[]>(\n\t\troutes: string[],\n\t\tenvParser: EnvironmentParser<{}>,\n\t\tapp = new Hono(),\n\t\t_logger: TLogger,\n\t\tcwd = process.cwd(),\n\t\toptions?: HonoEndpointOptions,\n\t): Promise<Hono> {\n\t\tconst endpoints = await getEndpointsFromRoutes<TServices>(routes, cwd);\n\t\tconst serviceDiscovery =\n\t\t\tServiceDiscovery.getInstance<ServiceRecord<TServices>>(envParser);\n\n\t\tHonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, options);\n\n\t\treturn app;\n\t}\n\n\tstatic addRoutes<\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t>(\n\t\tendpoints: Endpoint<string, HttpMethod, any, any, TServices, TLogger>[],\n\t\tserviceDiscovery: ServiceDiscovery<ServiceRecord<TServices>>,\n\t\tapp: Hono,\n\t\toptions?: HonoEndpointOptions,\n\t): void {\n\t\t// Add timing middleware (always enabled)\n\t\tapp.use('*', timing());\n\n\t\t// Add logger middleware in development mode\n\n\t\tif (HonoEndpoint.isDev) {\n\t\t\tapp.use('*', honoLogger());\n\t\t}\n\n\t\t// Add docs route if not disabled\n\t\tconst docsPath =\n\t\t\toptions?.docsPath !== false ? options?.docsPath || '/docs' : null;\n\t\tif (docsPath) {\n\t\t\tHonoEndpoint.addDocsRoute(\n\t\t\t\tendpoints,\n\t\t\t\tapp,\n\t\t\t\tdocsPath,\n\t\t\t\toptions?.openApiOptions,\n\t\t\t);\n\t\t}\n\n\t\t// Sort endpoints to ensure static routes come before dynamic ones\n\t\tconst sortedEndpoints = endpoints.sort((a, b) => {\n\t\t\tconst aSegments = a.route.split('/');\n\t\t\tconst bSegments = b.route.split('/');\n\n\t\t\t// Compare each segment\n\t\t\tfor (let i = 0; i < Math.max(aSegments.length, bSegments.length); i++) {\n\t\t\t\tconst aSegment = aSegments[i] || '';\n\t\t\t\tconst bSegment = bSegments[i] || '';\n\n\t\t\t\t// If one is dynamic and the other is not, static comes first\n\t\t\t\tconst aIsDynamic = aSegment.startsWith(':');\n\t\t\t\tconst bIsDynamic = bSegment.startsWith(':');\n\n\t\t\t\tif (!aIsDynamic && bIsDynamic) return -1;\n\t\t\t\tif (aIsDynamic && !bIsDynamic) return 1;\n\n\t\t\t\t// If both are the same type, compare alphabetically\n\t\t\t\tif (aSegment !== bSegment) {\n\t\t\t\t\treturn aSegment.localeCompare(bSegment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t});\n\n\t\t// Note: Global event middleware removed for performance\n\t\t// Events are now published per-route only for endpoints with events configured\n\t\tfor (const endpoint of sortedEndpoints) {\n\t\t\tHonoEndpoint.addRoute(endpoint, serviceDiscovery, app);\n\t\t}\n\t}\n\n\t// biome-ignore lint/suspicious/useAdjacentOverloadSignatures: not an overload — the instance `addRoute` above registers this adaptor's own endpoint, this one registers any endpoint on a given app. They share a name because they do the same thing to different subjects.\n\tstatic addRoute<\n\t\tTRoute extends string,\n\t\tTMethod extends HttpMethod,\n\t\tTInput extends EndpointSchemas = {},\n\t\tTOutSchema extends StandardSchemaV1 | undefined = undefined,\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t\tTSession = unknown,\n\t\tTAuditStorage extends AuditStorage | undefined = undefined,\n\t\tTAuditStorageServiceName extends string = string,\n\t\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>,\n\t\tTDatabase = undefined,\n\t\tTDatabaseServiceName extends string = string,\n\t>(\n\t\tendpoint: Endpoint<\n\t\t\tTRoute,\n\t\t\tTMethod,\n\t\t\tTInput,\n\t\t\tTOutSchema,\n\t\t\tTServices,\n\t\t\tTLogger,\n\t\t\tTSession,\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\tserviceDiscovery: ServiceDiscovery<ServiceRecord<TServices>>,\n\t\tapp: Hono,\n\t): void {\n\t\tconst { route } = endpoint;\n\t\tconst method = endpoint.method.toLowerCase() as LowerHttpMethod<TMethod>;\n\n\t\t// Analyze endpoint features once at registration time (not per-request)\n\t\tconst features = analyzeEndpointFeatures(endpoint);\n\n\t\t// Build validators array - only add validators for schemas that exist\n\t\tconst validators: any[] = [];\n\n\t\tif (features.hasBodyValidation) {\n\t\t\tvalidators.push(\n\t\t\t\tvalidator('json', (value, c) =>\n\t\t\t\t\tHonoEndpoint.validate(c, value, endpoint.input?.body),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\tif (features.hasQueryValidation) {\n\t\t\tvalidators.push(\n\t\t\t\tvalidator('query', (_, c) => {\n\t\t\t\t\tconst parsedQuery = parseHonoQuery(c);\n\t\t\t\t\treturn HonoEndpoint.validate(c, parsedQuery, endpoint.input?.query);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tif (features.hasParamValidation) {\n\t\t\tvalidators.push(\n\t\t\t\tvalidator('param', (params, c) =>\n\t\t\t\t\tHonoEndpoint.validate(c, params, endpoint.input?.params),\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\n\t\t// Main handler\n\t\tconst handler = async (c: Context) => {\n\t\t\t// Request context setup\n\t\t\tconst startTime = Date.now();\n\t\t\tconst requestId = c.req.header('X-Request-ID') ?? crypto.randomUUID();\n\n\t\t\tconst logger = endpoint.logger.child({\n\t\t\t\trequestId,\n\t\t\t\tendpoint: endpoint.fullPath,\n\t\t\t\troute: endpoint.route,\n\t\t\t\thost: c.req.header('host'),\n\t\t\t\tmethod: endpoint.method,\n\t\t\t\tpath: c.req.path,\n\t\t\t}) as TLogger;\n\n\t\t\t// Set response header\n\t\t\tc.header('X-Request-ID', requestId);\n\n\t\t\t// Wrap entire handler in request context for services to access\n\t\t\treturn runWithRequestContext(\n\t\t\t\t{ logger, requestId, startTime },\n\t\t\t\tasync () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Lazy accessors - no upfront parsing, use native Hono methods\n\t\t\t\t\t\tconst header = createHonoHeaders(c);\n\t\t\t\t\t\tconst cookie = createHonoCookies(c);\n\n\t\t\t\t\t\t// Only register services if endpoint has any\n\t\t\t\t\t\tconst services = features.hasServices\n\t\t\t\t\t\t\t? await serviceDiscovery.register(endpoint.services)\n\t\t\t\t\t\t\t: ({} as ServiceRecord<TServices>);\n\n\t\t\t\t\t\t// Resolve database service only if configured\n\t\t\t\t\t\tconst rawDb = features.hasDatabase\n\t\t\t\t\t\t\t? await serviceDiscovery\n\t\t\t\t\t\t\t\t\t.register([endpoint.databaseService!])\n\t\t\t\t\t\t\t\t\t.then(\n\t\t\t\t\t\t\t\t\t\t(s) =>\n\t\t\t\t\t\t\t\t\t\t\ts[\n\t\t\t\t\t\t\t\t\t\t\t\tendpoint.databaseService?.serviceName as keyof typeof s\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\t// Extract session (defaults to empty object)\n\t\t\t\t\t\tconst session = await endpoint.getSession({\n\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t...(rawDb !== undefined && { db: rawDb }),\n\t\t\t\t\t\t} as any);\n\n\t\t\t\t\t\t// Check authorization (defaults to true)\n\t\t\t\t\t\tconst isAuthorized = await endpoint.authorize({\n\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t...(rawDb !== undefined && { db: rawDb }),\n\t\t\t\t\t\t\tbody: features.hasBodyValidation\n\t\t\t\t\t\t\t\t? (c.req.valid as any)('json')\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\tquery: features.hasQueryValidation\n\t\t\t\t\t\t\t\t? (c.req.valid as any)('query')\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\tparams: features.hasParamValidation\n\t\t\t\t\t\t\t\t? (c.req.valid as any)('param')\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t} as any);\n\n\t\t\t\t\t\tif (!isAuthorized) {\n\t\t\t\t\t\t\tlogger.warn('Forbidden access attempt');\n\t\t\t\t\t\t\treturn c.json({ error: 'Forbidden' }, 403);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Check rate limit only if configured\n\t\t\t\t\t\tif (features.hasRateLimit) {\n\t\t\t\t\t\t\tconst rateLimitInfo = await checkRateLimit(endpoint.rateLimit!, {\n\t\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\tpath: c.req.path,\n\t\t\t\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tconst rateLimitHeaders = getRateLimitHeaders(\n\t\t\t\t\t\t\t\trateLimitInfo,\n\t\t\t\t\t\t\t\tendpoint.rateLimit!,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(rateLimitHeaders)) {\n\t\t\t\t\t\t\t\tif (value) {\n\t\t\t\t\t\t\t\t\tc.header(key, value);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Create audit context only if audits are configured\n\t\t\t\t\t\tconst auditContext = features.hasAudits\n\t\t\t\t\t\t\t? await createAuditContext(\n\t\t\t\t\t\t\t\t\tendpoint as any,\n\t\t\t\t\t\t\t\t\tserviceDiscovery,\n\t\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\tservices: services as Record<string, unknown>,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\tconst audits = features.hasAudits\n\t\t\t\t\t\t\t? (endpoint.audits as MappedAudit<TAuditAction, TOutSchema>[])\n\t\t\t\t\t\t\t: [];\n\n\t\t\t\t\t\t// Warn if declarative audits are configured but no audit storage\n\t\t\t\t\t\tif (features.hasAudits && !auditContext) {\n\t\t\t\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Extract RLS context only if configured and not bypassed\n\t\t\t\t\t\tconst rlsContext =\n\t\t\t\t\t\t\tfeatures.hasRls && rawDb !== undefined\n\t\t\t\t\t\t\t\t? await endpoint.rlsConfig?.extractor({\n\t\t\t\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\t\t\t\tsession: session as TSession,\n\t\t\t\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\t// Execute handler with automatic audit transaction support\n\t\t\t\t\t\tconst result = await executeWithAuditTransaction(\n\t\t\t\t\t\t\tauditContext,\n\t\t\t\t\t\t\tasync (auditor) => {\n\t\t\t\t\t\t\t\tconst sameDatabase =\n\t\t\t\t\t\t\t\t\tauditContext?.storage?.databaseServiceName &&\n\t\t\t\t\t\t\t\t\tauditContext.storage.databaseServiceName ===\n\t\t\t\t\t\t\t\t\t\tendpoint.databaseService?.serviceName;\n\t\t\t\t\t\t\t\tconst baseDb = sameDatabase\n\t\t\t\t\t\t\t\t\t? (auditor?.getTransaction?.() ?? rawDb)\n\t\t\t\t\t\t\t\t\t: rawDb;\n\n\t\t\t\t\t\t\t\tconst executeHandler = async (db: TDatabase | undefined) => {\n\t\t\t\t\t\t\t\t\tconst responseBuilder = new ResponseBuilder();\n\t\t\t\t\t\t\t\t\tconst response = await endpoint.handler(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tservices,\n\t\t\t\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\t\t\t\tbody: features.hasBodyValidation\n\t\t\t\t\t\t\t\t\t\t\t\t? (c.req.valid as any)('json')\n\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\tquery: features.hasQueryValidation\n\t\t\t\t\t\t\t\t\t\t\t\t? (c.req.valid as any)('query')\n\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\tparams: features.hasParamValidation\n\t\t\t\t\t\t\t\t\t\t\t\t? (c.req.valid as any)('param')\n\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t\t\t\t\theader,\n\t\t\t\t\t\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\t\t\t\t\tauditor,\n\t\t\t\t\t\t\t\t\t\t\tdb,\n\t\t\t\t\t\t\t\t\t\t} as unknown as EndpointContext<\n\t\t\t\t\t\t\t\t\t\t\tTInput,\n\t\t\t\t\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\t\t\t\t\tTLogger,\n\t\t\t\t\t\t\t\t\t\t\tTSession,\n\t\t\t\t\t\t\t\t\t\t\tTAuditAction,\n\t\t\t\t\t\t\t\t\t\t\tTDatabase,\n\t\t\t\t\t\t\t\t\t\t\tTAuditStorage\n\t\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\t\t\tresponseBuilder,\n\t\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\t\tlet data = response;\n\t\t\t\t\t\t\t\t\tlet metadata = responseBuilder.getMetadata();\n\n\t\t\t\t\t\t\t\t\tif (Endpoint.hasMetadata(response)) {\n\t\t\t\t\t\t\t\t\t\tdata = response.data;\n\t\t\t\t\t\t\t\t\t\tmetadata = response.metadata;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst output = endpoint.outputSchema\n\t\t\t\t\t\t\t\t\t\t? await endpoint.parseOutput(data)\n\t\t\t\t\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\t\t\t\t\treturn { output, metadata, responseBuilder };\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tif (features.hasRls && rlsContext && baseDb) {\n\t\t\t\t\t\t\t\t\treturn withRlsContext(\n\t\t\t\t\t\t\t\t\t\tbaseDb as any,\n\t\t\t\t\t\t\t\t\t\trlsContext,\n\t\t\t\t\t\t\t\t\t\tasync (trx) => executeHandler(trx as TDatabase),\n\t\t\t\t\t\t\t\t\t\t{ prefix: endpoint.rlsConfig?.prefix },\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn executeHandler(baseDb as TDatabase | undefined);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tasync (result, auditor) => {\n\t\t\t\t\t\t\t\tif (!audits?.length) return;\n\n\t\t\t\t\t\t\t\tfor (const audit of audits) {\n\t\t\t\t\t\t\t\t\tif (audit.when && !audit.when(result.output as any)) {\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst payload = audit.payload(result.output as any);\n\t\t\t\t\t\t\t\t\tconst entityId = audit.entityId?.(result.output as any);\n\t\t\t\t\t\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\t\t\t\t\t\ttable: audit.table,\n\t\t\t\t\t\t\t\t\t\tentityId,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{ db: rawDb },\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tconst { output, metadata } = result;\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlet status = endpoint.status as ContentfulStatusCode;\n\n\t\t\t\t\t\t\tif (metadata.status) {\n\t\t\t\t\t\t\t\tstatus = metadata.status as ContentfulStatusCode;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (metadata.headers) {\n\t\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(metadata.headers)) {\n\t\t\t\t\t\t\t\t\tc.header(key, value);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (metadata.cookies) {\n\t\t\t\t\t\t\t\tfor (const [name, { value, options }] of metadata.cookies) {\n\t\t\t\t\t\t\t\t\tsetCookie(c, name, value, options);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Only publish events if configured (no global middleware overhead)\n\t\t\t\t\t\t\tif (features.hasEvents && Endpoint.isSuccessStatus(status)) {\n\t\t\t\t\t\t\t\tawait publishConstructEvents<any>(\n\t\t\t\t\t\t\t\t\tendpoint as any,\n\t\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t\t\tserviceDiscovery,\n\t\t\t\t\t\t\t\t\tlogger,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (HonoEndpoint.isDev) {\n\t\t\t\t\t\t\t\tlogger.info({ status, body: output }, 'Outgoing response');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Respect the endpoint's declared responseType. For JSON (default)\n\t\t\t\t\t\t\t// we use c.json() which sets Content-Type and serializes. For any\n\t\t\t\t\t\t\t// other type, emit the body as-is and set the header explicitly —\n\t\t\t\t\t\t\t// metadata.headers (from r.header()) applied above still wins.\n\t\t\t\t\t\t\tif (endpoint.responseType === 'application/json') {\n\t\t\t\t\t\t\t\t// Hono 4.13 types `c.json`'s status well enough that the\n\t\t\t\t\t\t\t\t// suppression here is now itself an error.\n\t\t\t\t\t\t\t\treturn c.json(output, status);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!(metadata.headers && hasContentTypeHeader(metadata.headers))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tc.header('content-type', endpoint.responseType);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn c.body(output as any, status);\n\t\t\t\t\t\t} catch (validationError: any) {\n\t\t\t\t\t\t\tlogger.error(validationError, 'Output validation failed');\n\t\t\t\t\t\t\tconst error = wrapError(\n\t\t\t\t\t\t\t\tvalidationError,\n\t\t\t\t\t\t\t\t422,\n\t\t\t\t\t\t\t\t'Response validation failed',\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (HonoEndpoint.isDev) {\n\t\t\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t\t\t{ status: error.statusCode, body: error },\n\t\t\t\t\t\t\t\t\t'Outgoing response',\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn c.json(error, error.statusCode as ContentfulStatusCode);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e: any) {\n\t\t\t\t\t\tlogger.error(e, 'Error processing endpoint request');\n\t\t\t\t\t\tconst error = wrapError(e, 500, 'Internal Server Error');\n\t\t\t\t\t\tif (HonoEndpoint.isDev) {\n\t\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t\t{ status: error.statusCode, body: error },\n\t\t\t\t\t\t\t\t'Outgoing response',\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn c.json(error, error.statusCode as ContentfulStatusCode);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t};\n\n\t\t// Register route with conditional validators.\n\t\t//\n\t\t// `route` is a generic `TRoute`, and Hono 4.13 overloads `app.get` on\n\t\t// whether the first argument is a path or a handler. A generic that is\n\t\t// only *constrained* to string does not pick the path overload, so it\n\t\t// gets matched against the handler one and reported there. Saying it is a\n\t\t// string chooses the overload that was always intended.\n\t\t//\n\t\t// The spread is why a cast is needed rather than a better type: with\n\t\t// `...validators` of unknown length, the arity is not decidable, so the\n\t\t// first overload is chosen whatever the path argument says. Naming the\n\t\t// shape we are calling states the intent the overloads cannot infer.\n\t\t(\n\t\t\tapp[method] as unknown as (\n\t\t\t\tpath: string,\n\t\t\t\t...handlers: unknown[]\n\t\t\t) => unknown\n\t\t)(route, ...validators, handler);\n\t}\n\n\tstatic addDocsRoute<\n\t\tTServices extends Service[] = [],\n\t\tTLogger extends Logger = Logger,\n\t>(\n\t\tendpoints: Endpoint<string, HttpMethod, any, any, TServices, TLogger>[],\n\t\tapp: Hono,\n\t\tdocsPath: string,\n\t\topenApiOptions?: HonoEndpointOptions['openApiOptions'],\n\t): void {\n\t\tapp.get(docsPath, async (c) => {\n\t\t\ttry {\n\t\t\t\tconst openApiSchema = await Endpoint.buildOpenApiSchema(\n\t\t\t\t\tendpoints,\n\t\t\t\t\topenApiOptions,\n\t\t\t\t);\n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SAAS,YAAY;MAE/C,OAAO,EAAE,KAAK,QAAe,MAAM;KACpC,SAAS,iBAAsB;MAC9B,OAAO,MAAM,iBAAiB,0BAA0B;MACxD,MAAM,SAAA,GAAQC,kBAAAA,UAAAA,CACb,iBACA,KACA,4BACD;MACA,IAAI,aAAa,OAChB,OAAO,KACN;OAAE,QAAQ,MAAM;OAAY,MAAM;MAAM,GACxC,mBACD;MAED,OAAO,EAAE,KAAK,OAAO,MAAM,UAAkC;KAC9D;IACD,SAAS,GAAQ;KAChB,OAAO,MAAM,GAAG,mCAAmC;KACnD,MAAM,SAAA,GAAQA,kBAAAA,UAAAA,CAAU,GAAG,KAAK,uBAAuB;KACvD,IAAI,aAAa,OAChB,OAAO,KACN;MAAE,QAAQ,MAAM;MAAY,MAAM;KAAM,GACxC,mBACD;KAED,OAAO,EAAE,KAAK,OAAO,MAAM,UAAkC;IAC9D;GACD,CACD;EACD;EAcA,IACK,OAAO,CAIV,OAAO,GAAG,YAAY,OAAO;CAChC;CAEA,OAAO,aAIN,WACA,KACA,UACA,gBACO;EACP,IAAI,IAAI,UAAU,OAAO,MAAM;GAC9B,IAAI;IACH,MAAM,gBAAgB,MAAMhB,iBAAAA,SAAS,mBACpC,WACA,cACD;IAEA,OAAO,EAAE,KAAK,aAAa;GAC5B,QAAQ;IACP,OAAO,EAAE,KACR,EAAE,OAAO,2CAA2C,GACpD,GACD;GACD;EACD,CAAC;CACF;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kysely.cjs","names":["canonicalId","provideKey","DEFAULT_POSTGRES_VERSION","serviceKey","Cache","kysely","Kysely","PostgresDialect"],"sources":["../../src/database/kysely.ts"],"sourcesContent":["/**\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 pg from 'pg';\nimport { Cache } from '../cache';\nimport type { Construct } from '../construct-interface';\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}\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\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: pool(as.owner ? (ownerUrl ?? url) : url),\n\t\t\t}),\n\t\t});\n\t}\n}\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 */\nfunction pool(url: string): pg.Pool {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\n\tif (!searchPath) return new pg.Pool({ connectionString: url });\n\n\tparsed.searchParams.delete('search_path');\n\n\treturn new pg.Pool({\n\t\tconnectionString: parsed.toString(),\n\t\toptions: `-c search_path=${searchPath}`,\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>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,iBAAiB;;;;;;;;AAuDvB,IAAa,iBAAb,MAAa,eAEb;CAgBmB;CAflB;CACA;;;;;CAMA;CACA;CACA;CACA;CACA;CAEA,YACC,IACA,UAAkD,CAAC,GACnD,aACC;EAFgB,KAAA,UAAA;EAKjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,SAAS;GACb,MAAA,GAAKC,oBAAAA,WAAAA,CAAW,WAAW,KAAK;GAChC,WAAA,GAAUA,oBAAAA,WAAAA,CAAW,WAAW,UAAU;EAC3C;EACA,KAAK,aAAa,QAAQ,UAAU;EACpC,KAAK,QAAQ,QAAQ,SAAS;EAC9B,KAAK,UAAU,QAAQ,WAAWC,oBAAAA;EAClC,KAAK,cAAc;EAGnB,KAAK,UAAU;GACd,c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