@spfn/core 0.2.0-beta.6 → 0.2.0-beta.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +183 -1281
  3. package/dist/authz/index.d.ts +34 -0
  4. package/dist/authz/index.js +415 -0
  5. package/dist/authz/index.js.map +1 -0
  6. package/dist/{boss-DI1r4kTS.d.ts → boss-gXhgctn6.d.ts} +40 -0
  7. package/dist/cache/index.js +42 -30
  8. package/dist/cache/index.js.map +1 -1
  9. package/dist/codegen/index.d.ts +55 -8
  10. package/dist/codegen/index.js +183 -7
  11. package/dist/codegen/index.js.map +1 -1
  12. package/dist/config/index.d.ts +585 -6
  13. package/dist/config/index.js +116 -5
  14. package/dist/config/index.js.map +1 -1
  15. package/dist/db/index.d.ts +379 -75
  16. package/dist/db/index.js +625 -113
  17. package/dist/db/index.js.map +1 -1
  18. package/dist/define-middleware-DuXD8Hvu.d.ts +167 -0
  19. package/dist/env/index.d.ts +26 -2
  20. package/dist/env/index.js +15 -5
  21. package/dist/env/index.js.map +1 -1
  22. package/dist/env/loader.d.ts +26 -19
  23. package/dist/env/loader.js +32 -25
  24. package/dist/env/loader.js.map +1 -1
  25. package/dist/errors/index.d.ts +10 -0
  26. package/dist/errors/index.js +20 -2
  27. package/dist/errors/index.js.map +1 -1
  28. package/dist/event/index.d.ts +33 -3
  29. package/dist/event/index.js +24 -3
  30. package/dist/event/index.js.map +1 -1
  31. package/dist/event/sse/client.d.ts +42 -3
  32. package/dist/event/sse/client.js +128 -45
  33. package/dist/event/sse/client.js.map +1 -1
  34. package/dist/event/sse/index.d.ts +12 -5
  35. package/dist/event/sse/index.js +271 -32
  36. package/dist/event/sse/index.js.map +1 -1
  37. package/dist/event/ws/client.d.ts +59 -0
  38. package/dist/event/ws/client.js +273 -0
  39. package/dist/event/ws/client.js.map +1 -0
  40. package/dist/event/ws/index.d.ts +94 -0
  41. package/dist/event/ws/index.js +272 -0
  42. package/dist/event/ws/index.js.map +1 -0
  43. package/dist/job/index.d.ts +2 -2
  44. package/dist/job/index.js +155 -42
  45. package/dist/job/index.js.map +1 -1
  46. package/dist/logger/index.d.ts +5 -0
  47. package/dist/logger/index.js +14 -0
  48. package/dist/logger/index.js.map +1 -1
  49. package/dist/middleware/index.d.ts +243 -2
  50. package/dist/middleware/index.js +1323 -13
  51. package/dist/middleware/index.js.map +1 -1
  52. package/dist/nextjs/index.d.ts +2 -2
  53. package/dist/nextjs/index.js +77 -31
  54. package/dist/nextjs/index.js.map +1 -1
  55. package/dist/nextjs/server.d.ts +53 -23
  56. package/dist/nextjs/server.js +197 -66
  57. package/dist/nextjs/server.js.map +1 -1
  58. package/dist/route/index.d.ts +138 -146
  59. package/dist/route/index.js +238 -22
  60. package/dist/route/index.js.map +1 -1
  61. package/dist/security/index.d.ts +83 -0
  62. package/dist/security/index.js +173 -0
  63. package/dist/security/index.js.map +1 -0
  64. package/dist/server/index.d.ts +458 -17
  65. package/dist/server/index.js +1756 -277
  66. package/dist/server/index.js.map +1 -1
  67. package/dist/{router-Di7ENoah.d.ts → token-manager-jKD_EsSE.d.ts} +121 -1
  68. package/dist/{types-D_N_U-Py.d.ts → types-7Mhoxnnt.d.ts} +21 -1
  69. package/dist/types-BFB72jbM.d.ts +282 -0
  70. package/dist/types-DVjf37yO.d.ts +205 -0
  71. package/docs/file-upload.md +717 -0
  72. package/package.json +237 -208
  73. package/dist/types-B-e_f2dQ.d.ts +0 -121
@@ -1,12 +1,48 @@
1
1
  import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
2
2
  import postgres, { Sql } from 'postgres';
3
- import * as drizzle_orm from 'drizzle-orm';
4
- import { SQL } from 'drizzle-orm';
5
3
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
6
- import { PgColumn, PgTable } from 'drizzle-orm/pg-core';
4
+ import { PgAsyncDatabase, PgAsyncTransaction, PgColumn, PgTable } from 'drizzle-orm/pg-core';
5
+ import * as drizzle_orm from 'drizzle-orm';
6
+ import { InferSelectModel, SQL, InferInsertModel, AnyRelations, EmptyRelations } from 'drizzle-orm';
7
7
  import * as hono_types from 'hono/types';
8
8
  import { DatabaseError } from '@spfn/core/errors';
9
9
 
