@fuzdev/fuz_app 0.152.0 → 0.154.0

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 (177) hide show
  1. package/dist/actions/CLAUDE.md +14 -11
  2. package/dist/actions/action_rpc.js +3 -3
  3. package/dist/actions/action_types.d.ts +3 -3
  4. package/dist/actions/broadcast_api.d.ts +0 -6
  5. package/dist/actions/broadcast_api.d.ts.map +1 -1
  6. package/dist/actions/connection_closer.d.ts +14 -15
  7. package/dist/actions/connection_closer.d.ts.map +1 -1
  8. package/dist/actions/connection_closer.js +13 -13
  9. package/dist/actions/perform_action.d.ts +5 -1
  10. package/dist/actions/perform_action.d.ts.map +1 -1
  11. package/dist/actions/perform_action.js +57 -19
  12. package/dist/actions/register_action_ws.d.ts +6 -5
  13. package/dist/actions/register_action_ws.d.ts.map +1 -1
  14. package/dist/actions/register_action_ws.js +5 -6
  15. package/dist/auth/CLAUDE.md +44 -14
  16. package/dist/auth/account_actions.d.ts +2 -2
  17. package/dist/auth/account_actions.js +6 -6
  18. package/dist/auth/account_routes.js +9 -9
  19. package/dist/auth/admin_actions.d.ts +2 -1
  20. package/dist/auth/admin_actions.d.ts.map +1 -1
  21. package/dist/auth/admin_actions.js +21 -20
  22. package/dist/auth/audit_emitter.d.ts +111 -64
  23. package/dist/auth/audit_emitter.d.ts.map +1 -1
  24. package/dist/auth/audit_emitter.js +130 -55
  25. package/dist/auth/audit_log_queries.d.ts +9 -10
  26. package/dist/auth/audit_log_queries.d.ts.map +1 -1
  27. package/dist/auth/audit_log_queries.js +13 -10
  28. package/dist/auth/audit_log_routes.js +2 -2
  29. package/dist/auth/audit_log_schema.d.ts +6 -1
  30. package/dist/auth/audit_log_schema.d.ts.map +1 -1
  31. package/dist/auth/bootstrap_account.d.ts +4 -3
  32. package/dist/auth/bootstrap_account.d.ts.map +1 -1
  33. package/dist/auth/bootstrap_account.js +4 -3
  34. package/dist/auth/bootstrap_routes.js +2 -2
  35. package/dist/auth/cell_action_helpers.d.ts +3 -2
  36. package/dist/auth/cell_action_helpers.d.ts.map +1 -1
  37. package/dist/auth/cell_action_helpers.js +9 -10
  38. package/dist/auth/cell_actions.js +6 -6
  39. package/dist/auth/cell_data_schema.d.ts +5 -0
  40. package/dist/auth/cell_data_schema.d.ts.map +1 -1
  41. package/dist/auth/cell_data_schema.js +5 -0
  42. package/dist/auth/cell_field_actions.js +2 -2
  43. package/dist/auth/cell_grant_actions.js +2 -2
  44. package/dist/auth/cell_item_actions.js +3 -3
  45. package/dist/auth/deps.d.ts +12 -10
  46. package/dist/auth/deps.d.ts.map +1 -1
  47. package/dist/auth/middleware.js +1 -1
  48. package/dist/auth/request_context.d.ts +5 -10
  49. package/dist/auth/request_context.d.ts.map +1 -1
  50. package/dist/auth/request_context.js +10 -9
  51. package/dist/auth/role_grant_offer_actions.d.ts +11 -8
  52. package/dist/auth/role_grant_offer_actions.d.ts.map +1 -1
  53. package/dist/auth/role_grant_offer_actions.js +57 -41
  54. package/dist/auth/self_service_role_actions.d.ts +6 -5
  55. package/dist/auth/self_service_role_actions.d.ts.map +1 -1
  56. package/dist/auth/self_service_role_actions.js +17 -6
  57. package/dist/auth/session_cookie.d.ts +4 -4
  58. package/dist/auth/session_cookie.d.ts.map +1 -1
  59. package/dist/auth/session_cookie.js +0 -1
  60. package/dist/auth/session_middleware.d.ts +8 -5
  61. package/dist/auth/session_middleware.d.ts.map +1 -1
  62. package/dist/auth/session_middleware.js +10 -7
  63. package/dist/auth/signup_routes.js +6 -6
  64. package/dist/auth/standard_rpc_actions.d.ts +3 -2
  65. package/dist/auth/standard_rpc_actions.d.ts.map +1 -1
  66. package/dist/auth/standard_rpc_actions.js +3 -2
  67. package/dist/db/CLAUDE.md +10 -1
  68. package/dist/db/create_db.d.ts +18 -1
  69. package/dist/db/create_db.d.ts.map +1 -1
  70. package/dist/db/create_db.js +15 -4
  71. package/dist/db/db.d.ts +27 -0
  72. package/dist/db/db.d.ts.map +1 -1
  73. package/dist/db/db.js +26 -0
  74. package/dist/db/db_checkout_error.d.ts +36 -0
  75. package/dist/db/db_checkout_error.d.ts.map +1 -0
  76. package/dist/db/db_checkout_error.js +48 -0
  77. package/dist/db/db_pg.d.ts +83 -5
  78. package/dist/db/db_pg.d.ts.map +1 -1
  79. package/dist/db/db_pg.js +119 -9
  80. package/dist/db/pg_error.d.ts +4 -0
  81. package/dist/db/pg_error.d.ts.map +1 -1
  82. package/dist/db/pg_error.js +13 -3
  83. package/dist/dev/setup.d.ts +4 -2
  84. package/dist/dev/setup.d.ts.map +1 -1
  85. package/dist/dev/setup.js +12 -5
  86. package/dist/env/env_schemas.d.ts +41 -0
  87. package/dist/env/env_schemas.d.ts.map +1 -0
  88. package/dist/env/env_schemas.js +55 -0
  89. package/dist/env/load.d.ts +23 -15
  90. package/dist/env/load.d.ts.map +1 -1
  91. package/dist/env/load.js +38 -22
  92. package/dist/hono_context.d.ts +36 -6
  93. package/dist/hono_context.d.ts.map +1 -1
  94. package/dist/hono_context.js +29 -2
  95. package/dist/http/CLAUDE.md +11 -10
  96. package/dist/http/db_routes.d.ts +7 -12
  97. package/dist/http/db_routes.d.ts.map +1 -1
  98. package/dist/http/db_routes.js +32 -17
  99. package/dist/http/error_schemas.d.ts +12 -0
  100. package/dist/http/error_schemas.d.ts.map +1 -1
  101. package/dist/http/error_schemas.js +12 -0
  102. package/dist/http/jsonrpc_errors.d.ts +10 -0
  103. package/dist/http/jsonrpc_errors.d.ts.map +1 -1
  104. package/dist/http/jsonrpc_errors.js +14 -0
  105. package/dist/http/jsonrpc_helpers.d.ts +4 -0
  106. package/dist/http/jsonrpc_helpers.d.ts.map +1 -1
  107. package/dist/http/jsonrpc_helpers.js +8 -1
  108. package/dist/http/route_spec.d.ts +4 -4
  109. package/dist/http/route_spec.d.ts.map +1 -1
  110. package/dist/http/route_spec.js +20 -3
  111. package/dist/http/schema_helpers.d.ts +21 -0
  112. package/dist/http/schema_helpers.d.ts.map +1 -1
  113. package/dist/http/schema_helpers.js +38 -0
  114. package/dist/http/surface.d.ts +13 -9
  115. package/dist/http/surface.d.ts.map +1 -1
  116. package/dist/http/surface.js +22 -18
  117. package/dist/realtime/audit_log_sse.d.ts +2 -2
  118. package/dist/realtime/audit_log_sse.js +2 -2
  119. package/dist/schema_meta.d.ts +4 -2
  120. package/dist/schema_meta.d.ts.map +1 -1
  121. package/dist/schema_meta.js +4 -2
  122. package/dist/sensitivity.d.ts +34 -1
  123. package/dist/sensitivity.d.ts.map +1 -1
  124. package/dist/sensitivity.js +32 -2
  125. package/dist/server/app_backend.d.ts +25 -1
  126. package/dist/server/app_backend.d.ts.map +1 -1
  127. package/dist/server/app_backend.js +16 -3
  128. package/dist/server/app_error_handler.d.ts +30 -0
  129. package/dist/server/app_error_handler.d.ts.map +1 -0
  130. package/dist/server/app_error_handler.js +41 -0
  131. package/dist/server/app_server.d.ts +7 -6
  132. package/dist/server/app_server.d.ts.map +1 -1
  133. package/dist/server/app_server.js +6 -2
  134. package/dist/server/env.d.ts +55 -28
  135. package/dist/server/env.d.ts.map +1 -1
  136. package/dist/server/env.js +46 -29
  137. package/dist/testing/CLAUDE.md +23 -17
  138. package/dist/testing/app_server.js +2 -2
  139. package/dist/testing/audit_drift_guard.d.ts.map +1 -1
  140. package/dist/testing/audit_drift_guard.js +2 -0
  141. package/dist/testing/auth_apps.d.ts.map +1 -1
  142. package/dist/testing/auth_apps.js +2 -2
  143. package/dist/testing/cross_backend/conformance_case.d.ts +2 -0
  144. package/dist/testing/cross_backend/conformance_case.d.ts.map +1 -1
  145. package/dist/testing/cross_backend/conformance_case.js +8 -0
  146. package/dist/testing/cross_backend/conformance_table.d.ts.map +1 -1
  147. package/dist/testing/cross_backend/conformance_table.js +24 -7
  148. package/dist/testing/cross_backend/default_backend_configs.d.ts +4 -0
  149. package/dist/testing/cross_backend/default_backend_configs.d.ts.map +1 -1
  150. package/dist/testing/cross_backend/default_backend_configs.js +7 -0
  151. package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts +11 -0
  152. package/dist/testing/cross_backend/rust_spine_stub_backend_config.d.ts.map +1 -1
  153. package/dist/testing/cross_backend/testing_server_core.d.ts +1 -1
  154. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts +15 -11
  155. package/dist/testing/cross_backend/ts_spine_backend_config.d.ts.map +1 -1
  156. package/dist/testing/cross_backend/ts_spine_backend_config.js +3 -12
  157. package/dist/testing/daemon_token_rotation.d.ts +4 -14
  158. package/dist/testing/daemon_token_rotation.d.ts.map +1 -1
  159. package/dist/testing/daemon_token_rotation.js +0 -12
  160. package/dist/testing/db.d.ts.map +1 -1
  161. package/dist/testing/db.js +7 -3
  162. package/dist/testing/middleware.d.ts.map +1 -1
  163. package/dist/testing/middleware.js +2 -2
  164. package/dist/testing/rpc_helpers.d.ts +19 -0
  165. package/dist/testing/rpc_helpers.d.ts.map +1 -1
  166. package/dist/testing/rpc_helpers.js +25 -2
  167. package/dist/testing/schema_parity.d.ts +1 -1
  168. package/dist/testing/stubs.d.ts +2 -2
  169. package/dist/testing/stubs.d.ts.map +1 -1
  170. package/dist/testing/stubs.js +2 -2
  171. package/dist/testing/surface_invariants.js +1 -1
  172. package/dist/testing/ws_round_trip.d.ts.map +1 -1
  173. package/dist/testing/ws_round_trip.js +3 -3
  174. package/dist/zod.d.ts +9 -0
  175. package/dist/zod.d.ts.map +1 -1
  176. package/dist/zod.js +1 -1
  177. package/package.json +6 -10