10
+ /**
11
+ * Database Manager Types
12
+ */
13
+
14
+ /**
15
+ * DB connection type
16
+ */
17
+ type DbConnectionType = 'read' | 'write';
18
+ /**
19
+ * Common base for PostgreSQL Drizzle drivers.
20
+ *
21
+ * Both the built-in postgres.js database and externally supplied drivers such
22
+ * as PGlite extend this class.
23
+ */
24
+ type DrizzleDatabase = PgAsyncDatabase<any, any>;
25
+ /** Default database type used by the environment-backed postgres.js path. */
26
+ type DefaultDatabase = PostgresJsDatabase;
27
+ /** Resolve the transaction type belonging to a PostgreSQL Drizzle database. */
28
+ type DatabaseTransaction<TDatabase extends DrizzleDatabase> = TDatabase extends PgAsyncDatabase<infer TQueryResult, infer TRelations> ? PgAsyncTransaction<TQueryResult, TRelations> : never;
29
+ /**
30
+ * An externally owned PostgreSQL Drizzle database.
31
+ *
32
+ * The provider owns connection creation. SPFN calls `close` at most once when
33
+ * `closeDatabase()` or server shutdown releases the registered provider.
34
+ */
35
+ interface DatabaseProvider<TDatabase extends DrizzleDatabase = DrizzleDatabase> {
36
+ /** Primary database for writes (and reads when no replica is supplied). */
37
+ write: TDatabase;
38
+ /** Optional read replica. Falls back to `write`. */
39
+ read?: TDatabase;
40
+ /** Driver identifier used for diagnostics, for example `pglite`. */
41
+ kind: string;
42
+ /** Release provider-owned resources. */
43
+ close?: () => void | Promise<void>;
44
+ }
45
+
10
46
  /**
11
47
  * Database Configuration
12
48
  *
@@ -23,11 +59,11 @@ import { DatabaseError } from '@spfn/core/errors';
23
59
  * - src/server/core/db/index.ts (main exports)
24
60
  */
25
61
 
26
- interface DatabaseClients {
62
+ interface DatabaseClients<TDatabase extends DrizzleDatabase = PostgresJsDatabase> {
27
63
  /** Primary database for writes (or both read/write if no replica) */
28
- write?: PostgresJsDatabase;
64
+ write?: TDatabase;
29
65
  /** Replica database for reads (optional, falls back to write) */
30
- read?: PostgresJsDatabase;
66
+ read?: TDatabase;
31
67
  /** Raw postgres client for write operations (for cleanup) */
32
68
  writeClient?: Sql;
33
69
  /** Raw postgres client for read operations (for cleanup) */
@@ -71,6 +107,17 @@ interface DatabaseOptions {
71
107
  */
72
108
  monitoring?: Partial<MonitoringConfig>;
73
109
  }
110
+ /** Database initialization options, including an optional external provider. */
111
+ interface DatabaseInitOptions<TDatabase extends DrizzleDatabase = PostgresJsDatabase> extends DatabaseOptions {
112
+ /**
113
+ * Externally owned PostgreSQL Drizzle provider.
114
+ *
115
+ * When set, environment-based postgres.js initialization, health checks,
116
+ * and automatic reconnect are skipped. The provider's `close` callback is
117
+ * used during shutdown.
118
+ */
119
+ provider?: DatabaseProvider<TDatabase>;
120
+ }
74
121
  /**
75
122
  * Connection pool configuration
76
123
  *
@@ -81,6 +128,21 @@ interface PoolConfig {
81
128
  max: number;
82
129
  /** Idle connection timeout in seconds */
83
130
  idleTimeout: number;
131
+ /**
132
+ * Maximum connections for the read-replica pool. Defaults to `max`. Set
133
+ * separately (DB_POOL_READ_MAX) so a master-replica app can size the two
134
+ * pools independently and keep `write.max + read.max` under the server's
135
+ * `max_connections` (otherwise each process opens up to 2 × max).
136
+ */
137
+ readMax?: number;
138
+ /**
139
+ * Use server-side prepared statements (postgres-js `prepare`). When
140
+ * `undefined`, the connection layer auto-detects: it is disabled for
141
+ * transaction-mode poolers (PgBouncer/Supavisor, e.g. Supabase :6543),
142
+ * where cached statements break as the pooler rotates backends, and
143
+ * enabled otherwise. Set explicitly (or via `SPFN_DB_PREPARE`) to override.
144
+ */
145
+ prepare?: boolean;
84
146
  }
85
147
  /**
86
148
  * Retry configuration for exponential backoff algorithm
@@ -134,15 +196,6 @@ interface RetryConfig {
134
196
  */
135
197
  declare function createDatabaseFromEnv(options?: DatabaseOptions): Promise<DatabaseClients>;
136
198
 
137
- /**
138
- * Database Manager Types
139
- */
140
-
141
- /**
142
- * DB connection type
143
- */
144
- type DbConnectionType = 'read' | 'write';
145
-
146
199
  /**
147
200
  * Global Database instance manager
148
201
  * Provides singleton access to database across all modules
@@ -169,7 +222,7 @@ type DbConnectionType = 'read' | 'write';
169
222
  * const posts = await dbRead.select().from(postsTable);
170
223
  * ```
171
224
  */
172
- declare function getDatabase(type?: DbConnectionType): PostgresJsDatabase<Record<string, unknown>>;
225
+ declare function getDatabase<TDatabase extends DrizzleDatabase = DefaultDatabase>(type?: DbConnectionType): TDatabase;
173
226
  /**
174
227
  * Set global database instances (for testing or manual configuration)
175
228
  *
@@ -199,9 +252,17 @@ declare function getDatabase(type?: DbConnectionType): PostgresJsDatabase<Record
199
252
  * setDatabase(undefined, undefined);
200
253
  * ```
201
254
  */
202
- declare function setDatabase(write: PostgresJsDatabase<Record<string, unknown>> | undefined, read?: PostgresJsDatabase<Record<string, unknown>> | undefined): void;
255
+ declare function setDatabase<TDatabase extends DrizzleDatabase = DefaultDatabase>(write: TDatabase | undefined, read?: TDatabase | undefined): void;
203
256
  /**
204
- * Initialize database from environment variables
257
+ * Register an externally owned PostgreSQL Drizzle provider.
258
+ *
259
+ * This is the synchronous/manual counterpart to `initDatabase({ provider })`.
260
+ * It performs no connection test. Use `closeDatabase()` to invoke the
261
+ * provider's close callback and clear the global instances.
262
+ */
263
+ declare function setDatabaseProvider<TDatabase extends DrizzleDatabase>(provider: DatabaseProvider<TDatabase>): DatabaseClients<TDatabase>;
264
+ /**
265
+ * Initialize a database provider or create postgres.js clients from environment variables
205
266
  * Automatically called by server startup
206
267
  *
207
268
  * Supported environment variables:
@@ -246,14 +307,11 @@ declare function setDatabase(write: PostgresJsDatabase<Record<string, unknown>>
246
307
  * });
247
308
  * ```
248
309
  */
249
- declare function initDatabase(options?: DatabaseOptions): Promise<{
250
- write?: PostgresJsDatabase<Record<string, unknown>>;
251
- read?: PostgresJsDatabase<Record<string, unknown>>;
252
- }>;
310
+ declare function initDatabase<TDatabase extends DrizzleDatabase = DefaultDatabase>(options?: DatabaseInitOptions<TDatabase>): Promise<DatabaseClients<TDatabase>>;
253
311
  /**
254
- * Close all database connections and cleanup
312
+ * Close the active database provider or postgres.js connections and clean up
255
313
  *
256
- * Properly closes postgres connection pools with timeout.
314
+ * Invokes an external provider's close callback, or closes postgres.js pools with timeout.
257
315
  * Should be called during graceful shutdown or after tests.
258
316
  *
259
317
  * @example
@@ -273,6 +331,36 @@ declare function initDatabase(options?: DatabaseOptions): Promise<{
273
331
  * ```
274
332
  */
275
333
  declare function closeDatabase(): Promise<void>;
334
+ /**
335
+ * Force an immediate database pool rebuild
336
+ *
337
+ * Destroys the current postgres.js pool(s) and rebuilds them with the same
338
+ * configuration passed to the original `initDatabase()` call (or whatever
339
+ * was detected from environment variables). Uses the same atomic-swap
340
+ * strategy as the periodic health check: new connections are created and
341
+ * tested BEFORE the old ones are torn down, so `getDatabase()` callers never
342
+ * observe a missing instance.
343
+ *
344
+ * Use this when application code detects that the pool is stuck and does not
345
+ * want to wait for the next periodic health check tick. Concurrent calls are
346
+ * coalesced — if a reconnect is already in progress, this resolves to `false`
347
+ * without starting a second one.
348
+ *
349
+ * @param reason - Short label describing why the rebuild was requested (for logs)
350
+ * @returns `true` if a reconnection ran, `false` if one was already in-flight.
351
+ * Resolves after the rebuild completes (success or max retries exhausted).
352
+ *
353
+ * @example
354
+ * ```typescript
355
+ * import { forceReconnectDatabase } from '@spfn/core/db';
356
+ *
357
+ * app.post('/admin/db/reconnect', async (c) => {
358
+ * const ran = await forceReconnectDatabase('admin_request');
359
+ * return c.json({ reconnected: ran });
360
+ * });
361
+ * ```
362
+ */
363
+ declare function forceReconnectDatabase(reason?: string): Promise<boolean>;
276
364
  /**
277
365
  * Get database connection info (for debugging)
278
366
  *
@@ -306,8 +394,63 @@ declare function getDatabaseInfo(): {
306
394
  hasWrite: boolean;
307
395
  hasRead: boolean;
308
396
  isReplica: boolean;
397
+ providerKind?: string;
309
398
  };
310
399
 
400
+ /**
401
+ * Reconnect Trigger — Query-error driven pool rebuild
402
+ *
403
+ * Complements the periodic health check with a fast-path: when application
404
+ * queries start failing with connection-level errors, we do not wait up to
405
+ * DB_HEALTH_CHECK_INTERVAL (default 60s) to notice. A sliding-window counter
406
+ * trips a force-reconnect as soon as the failure rate crosses a threshold.
407
+ *
408
+ * Why this exists:
409
+ * - postgres.js transparently drops dead sockets and opens new ones on the
410
+ * next query. A single `SELECT 1` on the periodic interval can therefore
411
+ * false-pass while user-facing queries keep hitting the remaining dead
412
+ * sockets in the pool.
413
+ * - This module observes real query errors and, when it sees a burst of
414
+ * connection-level failures, calls triggerForceReconnect() which performs
415
+ * the same atomic-swap rebuild as the health check.
416
+ *
417
+ * Configuration (env vars, hardcoded defaults):
418
+ * - DB_RECONNECT_ERROR_THRESHOLD (default 3): errors needed in window
419
+ * - DB_RECONNECT_ERROR_WINDOW_MS (default 10000): sliding window size
420
+ */
421
+ /**
422
+ * Determine whether an error looks like a pool/connection failure
423
+ *
424
+ * Returns true when any layer in the error chain exposes a connection-level
425
+ * code (postgres.js driver code, Node network errno, PG SQLSTATE class 08 etc.)
426
+ * or is an instance of our own ConnectionError wrapper.
427
+ *
428
+ * Returns false for query errors (syntax, constraint violations, etc.) — those
429
+ * should NOT trigger a pool rebuild.
430
+ */
431
+ declare function isConnectionLevelError(error: unknown): boolean;
432
+ /**
433
+ * Reset the internal error counter
434
+ *
435
+ * Exposed for tests that need a clean slate between cases. Does not clear
436
+ * the WeakSet (which is GC-backed and self-cleans with error lifetimes).
437
+ */
438
+ declare function resetConnectionErrorCounter(): void;
439
+ /**
440
+ * Report a database error to the reconnect trigger
441
+ *
442
+ * Call this from any site that catches a query error before rethrowing.
443
+ * It is a no-op for non-connection-level errors. When the threshold is
444
+ * crossed it calls triggerForceReconnect() in the background — callers
445
+ * should NOT await it.
446
+ *
447
+ * Safe to call from any context: catches its own errors so it cannot
448
+ * disrupt the calling catch block. Deduplicates across error-chain
449
+ * re-wrapping so one failure counts exactly once regardless of how many
450
+ * catch layers it passes through.
451
+ */
452
+ declare function reportDatabaseError(error: unknown): void;
453
+
311
454
  /**
312
455
  * Create database connection with exponential backoff retry strategy
313
456
  *
@@ -380,6 +523,8 @@ interface DrizzleConfigOptions {
380
523
  schemaFilter?: string[];
381
524
  /** Auto-detect PostgreSQL schemas from entity files (requires expandGlobs: true) */
382
525
  autoDetectSchemas?: boolean;
526
+ /** Migration prefix strategy (default: 'timestamp') */
527
+ migrationPrefix?: 'index' | 'timestamp' | 'unix' | 'none';
383
528
  }