@@ -1,7 +1,28 @@
1
1
  /**
2
2
  * PostgreSQL driver adapter for `Db`.
3
3
  *
4
- * Provides `create_pg_db()` to construct a `Db` backed by a `pg.Pool`.
4
+ * Provides `create_pg_pool()` to build the pool with a bounded checkout, and
5
+ * `create_pg_db()` to construct a `Db` backed by it.
6
+ *
7
+ * ## Checkout timeout
8
+ *
9
+ * Every checkout from a `create_pg_pool` pool — the wait for a free client,
10
+ * or a new client's connect — gives up after `checkout_timeout_ms`
11
+ * (`connectionTimeoutMillis`; default `DEFAULT_DB_CHECKOUT_TIMEOUT_MS`, 5 s)
12
+ * and throws a `DbCheckoutError` (`db/db_checkout_error.ts`), which every
13
+ * request surface answers with a 503. A query that fails on a client already
14
+ * checked out throws the driver's error as before (a 500). Per-statement
15
+ * `pool.query` and each transaction's `pool.connect()` both check out through
16
+ * the pool's `connect`, so both are bounded. The wait and the connect are
17
+ * bounded one by one, so a checkout that waits and is then handed a slot to
18
+ * connect in can take about twice the bound. `Db.with_checkout_timeout` gives
19
+ * a caller its own bound on the same pool — the audit emitter's pool writes
20
+ * wait `DEFAULT_DB_AUDIT_CHECKOUT_TIMEOUT_MS` (30 s), so a pool saturated
21
+ * enough to shed requests does not also drop the failure rows recording them.
22
+ * A request that awaits its audit row — a failed login does — can therefore
23
+ * wait up to that bound, not the request's. Twin of the Rust
24
+ * `fuz_db::create_pool` / `PoolOptions`.
25
+ *
5
26
  * Statically imports only `pg` types; the `pg` runtime is dynamically
6
27
  * imported where needed — by callers (e.g., `create_db`) that construct the
7
28
  * `Pool`, and by `register_pg_type_parsers` to reach `pg.types`. pglite-only
@@ -11,6 +32,61 @@
11
32
  */
12
33
  import type { Pool } from 'pg';
13
34
  import { type DbDriverResult } from './db.js';
35
+ /** Default bound on one request's pool checkout — Rust `fuz_db::DEFAULT_CHECKOUT_TIMEOUT`. */
36
+ export declare const DEFAULT_DB_CHECKOUT_TIMEOUT_MS = 5000;
37
+ /**
38
+ * Default bound on the checkout behind one audit pool write — Rust
39
+ * `fuz_db::DEFAULT_AUDIT_CHECKOUT_TIMEOUT`.
40
+ */
41
+ export declare const DEFAULT_DB_AUDIT_CHECKOUT_TIMEOUT_MS = 30000;
42
+ /** The largest checkout bound either env var admits (10 minutes) — Rust `DB_CHECKOUT_TIMEOUT_MAX_MS`. */
43
+ export declare const DB_CHECKOUT_TIMEOUT_MAX_MS = 600000;
44
+ /**
45
+ * A `pg.Pool` from `create_pg_pool`: a failed checkout throws `DbCheckoutError`,
46
+ * and `query_with_checkout_timeout` runs one statement under its own bound.
47
+ */
48
+ export interface DbCheckoutPool extends Pool {
49
+ /**
50
+ * `pool.query` with the checkout bounded by `timeout_ms` in place of the
51
+ * pool's own.
52
+ */
53
+ query_with_checkout_timeout: <T>(timeout_ms: number, text: string, values?: Array<unknown>) => Promise<{
54
+ rows: Array<T>;
55
+ }>;
56
+ }
57
+ /** Options for `create_pg_pool`. */
58
+ export interface CreatePgPoolOptions {
59
+ /** The `postgres://` URL. */
60
+ connection_string: string;
61
+ /** Bound on every checkout, in ms — `DEFAULT_DB_CHECKOUT_TIMEOUT_MS` in production. */
62
+ checkout_timeout_ms: number;
63
+ }
64
+ /**
65
+ * Build a `pg.Pool` whose every checkout is bounded by
66
+ * `options.checkout_timeout_ms` and throws `DbCheckoutError` when it fails
67
+ * (module doc, "Checkout timeout").
68
+ *
69
+ * The pool wraps every error of its `connect` — the wait timing out, a new
70
+ * client's connect timing out or failing, a closed pool — and nothing a query
71
+ * on a checked-out client throws. `pool.query` checks out through the same
72
+ * `connect` (pg-pool's `query` calls `this.connect`), so per-statement queries
73
+ * keep pg-pool's own error-listener handling.
74
+ *
75
+ * `query_with_checkout_timeout` lends one statement its own bound by setting
76
+ * `options.connectionTimeoutMillis` for the synchronous span of `query` →
77
+ * `connect`: pg-pool reads it there, to arm the queue wait's timer or a new
78
+ * client's connect timer, and nowhere later on that checkout's path but one —
79
+ * a waiter that a freed slot later hands a brand-new client connects under the
80
+ * pool's own bound. Pinned against the installed pg-pool by
81
+ * `src/test/db/db_pg.db.test.ts`.
82
+ *
83
+ * @param pg - the `pg` module (dynamically imported by the caller)
84
+ * @param options - the URL and the checkout bound
85
+ * @returns the pool
86
+ */
87
+ export declare const create_pg_pool: (pg: {
88
+ Pool: typeof Pool;
89
+ }, options: CreatePgPoolOptions) => DbCheckoutPool;
14
90
  /**
15
91
  * Register the shared pg type-parser overrides on the module-global `pg.types`.
16
92
  *
@@ -38,13 +114,15 @@ import { type DbDriverResult } from './db.js';
38
114
  */
39
115
  export declare const register_pg_type_parsers: () => Promise<void>;
40
116
  /**
41
- * Create a `Db` backed by a `pg.Pool`.
117
+ * Create a `Db` backed by a `create_pg_pool` pool.
42
118
  *
43
119
  * Owns the transaction implementation, acquiring a dedicated pool client
44
- * per transaction.
120
+ * per transaction. `db.with_checkout_timeout(ms)` returns a `Db` over the
121
+ * same pool whose statements check out under `ms` instead (its transactions
122
+ * keep the pool's own bound).
45
123
  *
46
- * @param pool - an already-constructed `pg.Pool`
124
+ * @param pool - a pool from `create_pg_pool`
47
125
  * @returns the `Db` instance and a `close` callback bound to `pool.end()`
48
126
  */