384
529
  /**
385
530
  * Detect database dialect from connection URL
@@ -411,6 +556,9 @@ declare function getDrizzleConfig(options?: DrizzleConfigOptions): {
411
556
  dbCredentials: {
412
557
  url: string;
413
558
  };
559
+ migrations: {
560
+ prefix: "timestamp" | "none" | "index" | "unix";
561
+ };
414
562
  schemaFilter?: undefined;
415
563
  } | {
416
564
  schema: string | string[];
@@ -420,6 +568,9 @@ declare function getDrizzleConfig(options?: DrizzleConfigOptions): {
420
568
  url: string;
421
569
  };
422
570
  schemaFilter: string[] | undefined;
571
+ migrations: {
572
+ prefix: "timestamp" | "none" | "index" | "unix";
573
+ };
423
574
  };
424
575
  /**
425
576
  * Generate drizzle.config.ts file content
@@ -442,7 +593,7 @@ declare function generateDrizzleConfigFile(options?: DrizzleConfigOptions): stri
442
593
  * });
443
594
  * ```
444
595
  */
445
- declare function id(): drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_pg_core.PgBigSerial53BuilderInitial<"id">>>;
596
+ declare function id(): drizzle_orm_pg_core.SetIsPrimaryKey<drizzle_orm_pg_core.PgBigSerial53Builder>;
446
597
  /**
447
598
  * Standard timestamp fields (createdAt, updatedAt)
448
599
  *
@@ -469,13 +620,13 @@ declare function id(): drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_
469
620
  * ```
470
621
  */
471
622
  declare function timestamps(): {
472
- createdAt: drizzle_orm.NotNull<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"created_at">>>;
473
- updatedAt: drizzle_orm.NotNull<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgTimestampBuilderInitial<"updated_at">>>;
623
+ createdAt: drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.PgTimestampBuilder>>;
624
+ updatedAt: drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.PgTimestampBuilder>>;
474
625
  };
475
626
  /**
476
627
  * Foreign key reference to another table
477
628
  *
478
- * Creates a bigserial column with cascade delete.
629
+ * Creates a bigint column with cascade delete.
479
630
  * Type-safe: ensures the reference points to a valid PostgreSQL column.
480
631
  *
481
632
  * @param name - Column name (e.g., 'author' creates 'author_id')
@@ -495,7 +646,7 @@ declare function timestamps(): {
495
646
  */
496
647
  declare function foreignKey<T extends PgColumn>(name: string, reference: () => T, options?: {
497
648
  onDelete?: 'cascade' | 'set null' | 'restrict' | 'no action';
498
- }): drizzle_orm.NotNull<drizzle_orm_pg_core.PgBigSerial53BuilderInitial<`${string}_id`>>;
649
+ }): drizzle_orm_pg_core.SetNotNull<drizzle_orm_pg_core.PgBigInt53Builder>;
499
650
  /**
500
651
  * Optional foreign key reference (nullable)
501
652
  *
@@ -515,7 +666,7 @@ declare function foreignKey<T extends PgColumn>(name: string, reference: () => T
515
666
  */
516
667
  declare function optionalForeignKey<T extends PgColumn>(name: string, reference: () => T, options?: {
517
668
  onDelete?: 'cascade' | 'set null' | 'restrict' | 'no action';
518
- }): drizzle_orm_pg_core.PgBigSerial53BuilderInitial<`${string}_id`>;
669
+ }): drizzle_orm_pg_core.PgBigInt53Builder;
519
670
  /**
520
671
  * UUID primary key
521
672
  *
@@ -533,7 +684,7 @@ declare function optionalForeignKey<T extends PgColumn>(name: string, reference:
533
684
  * });
534
685
  * ```
535
686
  */
536
- declare function uuid(): drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm.HasDefault<drizzle_orm_pg_core.PgUUIDBuilderInitial<"id">>>>;
687
+ declare function uuid(): drizzle_orm_pg_core.SetIsPrimaryKey<drizzle_orm_pg_core.SetHasDefault<drizzle_orm_pg_core.PgUUIDBuilder>>;
537
688
  /**
538
689
  * Audit fields for tracking record creators and updaters
539
690
  *
@@ -559,8 +710,8 @@ declare function uuid(): drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_or
559
710
  * ```
560
711
  */
561
712
  declare function auditFields(): {
562
- createdBy: drizzle_orm_pg_core.PgTextBuilderInitial<"created_by", [string, ...string[]]>;
563
- updatedBy: drizzle_orm_pg_core.PgTextBuilderInitial<"updated_by", [string, ...string[]]>;
713
+ createdBy: drizzle_orm_pg_core.PgTextBuilder<[string, ...string[]]>;
714
+ updatedBy: drizzle_orm_pg_core.PgTextBuilder<[string, ...string[]]>;
564
715
  };
565
716
  /**
566
717
  * Publishing fields for content management
@@ -591,8 +742,8 @@ declare function auditFields(): {
591
742
  * ```
592
743
  */
593
744
  declare function publishingFields(): {
594
- publishedAt: drizzle_orm_pg_core.PgTimestampBuilderInitial<"published_at">;
595
- publishedBy: drizzle_orm_pg_core.PgTextBuilderInitial<"published_by", [string, ...string[]]>;
745
+ publishedAt: drizzle_orm_pg_core.PgTimestampBuilder;
746
+ publishedBy: drizzle_orm_pg_core.PgTextBuilder<[string, ...string[]]>;
596
747
  };