49
- export declare const create_pg_db: (pool: Pool) => DbDriverResult;
127
+ export declare const create_pg_db: (pool: DbCheckoutPool) => DbDriverResult;
50
128
  //# sourceMappingURL=db_pg.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"db_pg.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/db_pg.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAE/B,OAAO,EAA6B,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,wBAAwB,QAAa,OAAO,CAAC,IAAI,CAG7D,CAAC;AA2BF;;;;;;;;GAQG;AACH,eAAO,MAAM,YAAY,GAAI,MAAM,IAAI,KAAG,cAGxC,CAAC"}
1
+ {"version":3,"file":"db_pg.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/db_pg.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,KAAK,EAAE,IAAI,EAA0B,MAAM,IAAI,CAAC;AAEvD,OAAO,EAA6B,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzE,8FAA8F;AAC9F,eAAO,MAAM,8BAA8B,OAAQ,CAAC;AAEpD;;;GAGG;AACH,eAAO,MAAM,oCAAoC,QAAS,CAAC;AAE3D,yGAAyG;AACzG,eAAO,MAAM,0BAA0B,SAAU,CAAC;AAElD;;;GAGG;AACH,MAAM,WAAW,cAAe,SAAQ,IAAI;IAC3C;;;OAGG;IACH,2BAA2B,EAAE,CAAC,CAAC,EAC9B,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,KACnB,OAAO,CAAC;QAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAA;KAAE,CAAC,CAAC;CACjC;AAED,oCAAoC;AACpC,MAAM,WAAW,mBAAmB;IACnC,6BAA6B;IAC7B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,uFAAuF;IACvF,mBAAmB,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,cAAc,GAC1B,IAAI;IAAE,IAAI,EAAE,OAAO,IAAI,CAAA;CAAE,EACzB,SAAS,mBAAmB,KAC1B,cAkDF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,wBAAwB,QAAa,OAAO,CAAC,IAAI,CAG7D,CAAC;AAqCF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,YAAY,GAAI,MAAM,cAAc,KAAG,cAiBnD,CAAC"}
package/dist/db/db_pg.js CHANGED
@@ -1,7 +1,28 @@
1
1
  /**
2
2
  * PostgreSQL driver adapter for `Db`.
3
3
  *
4
- * Provides `create_pg_db()` to construct a `Db` backed by a `pg.Pool`.
4
+ * Provides `create_pg_pool()` to build the pool with a bounded checkout, and
5
+ * `create_pg_db()` to construct a `Db` backed by it.
6
+ *
7
+ * ## Checkout timeout
8
+ *
9
+ * Every checkout from a `create_pg_pool` pool — the wait for a free client,
10
+ * or a new client's connect — gives up after `checkout_timeout_ms`
11
+ * (`connectionTimeoutMillis`; default `DEFAULT_DB_CHECKOUT_TIMEOUT_MS`, 5 s)
12
+ * and throws a `DbCheckoutError` (`db/db_checkout_error.ts`), which every
13
+ * request surface answers with a 503. A query that fails on a client already
14
+ * checked out throws the driver's error as before (a 500). Per-statement
15
+ * `pool.query` and each transaction's `pool.connect()` both check out through
16
+ * the pool's `connect`, so both are bounded. The wait and the connect are
17
+ * bounded one by one, so a checkout that waits and is then handed a slot to
18
+ * connect in can take about twice the bound. `Db.with_checkout_timeout` gives
19
+ * a caller its own bound on the same pool — the audit emitter's pool writes
20
+ * wait `DEFAULT_DB_AUDIT_CHECKOUT_TIMEOUT_MS` (30 s), so a pool saturated
21
+ * enough to shed requests does not also drop the failure rows recording them.
22
+ * A request that awaits its audit row — a failed login does — can therefore
23
+ * wait up to that bound, not the request's. Twin of the Rust
24
+ * `fuz_db::create_pool` / `PoolOptions`.
25
+ *
5
26
  * Statically imports only `pg` types; the `pg` runtime is dynamically
6
27
  * imported where needed — by callers (e.g., `create_db`) that construct the
7
28
  * `Pool`, and by `register_pg_type_parsers` to reach `pg.types`. pglite-only
@@ -10,6 +31,71 @@
10
31
  * @module
11
32
  */
12
33
  import { Db, no_nested_transaction } from './db.js';
34
+ import { DbCheckoutError } from './db_checkout_error.js';
35
+ /** Default bound on one request's pool checkout — Rust `fuz_db::DEFAULT_CHECKOUT_TIMEOUT`. */
36
+ export const DEFAULT_DB_CHECKOUT_TIMEOUT_MS = 5_000;
37
+ /**
38
+ * Default bound on the checkout behind one audit pool write — Rust
39
+ * `fuz_db::DEFAULT_AUDIT_CHECKOUT_TIMEOUT`.
40
+ */
41
+ export const DEFAULT_DB_AUDIT_CHECKOUT_TIMEOUT_MS = 30_000;
42
+ /** The largest checkout bound either env var admits (10 minutes) — Rust `DB_CHECKOUT_TIMEOUT_MAX_MS`. */
43
+ export const DB_CHECKOUT_TIMEOUT_MAX_MS = 600_000;
44
+ /**
45
+ * Build a `pg.Pool` whose every checkout is bounded by
46
+ * `options.checkout_timeout_ms` and throws `DbCheckoutError` when it fails
47
+ * (module doc, "Checkout timeout").
48
+ *
49
+ * The pool wraps every error of its `connect` — the wait timing out, a new
50
+ * client's connect timing out or failing, a closed pool — and nothing a query
51
+ * on a checked-out client throws. `pool.query` checks out through the same
52
+ * `connect` (pg-pool's `query` calls `this.connect`), so per-statement queries
53
+ * keep pg-pool's own error-listener handling.
54
+ *
55
+ * `query_with_checkout_timeout` lends one statement its own bound by setting
56
+ * `options.connectionTimeoutMillis` for the synchronous span of `query` →
57
+ * `connect`: pg-pool reads it there, to arm the queue wait's timer or a new
58
+ * client's connect timer, and nowhere later on that checkout's path but one —
59
+ * a waiter that a freed slot later hands a brand-new client connects under the
60
+ * pool's own bound. Pinned against the installed pg-pool by
61
+ * `src/test/db/db_pg.db.test.ts`.
62
+ *
63
+ * @param pg - the `pg` module (dynamically imported by the caller)
64
+ * @param options - the URL and the checkout bound
65
+ * @returns the pool
66
+ */
67
+ export const create_pg_pool = (pg, options) => {
68
+ const config = {
69
+ connectionString: options.connection_string,
70
+ connectionTimeoutMillis: options.checkout_timeout_ms
71
+ };
72
+ const to_checkout_error = (err) => new DbCheckoutError({ cause: err });
73
+ class CheckoutPool extends pg.Pool {
74
+ connect(callback) {
75
+ if (callback) {
76
+ super.connect((err, client, done) => {
77
+ callback(err ? to_checkout_error(err) : undefined, client, done);
78
+ });
79
+ return;
80
+ }
81
+ return super.connect().catch((err) => {
82
+ throw to_checkout_error(err);
83
+ });
84
+ }
85
+ query_with_checkout_timeout = (timeout_ms, text, values) => {
86
+ const previous = this.options.connectionTimeoutMillis;
87
+ this.options.connectionTimeoutMillis = timeout_ms;
88
+ try {
89
+ const result = this.query(text, values);
90
+ return result;
91
+ }
92
+ finally {
93
+ this.options.connectionTimeoutMillis = previous;
94
+ }
95
+ };
96
+ }
97
+ return new CheckoutPool(config);
98
+ };
13
99
  /**
14
100
  * Register the shared pg type-parser overrides on the module-global `pg.types`.
15
101
  *
@@ -45,6 +131,13 @@ export const register_pg_type_parsers = async () => {
45
131
  * Acquires a dedicated client from the pool for each transaction,
46
132
  * ensuring `BEGIN` / `COMMIT` / `ROLLBACK` all hit the same connection.
47
133
  * Releases the client in `finally` regardless of outcome.
134
+ *
135
+ * Throws when PostgreSQL answers the `COMMIT` with `ROLLBACK` — a statement in
136
+ * the transaction failed and its error was swallowed (an un-awaited promise, a
137
+ * `catch` that never rethrew), so nothing committed. Without the check the
138
+ * caller would read the rolled-back transaction as a success. A handler that
139
+ * answers normally from a failed statement runs it under a savepoint and rolls
140
+ * back to it (`http/db_routes.ts`'s row delete does).
48
141
  */