597
748
  /**
598
749
  * Custom verification timestamp field
@@ -621,7 +772,7 @@ declare function publishingFields(): {
621
772
  * ```
622
773
  */
623
774
  declare function verificationTimestamp(fieldName: string): {
624
- [x: string]: drizzle_orm_pg_core.PgTimestampBuilderInitial<string>;
775
+ [x: string]: drizzle_orm_pg_core.PgTimestampBuilder;
625
776
  };
626
777
  /**
627
778
  * Soft delete fields
@@ -655,8 +806,8 @@ declare function verificationTimestamp(fieldName: string): {
655
806
  * ```
656
807
  */
657
808
  declare function softDelete(): {
658
- deletedAt: drizzle_orm_pg_core.PgTimestampBuilderInitial<"deleted_at">;
659
- deletedBy: drizzle_orm_pg_core.PgTextBuilderInitial<"deleted_by", [string, ...string[]]>;
809
+ deletedAt: drizzle_orm_pg_core.PgTimestampBuilder;
810
+ deletedBy: drizzle_orm_pg_core.PgTextBuilder<[string, ...string[]]>;
660
811
  };
661
812
  /**
662
813
  * UTC timestamp field
@@ -688,7 +839,7 @@ declare function softDelete(): {
688
839
  * });
689
840
  * ```
690
841
  */
691
- declare function utcTimestamp(fieldName: string, mode?: 'date' | 'string'): drizzle_orm_pg_core.PgTimestampBuilderInitial<string>;
842
+ declare function utcTimestamp(fieldName: string, mode?: 'date' | 'string'): drizzle_orm_pg_core.PgTimestampBuilder;
692
843
  /**
693
844
  * Type-safe enum text field
694
845
  *
@@ -722,7 +873,7 @@ declare function utcTimestamp(fieldName: string, mode?: 'date' | 'string'): driz
722
873
  * });
723
874
  * ```
724
875
  */
725
- declare function enumText<T extends readonly [string, ...string[]]>(fieldName: string, values: T): drizzle_orm_pg_core.PgTextBuilderInitial<string, drizzle_orm.Writable<T & [string, ...string[]]>>;
876
+ declare function enumText<T extends readonly [string, ...string[]]>(fieldName: string, values: T): drizzle_orm_pg_core.PgTextBuilder<drizzle_orm.Writable<T & [string, ...string[]]>>;
726
877
  /**
727
878
  * Type-safe JSONB field
728
879
  *
@@ -765,7 +916,7 @@ declare function enumText<T extends readonly [string, ...string[]]>(fieldName: s
765
916
  * tags: typedJsonb<string[]>('tags').notNull(),
766
917
  * ```
767
918
  */
768
- declare function typedJsonb<T>(fieldName: string): drizzle_orm.$Type<drizzle_orm_pg_core.PgJsonbBuilderInitial<string>, T>;
919
+ declare function typedJsonb<T>(fieldName: string): drizzle_orm_pg_core.Set$Type<drizzle_orm_pg_core.PgJsonbBuilder, T>;
769
920
 
770
921
  /**
771
922
  * Database Schema Helper
@@ -842,26 +993,37 @@ declare function getSchemaInfo(packageName: string): {
842
993
  */
843
994
 
844
995
  /**
845
- * Transaction database type
846
- * Uses Record<string, unknown> to accept any schema shape
996
+ * Transaction type belonging to a PostgreSQL Drizzle database.
997
+ */
998
+ type TransactionDB<TDatabase extends DrizzleDatabase = DefaultDatabase> = DatabaseTransaction<TDatabase>;
999
+ /**
1000
+ * afterCommit callback type
847
1001
  */
848
- type TransactionDB = PostgresJsDatabase<Record<string, unknown>>;
1002
+ type AfterCommitCallback = () => void | Promise<void>;
849
1003
  /**
850
1004
  * Transaction context stored in AsyncLocalStorage
851
1005
  */