49
142
  const create_pg_transaction = (pool) => async (fn) => {
50
143
  const client = await pool.connect();
@@ -52,7 +145,10 @@ const create_pg_transaction = (pool) => async (fn) => {
52
145
  await client.query('BEGIN');
53
146
  const tx_db = new Db({ client, transaction: no_nested_transaction });
54
147
  const result = await fn(tx_db);
55
- await client.query('COMMIT');
148
+ const commit = await client.query('COMMIT');
149
+ if (commit.command === 'ROLLBACK') {
150
+ throw new Error('transaction aborted before COMMIT: PostgreSQL rolled it back');
151
+ }
56
152
  return result;
57
153
  }
58
154
  catch (err) {
@@ -64,15 +160,29 @@ const create_pg_transaction = (pool) => async (fn) => {
64
160
  }
65
161
  };
66
162
  /**
67
- * Create a `Db` backed by a `pg.Pool`.
163
+ * Create a `Db` backed by a `create_pg_pool` pool.
68
164
  *
69
165
  * Owns the transaction implementation, acquiring a dedicated pool client
70
- * per transaction.
166
+ * per transaction. `db.with_checkout_timeout(ms)` returns a `Db` over the
167
+ * same pool whose statements check out under `ms` instead (its transactions
168
+ * keep the pool's own bound).
71
169
  *
72
- * @param pool - an already-constructed `pg.Pool`
170
+ * @param pool - a pool from `create_pg_pool`
73
171
  * @returns the `Db` instance and a `close` callback bound to `pool.end()`
74
172
  */
75
- export const create_pg_db = (pool) => ({
76
- db: new Db({ client: pool, transaction: create_pg_transaction(pool) }),
77
- close: () => pool.end()
78
- });
173
+ export const create_pg_db = (pool) => {
174
+ const transaction = create_pg_transaction(pool);
175
+ return {
176
+ db: new Db({
177
+ client: pool,
178
+ transaction,
179
+ with_checkout_timeout: (timeout_ms) => new Db({
180
+ client: {
181
+ query: (text, values) => pool.query_with_checkout_timeout(timeout_ms, text, values)
182
+ },
183
+ transaction
184
+ })
185
+ }),
186
+ close: () => pool.end()
187
+ };
188
+ };
@@ -9,6 +9,10 @@
9
9
  /**
10
10
  * Extract the error-code string from a caught error, for SQLSTATE checks.
11
11
  *
12
+ * A failed pool checkout (`DbCheckoutError`) is read through to its cause, so
13
+ * a connect the server refused (`3D000` for a missing database, `28P01` for a
14
+ * bad password) keeps its code.
15
+ *
12
16
  * Other error families also carry string `code`s (Node FS errors:
13
17
  * `ENOENT`, `ENOSPC`, …) — compare the result against specific SQLSTATE
14
18
  * values, never against truthiness.
@@ -1 +1 @@
1
- {"version":3,"file":"pg_error.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/pg_error.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;;;;;;;GAUG;AACH,eAAO,MAAM,aAAa,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,IAGhD,CAAC;AAET;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,GAAI,OAAO,OAAO,KAAG,OAA2C,CAAC"}
1
+ {"version":3,"file":"pg_error.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/pg_error.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,aAAa,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,IAOvD,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,GAAI,OAAO,OAAO,KAAG,OAA2C,CAAC"}
@@ -6,9 +6,14 @@
6
6
  *
7
7
  * @module
8
8
  */
9
+ import { is_db_checkout_error } from './db_checkout_error.js';
9
10
  /**
10
11
  * Extract the error-code string from a caught error, for SQLSTATE checks.
11
12
  *
13
+ * A failed pool checkout (`DbCheckoutError`) is read through to its cause, so
14
+ * a connect the server refused (`3D000` for a missing database, `28P01` for a
15
+ * bad password) keeps its code.
16
+ *
12
17
  * Other error families also carry string `code`s (Node FS errors:
13
18
  * `ENOENT`, `ENOSPC`, …) — compare the result against specific SQLSTATE
14
19
  * values, never against truthiness.
@@ -17,9 +22,14 @@
17
22
  * @returns the `code` string, or `null` when the value isn't an `Error`
18
23
  * or carries no string `code`
19
24
  */
20
- export const pg_error_code = (error) => error instanceof Error && 'code' in error && typeof error.code === 'string'
21
- ? error.code
22
- : null;
25
+ export const pg_error_code = (error) => {
26
+ const err = is_db_checkout_error(error) ? error.cause : error;
27
+ return err instanceof Error &&
28
+ 'code' in err &&
29
+ typeof err.code === 'string'
30
+ ? err.code
31
+ : null;
32
+ };
23
33
  /**
24
34
  * Check if an error is a PostgreSQL unique constraint violation (error code 23505).
25
35
  *
@@ -127,8 +127,10 @@ export declare const setup_env_file: (deps: FsReadDeps & FsWriteDeps, env_path:
127
127
  /**
128
128
  * Create a bootstrap token file if it doesn't exist.
129
129
  *
130
- * The token is a one-shot secret used to create the first admin account.
131
- * Stored at `~/.{app_name}/secret_bootstrap_token` by default.
130
+ * The token is a one-shot secret used to create the first admin account:
131
+ * 32 random bytes as 64 lowercase hex characters plus one LF, the file
132
+ * `openssl rand -hex 32` writes. Stored at
133
+ * `~/.{app_name}/secret_bootstrap_token` by default.
132
134
  *
133
135
  * @param deps - file and env capabilities
134
136
  * @param app_name - application name (used for default state directory)
@@ -1 +1 @@
1
- {"version":3,"file":"setup.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/dev/setup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,KAAK,EACX,WAAW,EACX,aAAa,EACb,OAAO,EACP,UAAU,EACV,YAAY,EACZ,WAAW,EACX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAYrD;;;;;GAKG;AACH,MAAM,WAAW,WAAW;IAC3B,EAAE,EAAE,CAAC,GAAG,E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C,CAAC;CAC9B;AAED,oCAAoC;AACpC,MAAM,WAAW,oBAAoB;IACpC,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,2CAA2C;AAC3C,MAAM,WAAW,kBAAmB,SAAQ,SAAS;IACpD,oEAAoE;IACpE,aAAa,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CACrD;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,gBAAgB,GAC5B,MAAM,kBAAkB,EACxB,OAAO,mBAAmB,EAC1B,UAAU;IAAE,GAAG,CAAC,EAAE,WAAW,CAAA;CAAE,KAC7B,OAAO,CAAC,oBAAoB,CAwC9B,CAAC"}
package/dist/dev/setup.js CHANGED
@@ -11,7 +11,6 @@
11
11
  import { to_hex } from '@fuzdev/fuz_util/hex.ts';
12
12
  import { load_env_file, parse_dotenv } from '../env/dotenv.js';
13
13
  import { update_env_content } from '../env/update_env_variable.js';
14
- import { generate_random_base64url } from '../crypto.js';
15
14
  import { write_file_atomic } from '../runtime/fs.js';
16
15
  import { query_account_by_username, query_actors_by_account, query_create_account_with_actor } from '../auth/account_queries.js';
17
16
  import { query_create_role_grant } from '../auth/role_grant_queries.js';
@@ -37,6 +36,12 @@ export const parse_db_name = (url) => {
37
36
  return null;
38
37
  }
39
38
  };
39
+ /**
40
+ * Mint an operator-facing secret: 32 random bytes as lowercase hex, the shape
41
+ * `openssl rand -hex 32` writes, so a hand-made secret and a generated one
42
+ * look the same.
43
+ */
44
+ const generate_secret_hex = () => to_hex(crypto.getRandomValues(new Uint8Array(32)));
40
45
  /**
41
46
  * Generate a cookie signing key in-process: 32 random bytes, hex-encoded.
42
47
  *
@@ -45,7 +50,7 @@ export const parse_db_name = (url) => {
45
50
  *
46
51
  * @returns a 64-character lowercase hex key
47
52
  */
48
- export const generate_cookie_key = () => to_hex(crypto.getRandomValues(new Uint8Array(32)));
53
+ export const generate_cookie_key = () => generate_secret_hex();
49
54
  // === File helpers ===
50
55
  /**
51
56
  * Read a single env var from a dotenv-style file.
@@ -133,8 +138,10 @@ export const setup_env_file = async (deps, env_path, example_path, options) => {
133
138
  /**
134
139
  * Create a bootstrap token file if it doesn't exist.
135
140
  *
136
- * The token is a one-shot secret used to create the first admin account.
137
- * Stored at `~/.{app_name}/secret_bootstrap_token` by default.
141
+ * The token is a one-shot secret used to create the first admin account:
142
+ * 32 random bytes as 64 lowercase hex characters plus one LF, the file
143
+ * `openssl rand -hex 32` writes. Stored at
144
+ * `~/.{app_name}/secret_bootstrap_token` by default.
138
145
  *
139
146
  * @param deps - file and env capabilities
140
147
  * @param app_name - application name (used for default state directory)
@@ -161,7 +168,7 @@ export const setup_bootstrap_token = async (deps, app_name, options) => {
161
168
  // existing files), so its 0600 holds unconditionally; the server-side
162
169
  // `read_secure_file` refuses anything laxer at read time.
163
170
  await deps.mkdir(state_dir, { recursive: true, mode: 0o700 });
164
- const token = generate_random_base64url();
171
+ const token = generate_secret_hex();
165
172
  await write_file_atomic(deps, token_path, token + '\n', { mode: 0o600 });
166
173
  log.ok(`Created ~/.${app_name}/secret_bootstrap_token (one-shot, deleted after first use)`);
167
174
  return { created: true, token_path };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * `@fuzdev/fuz_schema` schemas for env var values, matching the Rust spine's
3
+ * readers of the same vars.
4
+ *
5
+ * An env value is a string, so these take a string and output the value it
6
+ * spells: `env_integer` for whole numbers, `EnvStringbool` for booleans.
7
+ *
8
+ * @module
9
+ */
10
+ import { string, type PipeSchema } from '@fuzdev/fuz_schema/schema.ts';
11
+ import '../sensitivity.js';
12
+ /** Options of `env_integer`. */
13
+ export interface EnvIntegerOptions {
14
+ /** The least value accepted, default `0`. */
15
+ min?: number;
16
+ /** The greatest value accepted, default `Number.MAX_SAFE_INTEGER`. */
17
+ max?: number;
18
+ }
19
+ /**
20
+ * A whole number spelled in decimal digits, read the way the Rust spine reads
21
+ * one (`value.trim().parse::<u64>()`): trimmed of Unicode `White_Space` (the
22
+ * set Rust's `trim` strips, not `String.prototype.trim`'s), then decimal
23
+ * digits after at most one leading `+`, so a blank value, a `-`, a fraction,
24
+ * an exponent (`5e3`), and hex (`0x1F90`) are refused, and `+80` and leading
25
+ * zeros (`00080`) are not. The number must be a safe integer within `min` and
26
+ * `max`.
27
+ *
28
+ * @param options - the bounds, default `0` to `Number.MAX_SAFE_INTEGER`
29
+ */
30
+ export declare const env_integer: (options?: EnvIntegerOptions) => PipeSchema<number, typeof string>;
31
+ /**
32
+ * A boolean spelled as a word, matched case-insensitively and not trimmed:
33
+ * `true`, `1`, `yes`, `on`, `y`, or `enabled` for `true`, and `false`, `0`,
34
+ * `no`, `off`, `n`, or `disabled` for `false`. Anything else is refused,
35
+ * `''` and `' true'` included, so a typo doesn't silently flip a feature.
36
+ *
37
+ * The set and the case rule of Zod's `z.stringbool()` defaults, and the twin
38
+ * of the Rust spine's `parse_stringbool`.
39
+ */
40
+ export declare const EnvStringbool: PipeSchema<boolean, typeof string>;
41
+ //# sourceMappingURL=env_schemas.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env_schemas.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/env/env_schemas.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAON,MAAM,EAEN,KAAK,UAAU,EACf,MAAM,8BAA8B,CAAC;AAGtC,OAAO,mBAAmB,CAAC;AAE3B,gCAAgC;AAChC,MAAM,WAAW,iBAAiB;IACjC,6CAA6C;IAC7C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAeD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW,GAAI,UAAU,iBAAiB,KAAG,UAAU,CAAC,MAAM,EAAE,OAAO,MAAM,CAMxF,CAAC;AAmBH;;;;;;;;GAQG;AACH,eAAO,MAAM,aAAa,EAAE,UAAU,CAAC,OAAO,EAAE,OAAO,MAAM,CAO5D,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `@fuzdev/fuz_schema` schemas for env var values, matching the Rust spine's
3
+ * readers of the same vars.
4
+ *
5
+ * An env value is a string, so these take a string and output the value it
6
+ * spells: `env_integer` for whole numbers, `EnvStringbool` for booleans.
7
+ *
8
+ * @module
9
+ */
10
+ import { check, max_value, min_value, pipe, regex, safe_integer, string, transform } from '@fuzdev/fuz_schema/schema.ts';
11
+ // declares `sensitivity` on fuz_schema's `SchemaMeta`, for consumers marking env fields
12
+ import '../sensitivity.js';
13
+ // Unicode `White_Space`, the set Rust's `str::trim` strips (`char::is_whitespace`);
14
+ // `String.prototype.trim` differs, stripping U+FEFF and keeping U+0085
15
+ const WHITE_SPACE_EDGES = /^[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+|[\t\n\v\f\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+$/g;
16
+ // the trimmed value as a number, when it is decimal digits after at most one `+`
17
+ const EnvDigits = pipe(string, transform((v) => v.replace(WHITE_SPACE_EDGES, '')), regex(/^\+?\d+$/, 'decimal digits'), transform(Number));
18
+ /**
19
+ * A whole number spelled in decimal digits, read the way the Rust spine reads
20
+ * one (`value.trim().parse::<u64>()`): trimmed of Unicode `White_Space` (the
21
+ * set Rust's `trim` strips, not `String.prototype.trim`'s), then decimal
22
+ * digits after at most one leading `+`, so a blank value, a `-`, a fraction,
23
+ * an exponent (`5e3`), and hex (`0x1F90`) are refused, and `+80` and leading
24
+ * zeros (`00080`) are not. The number must be a safe integer within `min` and
25
+ * `max`.
26
+ *
27
+ * @param options - the bounds, default `0` to `Number.MAX_SAFE_INTEGER`
28
+ */
29
+ export const env_integer = (options) => pipe(EnvDigits, safe_integer, min_value(options?.min ?? 0), max_value(options?.max ?? Number.MAX_SAFE_INTEGER));
30
+ // the recognized spellings, lowercase, as Zod's `z.stringbool()` defaults and
31
+ // the Rust spine's `parse_stringbool` have them
32
+ const STRINGBOOL_VALUES = new Map([
33
+ ['true', true],
34
+ ['1', true],
35
+ ['yes', true],
36
+ ['on', true],
37
+ ['y', true],
38
+ ['enabled', true],
39
+ ['false', false],
40
+ ['0', false],
41
+ ['no', false],
42
+ ['off', false],
43
+ ['n', false],
44
+ ['disabled', false]
45
+ ]);
46
+ /**
47
+ * A boolean spelled as a word, matched case-insensitively and not trimmed:
48
+ * `true`, `1`, `yes`, `on`, `y`, or `enabled` for `true`, and `false`, `0`,
49
+ * `no`, `off`, `n`, or `disabled` for `false`. Anything else is refused,
50
+ * `''` and `' true'` included, so a typo doesn't silently flip a feature.
51
+ *
52
+ * The set and the case rule of Zod's `z.stringbool()` defaults, and the twin
53
+ * of the Rust spine's `parse_stringbool`.
54
+ */
55
+ export const EnvStringbool = pipe(string, check((v) => STRINGBOOL_VALUES.has(v.toLowerCase()), 'true|1|yes|on|y|enabled or false|0|no|off|n|disabled'), transform((v) => STRINGBOOL_VALUES.get(v.toLowerCase())));
@@ -1,36 +1,37 @@
1
1
  /**
2
- * Generic environment loading from Zod schemas.
2
+ * Generic environment loading from `@fuzdev/fuz_schema` object schemas.
3
3
  *
4
- * Provides `load_env` which iterates Zod schema keys, gets env values, and validates.
5
- * Apps handle error messages themselves (they're always app-specific).
4
+ * Provides `load_env`, which reads each key of an object schema with a
5
+ * getter and validates the values. Apps handle error messages themselves
6
+ * (they're always app-specific).
6
7
  *
7
8
  * @module
8
9
  */
9
- import { z } from 'zod';
10
+ import { type Infer, type Schema, type SchemaIssue } from '@fuzdev/fuz_schema/schema.ts';
10
11
  /**
11
12
  * Error thrown when environment validation fails.
12
13
  *
13
14
  * Contains structured information for apps to format their own error messages.
14
15
  */
15
16
  export declare class EnvValidationError extends Error {
16
- /** The raw env values that were read. */
17
+ /** The raw env values that were read, every key of the schema, unset ones as `undefined`. */
17
18
  readonly raw: Record<string, string | undefined>;
18
- /** The Zod validation error. */
19
- readonly zod_error: z.core.$ZodError;
19
+ /** The validation issues, which hold no env value, only the keys in their paths. */
20
+ readonly issues: Array<SchemaIssue>;
20
21
  /** True if every env var was undefined (nothing loaded). */
21
22
  readonly all_undefined: boolean;
22
- constructor(raw: Record<string, string | undefined>, zod_error: z.core.$ZodError);
23
+ constructor(raw: Record<string, string | undefined>, issues: Array<SchemaIssue>);
23
24
  /**
24
- * Format Zod validation issues as human-readable strings.
25
+ * Format the validation issues as human-readable strings.
25
26
  *
26
- * @returns array of formatted issue strings like `"PORT: Expected number"`
27
+ * @returns array of formatted issue strings like `"PORT: expected decimal digits, received string"`
27
28
  */
28
29
  format_issues(): Array<string>;
29
30
  }
30
31
  /**
31
32
  * Log formatted env validation issues to stderr.
32
33
  *
33
- * Handles the common case: labels each Zod issue with an optional prefix.
34
+ * Handles the common case: labels each issue with an optional prefix.
34
35
  * Callers who want app-specific "getting started" instructions should check
35
36
  * `error.all_undefined` before calling this.
36
37
  *
@@ -39,12 +40,19 @@ export declare class EnvValidationError extends Error {
39
40
  */
40
41
  export declare const log_env_validation_error: (error: EnvValidationError, label?: string) => void;
41
42
  /**
42
- * Load and validate env vars against a Zod schema.
43
+ * Load and validate env vars against a `@fuzdev/fuz_schema` object schema.
43
44
  *
44
- * @param schema - Zod object schema defining expected env vars
45
+ * Reads every key of the schema's entries with `get_env`. An unset var is
46
+ * left out of the object parsed, not given as `undefined`, so it reads as a
47
+ * missing key: a `pipe` that starts with an `optional` runs none of its
48
+ * steps for it, as it would for an absent key of any object. `raw` still
49
+ * lists it, as `undefined`.
50
+ *
51
+ * @param schema - an object schema (`object`, `strip_object`, ..., under any wrappers) of the expected env vars
45
52
  * @param get_env - function to read an env var by key
46
53
  * @returns validated env object
47
- * @throws EnvValidationError if Zod validation fails
54
+ * @throws TypeError if `schema` is not an object schema
55
+ * @throws EnvValidationError if validation fails
48
56
  */
49
- export declare const load_env: <T extends z.ZodObject>(schema: T, get_env: (key: string) => string | undefined) => z.infer<T>;
57
+ export declare const load_env: <T extends Schema<Record<string, unknown>, any>>(schema: T, get_env: (key: string) => string | undefined) => Infer<T>;
50
58
  //# sourceMappingURL=load.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"load.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/env/load.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;GAIG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IAC5C,yCAAyC;IACzC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IACjD,gCAAgC;IAChC,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC;IACrC,4DAA4D;IAC5D,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;gBAEpB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS;IAOhF;;;;OAIG;IACH,aAAa,IAAI,KAAK,CAAC,MAAM,CAAC;CAG9B;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,wBAAwB,GAAI,OAAO,kBAAkB,EAAE,QAAQ,MAAM,KAAG,IAUpF,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ,GAAI,CAAC,SAAS,CAAC,CAAC,SAAS,EAC7C,QAAQ,CAAC,EACT,SAAS,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,KAC1C,CAAC,CAAC,KAAK,CAAC,CAAC,CAaX,CAAC"}
1
+ {"version":3,"file":"load.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/env/load.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAGN,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,W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