852
- type TransactionContext = {
1006
+ type TransactionContext<TDatabase extends DrizzleDatabase = DrizzleDatabase> = {
853
1007
  /** The actual Drizzle transaction object */
854
- tx: TransactionDB;
1008
+ tx: TransactionDB<TDatabase>;
855
1009
  /** Unique transaction ID for logging and tracing */
856
1010
  txId: string;
857
1011
  level: number;
1012
+ /** Callbacks to execute after root transaction commits */
1013
+ afterCommitCallbacks: AfterCommitCallback[];
858
1014
  };
1015
+ /**
1016
+ * Get current transaction object and metadata from AsyncLocalStorage
1017
+ *
1018
+ * @returns TransactionContext if available, null otherwise
1019
+ */
1020
+ declare function getTransactionContext<TDatabase extends DrizzleDatabase = DefaultDatabase>(): TransactionContext<TDatabase> | null;
859
1021
  /**
860
1022
  * Get current transaction from AsyncLocalStorage
861
1023
  *
862
1024
  * @returns Transaction if available, null otherwise
863
1025
  */
864
- declare function getTransaction(): TransactionDB | null;
1026
+ declare function getTransaction<TDatabase extends DrizzleDatabase = DefaultDatabase>(): TransactionDB<TDatabase> | null;
865
1027
  /**
866
1028
  * Run a function within a transaction context
867
1029
  *
@@ -873,8 +1035,33 @@ declare function getTransaction(): TransactionDB | null;
873
1035
  * @param callback - Function to run within transaction context
874
1036
  * @returns Result of the callback
875
1037
  */
876
- declare function runWithTransaction<T>(tx: TransactionDB, txId: string, // Add txId parameter
1038
+ declare function runWithTransaction<T, TDatabase extends DrizzleDatabase = DefaultDatabase>(tx: TransactionDB<TDatabase>, txId: string, // Add txId parameter
877
1039
  callback: () => Promise<T>): Promise<T>;
1040
+ /**
1041
+ * Register a callback to run after the current transaction commits
1042
+ *
1043
+ * - Inside a transaction: queued and executed after root transaction commits
1044
+ * - Outside a transaction: executed immediately (already "committed")
1045
+ * - Nested transactions: callbacks bubble up to root transaction
1046
+ * - Callbacks run outside transaction context (new connection for DB access)
1047
+ * - Errors are logged but never thrown (commit already succeeded)
1048
+ *
1049
+ * @example
1050
+ * ```typescript
1051
+ * import { onAfterCommit } from '@spfn/core/db/transaction';
1052
+ *
1053
+ * async function submit(spaceId: string, chatId: string)
1054
+ * {
1055
+ * const publication = await publicationRepo.create({...});
1056
+ * await requestRepo.updateStatusAtomically(...);
1057
+ *
1058
+ * onAfterCommit(() => generateArticle(spaceId, chatId, publication.id));
1059
+ *
1060
+ * return publication;
1061
+ * }
1062
+ * ```
1063
+ */
1064
+ declare function onAfterCommit(callback: AfterCommitCallback): void;
878
1065
 
879
1066
  /**
880
1067
  * Transaction middleware options
@@ -910,6 +1097,15 @@ interface TransactionalOptions {
910
1097
  * ```
911
1098
  */
912
1099
  timeout?: number;
1100
+ /**
1101
+ * Idle-in-transaction timeout in milliseconds — Postgres reclaims the pooled
1102
+ * connection if the transaction sits idle (e.g. the handler awaits external
1103
+ * I/O) longer than this. A backstop against pool starvation, not a license
1104
+ * to do non-DB work inside a transaction. `0` disables it.
1105
+ *
1106
+ * @default 30000 (30s) or TRANSACTION_IDLE_TIMEOUT environment variable
1107
+ */
1108
+ idleTimeout?: number;
913
1109
  }
914
1110
  /**
915
1111
  * Transaction middleware for Hono routes
@@ -955,6 +1151,93 @@ interface TransactionalOptions {
955
1151
  */
956
1152
  declare function Transactional(options?: TransactionalOptions): hono_types.MiddlewareHandler<any, string, {}, Response>;
957
1153
 
1154
+ /**
1155
+ * Transaction runner options
1156
+ */
1157
+ interface RunInTransactionOptions {
1158
+ /**
1159
+ * Slow transaction warning threshold in milliseconds
1160
+ * @default 1000 (1 second)
1161
+ */
1162
+ slowThreshold?: number;
1163
+ /**
1164
+ * Enable transaction logging
1165
+ * @default true
1166
+ */
1167
+ enableLogging?: boolean;
1168
+ /**
1169
+ * Transaction timeout in milliseconds
1170
+ *
1171
+ * Sets PostgreSQL `statement_timeout` to enforce database-level timeout.
1172
+ * If transaction exceeds this duration, PostgreSQL will automatically cancel
1173
+ * the query and rollback the transaction, ensuring data consistency.
1174
+ *
1175
+ * Behavior:
1176
+ * - `timeout: 0` - Disables timeout (unlimited execution time)
1177
+ * - `timeout: null` - Uses default (30s or TRANSACTION_TIMEOUT env var)
1178
+ * - `timeout: undefined` - Uses default (30s or TRANSACTION_TIMEOUT env var)
1179
+ * - `timeout: N` - Sets timeout to N milliseconds (1 to 2147483647)
1180
+ *
1181
+ * Note: Timeout is only applied to root transactions. Nested transactions
1182
+ * (SAVEPOINTs) inherit the timeout from the outer transaction.
1183
+ *
1184
+ * @default 30000 (30 seconds) or TRANSACTION_TIMEOUT environment variable
1185
+ *
1186
+ * @example
1187
+ * ```typescript
1188
+ * // Use default timeout (30s)
1189
+ * await runInTransaction(callback);
1190
+ *
1191
+ * // Disable timeout for long-running operations
1192
+ * await runInTransaction(callback, { timeout: 0 });
1193
+ *
1194
+ * // Set custom timeout (60s)
1195
+ * await runInTransaction(callback, { timeout: 60000 });
1196
+ * ```
1197
+ */
1198
+ timeout?: number;
1199
+ /**
1200
+ * Idle-in-transaction timeout in milliseconds (root transactions only).
1201
+ *
1202
+ * Sets PostgreSQL `idle_in_transaction_session_timeout`: if the transaction
1203
+ * sits open without running a query for longer than this — e.g. while the
1204
+ * handler awaits external I/O inside the transaction — Postgres terminates
1205
+ * the session and rolls back, reclaiming the pooled connection instead of
1206
+ * letting one stuck request hold it (and its row locks) indefinitely.
1207
+ *
1208
+ * Do not put external I/O inside a transaction; this is a backstop, not a
1209
+ * license. `0` disables it.
1210
+ *
1211
+ * @default 30000 (30s) or TRANSACTION_IDLE_TIMEOUT environment variable
1212
+ */
1213
+ idleTimeout?: number;
1214
+ /**
1215
+ * Context string for logging (e.g., 'migration:add-user', 'script:cleanup')
1216
+ * @default 'transaction'
1217
+ */
1218
+ context?: string;
1219
+ }
1220
+ /**
1221
+ * Run a callback function within a database transaction
1222
+ *
1223
+ * Automatically manages transaction lifecycle:
1224
+ * - Commits on success
1225
+ * - Rolls back on error
1226
+ * - Tracks execution time
1227
+ * - Warns about slow transactions
1228
+ * - Enforces timeout if configured
1229
+ *
1230
+ * Errors are propagated to the caller without modification.
1231
+ * Caller is responsible for error handling and conversion.
1232
+ *
1233
+ * @param callback - Function to execute within transaction
1234
+ * @param options - Transaction options
1235
+ * @returns Result of callback function
1236
+ * @throws TransactionError if database not initialized or timeout exceeded
1237
+ * @throws Any error thrown by callback function
1238
+ */
1239
+ declare function runInTransaction<T, TDatabase extends DrizzleDatabase = DefaultDatabase>(callback: (tx: TransactionDB<TDatabase>) => Promise<T>, options?: RunInTransactionOptions): Promise<T>;
1240
+
958
1241
  /**
959
1242
  * PostgreSQL Error Conversion Utilities
960
1243
  *
@@ -1007,14 +1290,6 @@ declare function fromPostgresError(error: any): DatabaseError;
1007
1290
  * ```
1008
1291
  */
1009
1292
 
1010
- /**
1011
- * Infer SELECT model from PgTable
1012
- */
1013
- type InferSelectModel<T extends PgTable> = T['$inferSelect'];
1014
- /**
1015
- * Infer INSERT model from PgTable
1016
- */
1017
- type InferInsertModel<T extends PgTable> = T['$inferInsert'];
1018
1293
  /**
1019
1294
  * Object-based where condition (AND only, equality only)
1020
1295
  */
@@ -1279,10 +1554,10 @@ declare function count<T extends PgTable>(table: T, where?: WhereObject<InferSel
1279
1554
  *
1280
1555
  * @example With Custom Schema Type
1281
1556
  * ```typescript
1282
- * import type { AppSchema } from './schema';
1557
+ * import type { AppRelations } from './relations';
1283
1558
  *
1284
- * export class UserRepository extends BaseRepository<AppSchema> {
1285
- * // Now this.db and this.readDb are typed with AppSchema
1559
+ * export class UserRepository extends BaseRepository<AppRelations> {
1560
+ * // Now this.db and this.readDb preserve the app's Drizzle relations
1286
1561
  * }
1287
1562
  * ```
1288
1563
  *
@@ -1302,6 +1577,8 @@ declare function count<T extends PgTable>(table: T, where?: WhereObject<InferSel
1302
1577
  * ```
1303
1578
  */
1304
1579
 
1580
+ /** Database surface available to repositories inside and outside transactions. */
1581
+ type RepositoryDatabase<TDatabase extends DrizzleDatabase> = TDatabase extends PgAsyncDatabase<infer TQueryResult, infer TRelations> ? PgAsyncDatabase<TQueryResult, TRelations> : never;
1305
1582
  /**
1306
1583
  * Enhanced error class that includes repository context
1307
1584
  */
@@ -1323,9 +1600,10 @@ declare class RepositoryError extends Error {
1323
1600
  * - Inside transaction: Uses transaction DB
1324
1601
  * - Outside transaction: Uses global DB instance (with read/write separation)
1325
1602
  *
1326
- * @template TSchema - Database schema type (defaults to Record<string, unknown>)
1603
+ * @template TRelations - Drizzle relations type (defaults to no relations)
1604
+ * @template TDatabase - PostgreSQL Drizzle driver type (defaults to postgres.js)
1327
1605
  */
1328
- declare abstract class BaseRepository<TSchema extends Record<string, unknown> = Record<string, unknown>> {
1606
+ declare abstract class BaseRepository<TRelations extends AnyRelations = EmptyRelations, TDatabase extends DrizzleDatabase = PostgresJsDatabase<TRelations>> {
1329
1607
  /**
1330
1608
  * Write database instance
1331
1609
  *
@@ -1342,7 +1620,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1342
1620
  * }
1343
1621
  * ```
1344
1622
  */
1345
- protected get db(): PostgresJsDatabase<TSchema>;
1623
+ protected get db(): RepositoryDatabase<TDatabase>;
1346
1624
  /**
1347
1625
  * Read database instance
1348
1626
  *
@@ -1363,7 +1641,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1363
1641
  * }
1364
1642
  * ```
1365
1643
  */
1366
- protected get readDb(): PostgresJsDatabase<TSchema>;
1644
+ protected get readDb(): RepositoryDatabase<TDatabase>;
1367
1645
  /**
1368
1646
  * Wrap query execution with repository context
1369
1647
  *
@@ -1409,7 +1687,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1409
1687
  * const user = await this._findOne(users, eq(users.id, 1));
1410
1688
  * ```
1411
1689
  */
1412
- protected _findOne<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined): Promise<T['$inferSelect'] | null>;
1690
+ protected _findOne<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined): Promise<InferSelectModel<T> | null>;
1413
1691
  /**
1414
1692
  * Find multiple records
1415
1693
  *
@@ -1431,7 +1709,33 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1431
1709
  orderBy?: SQL | SQL[];
1432
1710
  limit?: number;
1433
1711
  offset?: number;
1434
- }): Promise<T['$inferSelect'][]>;
1712
+ }): Promise<InferSelectModel<T>[]>;
1713
+ /**
1714
+ * Keyset (cursor) pagination — O(limit) instead of OFFSET's O(offset).
1715
+ *
1716
+ * Pages by a strictly-ordered, unique column instead of a numeric offset, so a
1717
+ * deep page doesn't scan and discard everything before it. Pass the cursor
1718
+ * column's value from the last row of the previous page as `after`; omit it for
1719
+ * the first page. The column must be unique and the sole sort key (e.g. an
1720
+ * auto-increment id or a ULID).
1721
+ *
1722
+ * @example
1723
+ * ```typescript
1724
+ * const page1 = await this._findManyKeyset(users, { cursorColumn: users.id, limit: 20 });
1725
+ * const page2 = await this._findManyKeyset(users, {
1726
+ * cursorColumn: users.id,
1727
+ * after: page1.at(-1)?.id,
1728
+ * limit: 20,
1729
+ * });
1730
+ * ```
1731
+ */
1732
+ protected _findManyKeyset<T extends PgTable>(table: T, options: {
1733
+ cursorColumn: PgColumn;
1734
+ limit: number;
1735
+ after?: string | number | bigint | Date;
1736
+ order?: 'asc' | 'desc';
1737
+ where?: Record<string, any> | SQL | undefined;
1738
+ }): Promise<InferSelectModel<T>[]>;
1435
1739
  /**
1436
1740
  * Create a new record
1437
1741
  *
@@ -1447,7 +1751,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1447
1751
  * });
1448
1752
  * ```
1449
1753
  */
1450
- protected _create<T extends PgTable>(table: T, data: T['$inferInsert']): Promise<T['$inferSelect']>;
1754
+ protected _create<T extends PgTable>(table: T, data: InferInsertModel<T>): Promise<InferSelectModel<T>>;
1451
1755
  /**
1452
1756
  * Create multiple records
1453
1757
  *
@@ -1463,7 +1767,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1463
1767
  * ]);
1464
1768
  * ```
1465
1769
  */
1466
- protected _createMany<T extends PgTable>(table: T, data: T['$inferInsert'][]): Promise<T['$inferSelect'][]>;
1770
+ protected _createMany<T extends PgTable>(table: T, data: InferInsertModel<T>[]): Promise<InferSelectModel<T>[]>;
1467
1771
  /**
1468
1772
  * Upsert a record (INSERT or UPDATE on conflict)
1469
1773
  *
@@ -1483,10 +1787,10 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1483
1787
  * });
1484
1788
  * ```
1485
1789
  */
1486
- protected _upsert<T extends PgTable>(table: T, data: T['$inferInsert'], options: {
1790
+ protected _upsert<T extends PgTable>(table: T, data: InferInsertModel<T>, options: {
1487
1791
  target: PgColumn[];
1488
- set?: Partial<T['$inferInsert']> | Record<string, SQL | any>;
1489
- }): Promise<T['$inferSelect']>;
1792
+ set?: Partial<InferInsertModel<T>> | Record<string, SQL | any>;
1793
+ }): Promise<InferSelectModel<T>>;
1490
1794
  /**
1491
1795
  * Update a single record
1492
1796
  *
@@ -1503,7 +1807,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1503
1807
  * );
1504
1808
  * ```
1505
1809
  */
1506
- protected _updateOne<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined, data: Partial<T['$inferInsert']>): Promise<T['$inferSelect'] | null>;
1810
+ protected _updateOne<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined, data: Partial<InferInsertModel<T>>): Promise<InferSelectModel<T> | null>;
1507
1811
  /**
1508
1812
  * Update multiple records
1509
1813
  *
@@ -1520,7 +1824,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1520
1824
  * );
1521
1825
  * ```
1522
1826
  */
1523
- protected _updateMany<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined, data: Partial<T['$inferInsert']>): Promise<T['$inferSelect'][]>;
1827
+ protected _updateMany<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined, data: Partial<InferInsertModel<T>>): Promise<InferSelectModel<T>[]>;
1524
1828
  /**
1525
1829
  * Delete a single record
1526
1830
  *
@@ -1533,7 +1837,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1533
1837
  * const user = await this._deleteOne(users, { id: 1 });
1534
1838
  * ```
1535
1839
  */
1536
- protected _deleteOne<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined): Promise<T['$inferSelect'] | null>;
1840
+ protected _deleteOne<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined): Promise<InferSelectModel<T> | null>;
1537
1841
  /**
1538
1842
  * Delete multiple records
1539
1843
  *
@@ -1546,7 +1850,7 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1546
1850
  * const users = await this._deleteMany(users, { verified: false });
1547
1851
  * ```
1548
1852
  */
1549
- protected _deleteMany<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined): Promise<T['$inferSelect'][]>;
1853
+ protected _deleteMany<T extends PgTable>(table: T, where: Record<string, any> | SQL | undefined): Promise<InferSelectModel<T>[]>;
1550
1854
  /**
1551
1855
  * Count records
1552
1856
  *
@@ -1563,4 +1867,4 @@ declare abstract class BaseRepository<TSchema extends Record<string, unknown> =
1563
1867
  protected _count<T extends PgTable>(table: T, where?: Record<string, any> | SQL | undefined): Promise<number>;
1564
1868
  }
1565
1869
 
1566
- export { BaseRepository, type DatabaseClients, type DrizzleConfigOptions, type PoolConfig, RepositoryError, type RetryConfig, type TransactionContext, type TransactionDB, Transactional, type TransactionalOptions, auditFields, checkConnection, closeDatabase, count, create, createDatabaseConnection, createDatabaseFromEnv, createMany, createSchema, deleteMany, deleteOne, detectDialect, enumText, findMany, findOne, foreignKey, fromPostgresError, generateDrizzleConfigFile, getDatabase, getDatabaseInfo, getDrizzleConfig, getSchemaInfo, getTransaction, id, initDatabase, optionalForeignKey, packageNameToSchema, publishingFields, runWithTransaction, setDatabase, softDelete, timestamps, typedJsonb, updateMany, updateOne, upsert, utcTimestamp, uuid, verificationTimestamp };
1870
+ export { type AfterCommitCallback, BaseRepository, type DatabaseClients, type DatabaseInitOptions, type DatabaseOptions, type DatabaseProvider, type DatabaseTransaction, type DefaultDatabase, type DrizzleConfigOptions, type DrizzleDatabase, type PoolConfig, type RepositoryDatabase, RepositoryError, type RetryConfig, type RunInTransactionOptions, type TransactionContext, type TransactionDB, Transactional, type TransactionalOptions, auditFields, checkConnection, closeDatabase, count, create, createDatabaseConnection, createDatabaseFromEnv, createMany, createSchema, deleteMany, deleteOne, detectDialect, enumText, findMany, findOne, forceReconnectDatabase, foreignKey, fromPostgresError, generateDrizzleConfigFile, getDatabase, getDatabaseInfo, getDrizzleConfig, getSchemaInfo, getTransaction, getTransactionContext, id, initDatabase, isConnectionLevelError, onAfterCommit, optionalForeignKey, packageNameToSchema, publishingFields, reportDatabaseError, resetConnectionErrorCounter, runInTransaction, runWithTransaction, setDatabase, setDatabaseProvider, softDelete, timestamps, typedJsonb, updateMany, updateOne, upsert, utcTimestamp, uuid, verificationTimestamp };