@rdlabo/workers-hono-kit 0.2.0 → 0.3.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 (104) hide show
  1. package/README.md +126 -11
  2. package/dist/ai/gateway.d.ts +54 -16
  3. package/dist/ai/gateway.js +37 -12
  4. package/dist/aws/cloudfront.d.ts +23 -5
  5. package/dist/aws/cloudfront.js +45 -6
  6. package/dist/aws/secrets-manager.d.ts +38 -4
  7. package/dist/aws/secrets-manager.js +48 -3
  8. package/dist/cache/kv-cache.d.ts +173 -10
  9. package/dist/cache/kv-cache.js +139 -7
  10. package/dist/db/connection.d.ts +56 -14
  11. package/dist/db/connection.js +39 -13
  12. package/dist/db/database.d.ts +159 -23
  13. package/dist/db/database.js +49 -5
  14. package/dist/db/index.d.ts +11 -0
  15. package/dist/db/index.js +11 -2
  16. package/dist/db/jst.d.ts +89 -6
  17. package/dist/db/jst.js +89 -23
  18. package/dist/db/orm-config.d.ts +61 -19
  19. package/dist/db/orm-config.js +43 -14
  20. package/dist/db/retry.d.ts +25 -3
  21. package/dist/db/retry.js +25 -3
  22. package/dist/db/write-result.d.ts +27 -4
  23. package/dist/db/write-result.js +22 -1
  24. package/dist/firebase/firebase-verifier.d.ts +53 -4
  25. package/dist/firebase/identity-toolkit.d.ts +54 -5
  26. package/dist/firebase/identity-toolkit.js +51 -0
  27. package/dist/firebase/jose-firebase-verifier.d.ts +79 -7
  28. package/dist/firebase/jose-firebase-verifier.js +68 -7
  29. package/dist/firebase/remote-verifier.d.ts +42 -4
  30. package/dist/firebase/remote-verifier.js +58 -9
  31. package/dist/http/app-env.d.ts +41 -8
  32. package/dist/http/app-env.js +38 -8
  33. package/dist/http/app-info.d.ts +25 -3
  34. package/dist/http/app-info.js +16 -2
  35. package/dist/http/http-status.d.ts +12 -3
  36. package/dist/http/http-status.js +12 -3
  37. package/dist/http/nest-error.d.ts +90 -29
  38. package/dist/http/nest-error.js +59 -18
  39. package/dist/http/user-protocol.d.ts +23 -3
  40. package/dist/http/user-protocol.js +14 -2
  41. package/dist/index.d.ts +15 -0
  42. package/dist/index.js +14 -3
  43. package/dist/middleware/auth.d.ts +74 -13
  44. package/dist/middleware/auth.js +30 -6
  45. package/dist/middleware/finalize-response.d.ts +30 -0
  46. package/dist/middleware/finalize-response.js +41 -12
  47. package/dist/middleware/validation.d.ts +83 -9
  48. package/dist/middleware/validation.js +52 -9
  49. package/dist/middleware/zod-coerce.d.ts +56 -2
  50. package/dist/middleware/zod-coerce.js +68 -9
  51. package/dist/queue/consumer.d.ts +112 -0
  52. package/dist/queue/consumer.js +80 -0
  53. package/dist/queue/send.d.ts +90 -0
  54. package/dist/queue/send.js +85 -0
  55. package/dist/stripe/client.d.ts +46 -9
  56. package/dist/stripe/client.js +41 -3
  57. package/dist/testing/auth.d.ts +58 -10
  58. package/dist/testing/auth.js +58 -10
  59. package/dist/testing/configurable-fake.d.ts +20 -9
  60. package/dist/testing/configurable-fake.js +23 -11
  61. package/dist/testing/db.d.ts +81 -12
  62. package/dist/testing/db.js +23 -1
  63. package/dist/testing/fakes.d.ts +77 -9
  64. package/dist/testing/fakes.js +69 -7
  65. package/dist/testing/index.d.ts +7 -0
  66. package/dist/testing/index.js +10 -5
  67. package/dist/testing/stripe-fixtures.d.ts +93 -3
  68. package/dist/testing/stripe-fixtures.js +93 -3
  69. package/package.json +3 -2
  70. package/scripts/check-subrequest-fanout.mjs +86 -0
  71. package/src/ai/gateway.ts +66 -27
  72. package/src/aws/cloudfront.ts +46 -6
  73. package/src/aws/secrets-manager.ts +56 -7
  74. package/src/cache/kv-cache.ts +194 -12
  75. package/src/db/connection.ts +56 -14
  76. package/src/db/database.ts +160 -24
  77. package/src/db/index.ts +11 -2
  78. package/src/db/jst.ts +89 -23
  79. package/src/db/orm-config.ts +61 -19
  80. package/src/db/retry.ts +25 -3
  81. package/src/db/write-result.ts +27 -4
  82. package/src/firebase/firebase-verifier.ts +53 -4
  83. package/src/firebase/identity-toolkit.ts +57 -5
  84. package/src/firebase/jose-firebase-verifier.ts +79 -9
  85. package/src/firebase/remote-verifier.ts +58 -9
  86. package/src/http/app-env.ts +41 -8
  87. package/src/http/app-info.ts +25 -3
  88. package/src/http/http-status.ts +12 -3
  89. package/src/http/nest-error.ts +106 -37
  90. package/src/http/user-protocol.ts +23 -3
  91. package/src/index.ts +17 -3
  92. package/src/middleware/auth.ts +77 -15
  93. package/src/middleware/finalize-response.ts +41 -12
  94. package/src/middleware/validation.ts +89 -15
  95. package/src/middleware/zod-coerce.ts +68 -9
  96. package/src/queue/consumer.ts +146 -0
  97. package/src/queue/send.ts +129 -0
  98. package/src/stripe/client.ts +46 -9
  99. package/src/testing/auth.ts +58 -10
  100. package/src/testing/configurable-fake.ts +23 -11
  101. package/src/testing/db.ts +82 -13
  102. package/src/testing/fakes.ts +77 -9
  103. package/src/testing/index.ts +10 -5
  104. package/src/testing/stripe-fixtures.ts +93 -3
@@ -1,60 +1,196 @@
1
1
  import type { Connection, Pool } from 'mysql2/promise';
2
2
  import type { HyperdriveLike } from './connection.js';
3
3
  /**
4
- * フリート共通のデータ層(NestJS/TypeORM master/slave + retryWhenDeadlock 置換)。
5
- * - reads → replica。透明性のため生 SQL を維持(旧 helper.slave().query 相当)。
6
- * - writes → primary。型安全のため Drizzle 経由。ただし `write(fn)`/`transaction(fn)` 経由のみで、
7
- * 生 builder は公開しない。builder はここで await される(Drizzle builder は lazy thenable のため
8
- * `return builder` が黙って no-op になるフットガンを排除)。両者とも ER_LOCK_DEADLOCK を retry。
4
+ * Dual-connection data layer that separates reads from writes.
9
5
  *
10
- * 重要: kit は `drizzle-orm` の **型同一性に依存しない**。各 repo が自分の drizzle-orm で作った orm を
11
- * 渡す(`Database` orm `TDrizzle` にジェネリック)。これにより kit repo で drizzle-orm の
12
- * コピーが分かれても(symlink 構成)`MySqlTable`/`SQL` のブランド衝突が起きない。
6
+ * @remarks
7
+ * The two sides of the database are deliberately handled differently:
8
+ *
9
+ * - Reads go to the **replica** as raw SQL (`QueryRunner.query`) for transparency, returning plain
10
+ * rows.
11
+ * - Writes and transactions go to the **primary** through the Drizzle ORM for type safety, but only
12
+ * via `write(fn)` / `transaction(fn)` — the raw query builder is never exposed. The builder is
13
+ * awaited inside those methods, which removes a foot-gun: a Drizzle builder is a lazy thenable, so
14
+ * a bare `return builder` would silently become a no-op.
15
+ *
16
+ * Both sides retry on `ER_LOCK_DEADLOCK`.
17
+ *
18
+ * The kit deliberately avoids depending on the type identity of `drizzle-orm`: the consumer creates
19
+ * the ORM instance with its own copy of `drizzle-orm` and passes it in, and {@link Database} is
20
+ * generic over that ORM type (`TDrizzle`). This keeps the ORM's `MySqlTable`/`SQL` brands from
21
+ * clashing even when the kit and the consumer resolve separate copies of `drizzle-orm`.
22
+ */
23
+ /**
24
+ * Minimal connection interface used for reads.
25
+ *
26
+ * @remarks
27
+ * A mysql2 `Connection` or `Pool` satisfies this structurally.
13
28
  */
14
- /** reads 用の最小接続インターフェース(mysql2 Connection / Pool が構造的に満たす)。 */
15
29
  export interface QueryRunner {
30
+ /**
31
+ * Run a parameterized SQL query.
32
+ *
33
+ * @param sql - the SQL text, with `?` placeholders for `params`.
34
+ * @param params - optional positional parameters.
35
+ * @returns the driver's raw result (typically `[rows, fields]`).
36
+ */
16
37
  query(sql: string, params?: unknown[]): Promise<unknown>;
17
38
  }
18
- /** drizzle インスタンスの `.transaction(cb)` が受け取る tx ハンドルの型を取り出す。 */
39
+ /**
40
+ * Extract the transaction-handle type that a Drizzle instance passes to its `.transaction(cb)`
41
+ * callback.
42
+ *
43
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
44
+ */
19
45
  export type TxOf<TDrizzle> = TDrizzle extends {
20
46
  transaction(cb: (tx: infer Tx) => Promise<unknown>): Promise<unknown>;
21
47
  } ? Tx : unknown;
48
+ /**
49
+ * The read/write surface of the data layer.
50
+ *
51
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type used for writes and transactions.
52
+ * @typeParam TTx - the transaction-handle type, inferred from `TDrizzle` by default.
53
+ */
22
54
  export interface Database<TDrizzle, TTx = TxOf<TDrizzle>> {
55
+ /**
56
+ * Run a raw SQL read against the replica, with deadlock retry.
57
+ *
58
+ * @typeParam T - the row shape.
59
+ * @param sql - the SQL text, with `?` placeholders for `params`.
60
+ * @param params - optional positional parameters.
61
+ * @returns the rows returned by the query.
62
+ */
23
63
  read<T>(sql: string, params?: unknown[]): Promise<T[]>;
24
- /** 単一 INSERT/UPDATE/DELETE。primary で await + deadlock retry。 */
64
+ /**
65
+ * Run a single INSERT/UPDATE/DELETE against the primary, awaited with deadlock retry.
66
+ *
67
+ * @typeParam T - the value resolved by `fn`.
68
+ * @param fn - callback that receives the Drizzle ORM and returns the awaited write.
69
+ * @returns the value resolved by `fn`.
70
+ */
25
71
  write<T>(fn: (dz: TDrizzle) => Promise<T>): Promise<T>;
26
- /** 複数 write を 1 トランザクションで。deadlock 時は全体を retry。 */
72
+ /**
73
+ * Run multiple writes inside a single transaction; the whole transaction is retried on deadlock.
74
+ *
75
+ * @typeParam T - the value resolved by `fn`.
76
+ * @param fn - callback that receives the transaction handle and returns the awaited work.
77
+ * @returns the value resolved by `fn`.
78
+ */
27
79
  transaction<T>(fn: (tx: TTx) => Promise<T>): Promise<T>;
28
80
  }
29
- /** dispose() を持つ Database(接続をモジュール内で開く版=Hyperdrive / Pool 背面)。 */
81
+ /**
82
+ * A {@link Database} that owns its connections and must be disposed.
83
+ *
84
+ * @remarks
85
+ * Used by the variants that open connections internally (Hyperdrive- or Pool-backed).
86
+ *
87
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
88
+ * @typeParam TTx - the transaction-handle type, inferred from `TDrizzle` by default.
89
+ */
30
90
  export interface DisposableDatabase<TDrizzle, TTx = TxOf<TDrizzle>> extends Database<TDrizzle, TTx> {
91
+ /**
92
+ * Close the connections opened by this database.
93
+ *
94
+ * @returns a promise that settles once both connections are closed.
95
+ */
31
96
  dispose(): Promise<void>;
32
97
  }
98
+ /**
99
+ * Options for {@link createMysqlDatabase}.
100
+ *
101
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
102
+ */
33
103
  export interface CreateMysqlDatabaseOptions<TDrizzle> {
34
- /** 消費側が自分の drizzle-orm で `drizzle(primary, { schema, ... })` を作って渡す(writes 用)。 */
104
+ /**
105
+ * The Drizzle ORM used for writes, created by the consumer with its own `drizzle-orm`
106
+ * (e.g. `drizzle(primary, { schema, ... })`).
107
+ */
35
108
  orm: TDrizzle;
36
- /** reads(生 SQL)用の接続。 */
109
+ /** The connection used for reads (raw SQL). */
37
110
  replica: QueryRunner;
38
111
  }
39
112
  /**
40
- * 接続済みの orm/replica を受け取り Database を組み立てる(receptray/tipsys MysqlDatabase 相当)。
41
- * 接続・orm の生成と接続の破棄は呼び出し側(worker entry)が担う。
113
+ * Assemble a {@link Database} from an already-connected ORM and replica.
114
+ *
115
+ * @remarks
116
+ * The caller (typically the worker entry point) owns creating the connections and the ORM, and is
117
+ * responsible for closing the connections; this variant does not manage their lifecycle.
118
+ *
119
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
120
+ * @param options - the write ORM and the read connection.
121
+ * @returns a {@link Database} backed by the supplied ORM and replica.
122
+ * @example
123
+ * ```ts
124
+ * const db = createMysqlDatabase({
125
+ * orm: drizzle(primary, { schema, ...DRIZZLE_ORM_OPTIONS }),
126
+ * replica,
127
+ * });
128
+ * const rows = await db.read<User>('SELECT * FROM users WHERE id = ?', [id]);
129
+ * ```
42
130
  */
43
131
  export declare function createMysqlDatabase<TDrizzle>(options: CreateMysqlDatabaseOptions<TDrizzle>): Database<TDrizzle>;
132
+ /**
133
+ * Options for {@link createHyperdriveDatabase}.
134
+ *
135
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
136
+ */
44
137
  export interface CreateHyperdriveDatabaseOptions<TDrizzle> {
138
+ /** The Hyperdrive binding for the primary (write) connection. */
45
139
  primaryHyperdrive: HyperdriveLike;
140
+ /** The Hyperdrive binding for the replica (read) connection. */
46
141
  replicaHyperdrive: HyperdriveLike;
47
- /** 消費側の drizzle-orm で primary 接続から orm を作る factory(writes 用)。 */
142
+ /**
143
+ * Factory that builds the write ORM from the primary connection, using the consumer's
144
+ * `drizzle-orm`.
145
+ */
48
146
  createOrm: (primary: Connection) => TDrizzle;
49
- /** createConnection に渡す追加オプション(timezone など)。disableEval:true は既定で付与。 */
147
+ /**
148
+ * Extra options forwarded to mysql2 `createConnection`, merged on top of the defaults applied by
149
+ * {@link hyperdriveConnectionOptions} (`disableEval: true`, `decimalNumbers: true`, and
150
+ * `timezone: '+09:00'`). Pass a field here to override any of those defaults.
151
+ */
50
152
  connectionOptions?: Record<string, unknown>;
51
153
  }
52
154
  /**
53
- * Hyperdrive バインディングから接続を遅延生成する Database(foodlabel MysqlDatabase 相当)。
54
- * リクエスト毎に new し、レスポンス後 `dispose()` で接続を閉じる。read/write/transaction の面は同一。
155
+ * Create a {@link DisposableDatabase} that lazily opens its connections from Hyperdrive bindings.
156
+ *
157
+ * @remarks
158
+ * Construct one per request and call `dispose()` after the response to close the connections.
159
+ * Connections and the ORM are created on first use and reused for the lifetime of the instance; the
160
+ * read/write/transaction surface is identical to {@link createMysqlDatabase}.
161
+ *
162
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
163
+ * @param options - the primary/replica Hyperdrive bindings, the ORM factory, and connection options.
164
+ * @returns a {@link DisposableDatabase} that must be disposed when done.
165
+ * @example
166
+ * ```ts
167
+ * const db = createHyperdriveDatabase({
168
+ * primaryHyperdrive: env.PRIMARY,
169
+ * replicaHyperdrive: env.REPLICA,
170
+ * createOrm: (primary) => drizzle(primary, { schema, ...DRIZZLE_ORM_OPTIONS }),
171
+ * });
172
+ * try {
173
+ * await db.write((dz) => dz.insert(users).values(user));
174
+ * } finally {
175
+ * await db.dispose();
176
+ * }
177
+ * ```
55
178
  */
56
179
  export declare function createHyperdriveDatabase<TDrizzle>(options: CreateHyperdriveDatabaseOptions<TDrizzle>): DisposableDatabase<TDrizzle>;
57
- /** orm と replica 接続から Database を組み立てる内部ヘルパ。 */
180
+ /**
181
+ * Internal helper that assembles a {@link Database} from an ORM and a replica connection.
182
+ *
183
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
184
+ * @param orm - the Drizzle ORM used for writes and transactions.
185
+ * @param replica - the connection used for reads.
186
+ * @returns a {@link Database} wiring reads to `replica` and writes to `orm`, both with deadlock retry.
187
+ * @internal
188
+ */
58
189
  export declare function databaseFrom<TDrizzle>(orm: TDrizzle, replica: QueryRunner): Database<TDrizzle>;
59
- /** Pool/Connection は mysql2 の型。kit の QueryRunner には構造的に代入可能。 */
190
+ /**
191
+ * Re-export of the mysql2 `Connection` and `Pool` types.
192
+ *
193
+ * @remarks
194
+ * Both are structurally assignable to the kit's {@link QueryRunner}.
195
+ */
60
196
  export type { Connection, Pool };
@@ -2,15 +2,51 @@ import { createConnection } from 'mysql2/promise';
2
2
  import { hyperdriveConnectionOptions } from './connection.js';
3
3
  import { retryWhenDeadlock } from './retry.js';
4
4
  /**
5
- * 接続済みの orm/replica を受け取り Database を組み立てる(receptray/tipsys MysqlDatabase 相当)。
6
- * 接続・orm の生成と接続の破棄は呼び出し側(worker entry)が担う。
5
+ * Assemble a {@link Database} from an already-connected ORM and replica.
6
+ *
7
+ * @remarks
8
+ * The caller (typically the worker entry point) owns creating the connections and the ORM, and is
9
+ * responsible for closing the connections; this variant does not manage their lifecycle.
10
+ *
11
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
12
+ * @param options - the write ORM and the read connection.
13
+ * @returns a {@link Database} backed by the supplied ORM and replica.
14
+ * @example
15
+ * ```ts
16
+ * const db = createMysqlDatabase({
17
+ * orm: drizzle(primary, { schema, ...DRIZZLE_ORM_OPTIONS }),
18
+ * replica,
19
+ * });
20
+ * const rows = await db.read<User>('SELECT * FROM users WHERE id = ?', [id]);
21
+ * ```
7
22
  */
8
23
  export function createMysqlDatabase(options) {
9
24
  return databaseFrom(options.orm, options.replica);
10
25
  }
11
26
  /**
12
- * Hyperdrive バインディングから接続を遅延生成する Database(foodlabel MysqlDatabase 相当)。
13
- * リクエスト毎に new し、レスポンス後 `dispose()` で接続を閉じる。read/write/transaction の面は同一。
27
+ * Create a {@link DisposableDatabase} that lazily opens its connections from Hyperdrive bindings.
28
+ *
29
+ * @remarks
30
+ * Construct one per request and call `dispose()` after the response to close the connections.
31
+ * Connections and the ORM are created on first use and reused for the lifetime of the instance; the
32
+ * read/write/transaction surface is identical to {@link createMysqlDatabase}.
33
+ *
34
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
35
+ * @param options - the primary/replica Hyperdrive bindings, the ORM factory, and connection options.
36
+ * @returns a {@link DisposableDatabase} that must be disposed when done.
37
+ * @example
38
+ * ```ts
39
+ * const db = createHyperdriveDatabase({
40
+ * primaryHyperdrive: env.PRIMARY,
41
+ * replicaHyperdrive: env.REPLICA,
42
+ * createOrm: (primary) => drizzle(primary, { schema, ...DRIZZLE_ORM_OPTIONS }),
43
+ * });
44
+ * try {
45
+ * await db.write((dz) => dz.insert(users).values(user));
46
+ * } finally {
47
+ * await db.dispose();
48
+ * }
49
+ * ```
14
50
  */
15
51
  export function createHyperdriveDatabase(options) {
16
52
  const { primaryHyperdrive, replicaHyperdrive, createOrm, connectionOptions } = options;
@@ -40,7 +76,15 @@ export function createHyperdriveDatabase(options) {
40
76
  },
41
77
  };
42
78
  }
43
- /** orm と replica 接続から Database を組み立てる内部ヘルパ。 */
79
+ /**
80
+ * Internal helper that assembles a {@link Database} from an ORM and a replica connection.
81
+ *
82
+ * @typeParam TDrizzle - the consumer's Drizzle ORM type.
83
+ * @param orm - the Drizzle ORM used for writes and transactions.
84
+ * @param replica - the connection used for reads.
85
+ * @returns a {@link Database} wiring reads to `replica` and writes to `orm`, both with deadlock retry.
86
+ * @internal
87
+ */
44
88
  export function databaseFrom(orm, replica) {
45
89
  const drizzleLike = orm;
46
90
  return {
@@ -1,3 +1,14 @@
1
+ /**
2
+ * Data-layer helpers that depend on `mysql2` (exposed under the `/db` subpath because the package
3
+ * root is reserved for web-standard-only code).
4
+ *
5
+ * @remarks
6
+ * This module never depends on the type identity of `drizzle-orm`: the ORM instance is always
7
+ * supplied by the consumer. That keeps the kit safe to use even when the kit and the consuming app
8
+ * resolve separate copies of `drizzle-orm`.
9
+ *
10
+ * @packageDocumentation
11
+ */
1
12
  export { retryWhenDeadlock } from './retry.js';
2
13
  export { createMysqlDatabase, createHyperdriveDatabase, databaseFrom } from './database.js';
3
14
  export type { Database, DisposableDatabase, QueryRunner, TxOf, CreateMysqlDatabaseOptions, CreateHyperdriveDatabaseOptions, Connection, Pool, } from './database.js';
package/dist/db/index.js CHANGED
@@ -1,5 +1,14 @@
1
- // @rdlabo/workers-hono-kit/db — mysql2 依存のデータ層ヘルパ(ルート `.` は web 標準のみのため別サブパス)。
2
- // drizzle-orm の型同一性には依存しない(orm は消費側が渡す)。
1
+ /**
2
+ * Data-layer helpers that depend on `mysql2` (exposed under the `/db` subpath because the package
3
+ * root is reserved for web-standard-only code).
4
+ *
5
+ * @remarks
6
+ * This module never depends on the type identity of `drizzle-orm`: the ORM instance is always
7
+ * supplied by the consumer. That keeps the kit safe to use even when the kit and the consuming app
8
+ * resolve separate copies of `drizzle-orm`.
9
+ *
10
+ * @packageDocumentation
11
+ */
3
12
  export { retryWhenDeadlock } from './retry.js';
4
13
  export { createMysqlDatabase, createHyperdriveDatabase, databaseFrom } from './database.js';
5
14
  export { insertIdOf, affectedRowsOf, insertedIdsOf } from './write-result.js';
package/dist/db/jst.d.ts CHANGED
@@ -1,18 +1,101 @@
1
1
  /**
2
- * クライアント送出の日付(ISO 8601 `...Z` / `YYYY-MM-DD` / 空文字)を MySQL DATE 用の
3
- * `YYYY-MM-DD`(JST)へ正規化。nullish/空/解釈不能は null。MySQL DATE は ISO を弾く
4
- * (ER_TRUNCATED_WRONG_VALUE)ため driver では代替できず、列の toDriver に必要。
2
+ * Shared building blocks for normalizing JST (Asia/Tokyo) date/time values.
3
+ *
4
+ * @remarks
5
+ * JST normalization is applied at the column boundary as a write-time side effect, and neither
6
+ * values nor types from `drizzle-orm` are imported here on purpose. Exporting a fully-built
7
+ * `customType` column from the kit would cause type collisions when the kit and the consumer
8
+ * resolve separate copies of `drizzle-orm` (the private `SQL` brand stops being nominally
9
+ * compatible). Instead the kit ships only the params and helpers, and the consumer builds the
10
+ * column with its own `customType`:
11
+ *
12
+ * ```ts
13
+ * import { customType } from 'drizzle-orm/mysql-core';
14
+ * import { jstTimestampParams, jstDateParams } from '@rdlabo/workers-hono-kit/db';
15
+ *
16
+ * export const jstTimestamp = (name: string, opts?: { fsp?: number }) =>
17
+ * customType<{ data: string | Date; driverData: string | Date }>(jstTimestampParams(opts?.fsp))(name);
18
+ * export const jstDate = (name: string) =>
19
+ * customType<{ data: string | null; driverData: string | null }>(jstDateParams())(name);
20
+ * ```
21
+ *
22
+ * `timestamp`/`datetime` columns omit `toDriver` and pass `Date` values straight through, so the
23
+ * connection's `timezone: '+09:00'` default makes mysql2 format them as JST; pre-formatted strings
24
+ * also pass through. Drizzle's native `mode: 'date'` is avoided because it stringifies `Date` to
25
+ * UTC before the timezone layer, shifting values by -9h. `date` columns keep `toJstDate` because
26
+ * MySQL `DATE` rejects ISO/empty strings and a JST day-boundary normalization is required.
27
+ */
28
+ /**
29
+ * Normalize a client-supplied date to the `YYYY-MM-DD` (JST) form accepted by a MySQL `DATE` column.
30
+ *
31
+ * Accepts ISO 8601 (`...Z`), `YYYY-MM-DD`, or an empty string. Nullish, empty, or unparseable input
32
+ * resolves to `null`.
33
+ *
34
+ * @remarks
35
+ * MySQL `DATE` rejects ISO strings with `ER_TRUNCATED_WRONG_VALUE`, so this cannot be handled by the
36
+ * driver alone; it is needed as the `toDriver` transform for a `date` column.
37
+ *
38
+ * @param value - the raw date string from the client (ISO 8601, `YYYY-MM-DD`, or empty), or nullish.
39
+ * @returns the JST calendar date as `YYYY-MM-DD`, or `null` when the input is empty or unparseable.
5
40
  */
6
41
  export declare function toJstDate(value: string | null | undefined): string | null;
7
- /** `customType` に渡す params: `timestamp(fsp)` 列(created_at 群)。Date 素通し(pass-through)。 */
42
+ /**
43
+ * Build the params for a `customType` backing a MySQL `timestamp` column with `Date` pass-through.
44
+ *
45
+ * The column omits `toDriver`, so `Date` values flow straight to mysql2 and are formatted as JST by
46
+ * the connection's `timezone: '+09:00'` default.
47
+ *
48
+ * @param fsp - optional fractional-seconds precision; when provided, emits `timestamp(fsp)`.
49
+ * @returns the `customType` params object exposing the column's `dataType`.
50
+ * @example
51
+ * ```ts
52
+ * import { customType } from 'drizzle-orm/mysql-core';
53
+ * import { jstTimestampParams } from '@rdlabo/workers-hono-kit/db';
54
+ *
55
+ * const jstTimestamp = (name: string) =>
56
+ * customType<{ data: string | Date; driverData: string | Date }>(jstTimestampParams())(name);
57
+ * ```
58
+ */
8
59
  export declare const jstTimestampParams: (fsp?: number) => {
9
60
  dataType: () => string;
10
61
  };
11
- /** `customType` に渡す params: `datetime` 列(payment.limit_at 等)。Date 素通し(pass-through)。 */
62
+ /**
63
+ * Build the params for a `customType` backing a MySQL `datetime` column with `Date` pass-through.
64
+ *
65
+ * Behaves like {@link jstTimestampParams} but emits a `datetime` data type; `Date` values pass
66
+ * through and are formatted as JST by the connection's `timezone: '+09:00'` default.
67
+ *
68
+ * @param fsp - optional fractional-seconds precision; when provided, emits `datetime(fsp)`.
69
+ * @returns the `customType` params object exposing the column's `dataType`.
70
+ * @example
71
+ * ```ts
72
+ * import { customType } from 'drizzle-orm/mysql-core';
73
+ * import { jstDatetimeParams } from '@rdlabo/workers-hono-kit/db';
74
+ *
75
+ * const jstDatetime = (name: string) =>
76
+ * customType<{ data: string | Date; driverData: string | Date }>(jstDatetimeParams())(name);
77
+ * ```
78
+ */
12
79
  export declare const jstDatetimeParams: (fsp?: number) => {
13
80
  dataType: () => string;
14
81
  };
15
- /** `customType` に渡す params: `date` 列(expiry_date 等)。toJstDate で文字列を正規化。 */
82
+ /**
83
+ * Build the params for a `customType` backing a MySQL `date` column with JST normalization.
84
+ *
85
+ * Unlike the timestamp/datetime params, this defines a `toDriver` transform that runs
86
+ * {@link toJstDate} so client-supplied ISO/empty strings are normalized to a JST `YYYY-MM-DD` value
87
+ * the column accepts.
88
+ *
89
+ * @returns the `customType` params object exposing the column's `dataType` and `toDriver`.
90
+ * @example
91
+ * ```ts
92
+ * import { customType } from 'drizzle-orm/mysql-core';
93
+ * import { jstDateParams } from '@rdlabo/workers-hono-kit/db';
94
+ *
95
+ * const jstDate = (name: string) =>
96
+ * customType<{ data: string | null; driverData: string | null }>(jstDateParams())(name);
97
+ * ```
98
+ */
16
99
  export declare const jstDateParams: () => {
17
100
  dataType: () => string;
18
101
  toDriver: (value: string | null) => string | null;
package/dist/db/jst.js CHANGED
@@ -1,25 +1,43 @@
1
- // JST 日時の整形を「DB 書き込みの副作用」として列の境界に寄せるための共有部品。
2
- // drizzle-orm の値・型は import しない(kit の脱・型同一性方針)。kit で完成した customType 列を
3
- // export すると、消費側と drizzle-orm のコピーが分かれた場合に `.default(sql\`…\`)` 等で `SQL` の
4
- // private プロパティ(shouldInlineParams)が nominal 不一致になり型衝突する(実測で確認)。そのため
5
- // 列生成は消費側の `customType` に委ね、kit params とヘルパだけ供給する:
6
- //
7
- // import { customType } from 'drizzle-orm/mysql-core';
8
- // import { jstTimestampParams, jstDateParams } from '@rdlabo/workers-hono-kit/db';
9
- // export const jstTimestamp = (name: string, opts?: { fsp?: number }) =>
10
- // customType<{ data: string | Date; driverData: string | Date }>(jstTimestampParams(opts?.fsp))(name);
11
- // export const jstDate = (name: string) =>
12
- // customType<{ data: string | null; driverData: string | null }>(jstDateParams())(name);
13
- //
14
- // timestamp/datetime toDriver を置かず Date を素通し 接続の `timezone:'+09:00'`(hyperdrive
15
- // 既定)で mysql2 が JST 整形、整形済み文字列も素通し。Drizzle ネイティブ `mode:'date'` は Date を
16
- // tz 層より前に UTC 文字列化して −9h で壊れるため使わない(customType pass-through が唯一クリーン)。
17
- // date 列はクライアントの ISO/空文字を MySQL DATE が弾く+JST 日跨ぎ正規化が要るので toJstDate を残す。
1
+ /**
2
+ * Shared building blocks for normalizing JST (Asia/Tokyo) date/time values.
3
+ *
4
+ * @remarks
5
+ * JST normalization is applied at the column boundary as a write-time side effect, and neither
6
+ * values nor types from `drizzle-orm` are imported here on purpose. Exporting a fully-built
7
+ * `customType` column from the kit would cause type collisions when the kit and the consumer
8
+ * resolve separate copies of `drizzle-orm` (the private `SQL` brand stops being nominally
9
+ * compatible). Instead the kit ships only the params and helpers, and the consumer builds the
10
+ * column with its own `customType`:
11
+ *
12
+ * ```ts
13
+ * import { customType } from 'drizzle-orm/mysql-core';
14
+ * import { jstTimestampParams, jstDateParams } from '@rdlabo/workers-hono-kit/db';
15
+ *
16
+ * export const jstTimestamp = (name: string, opts?: { fsp?: number }) =>
17
+ * customType<{ data: string | Date; driverData: string | Date }>(jstTimestampParams(opts?.fsp))(name);
18
+ * export const jstDate = (name: string) =>
19
+ * customType<{ data: string | null; driverData: string | null }>(jstDateParams())(name);
20
+ * ```
21
+ *
22
+ * `timestamp`/`datetime` columns omit `toDriver` and pass `Date` values straight through, so the
23
+ * connection's `timezone: '+09:00'` default makes mysql2 format them as JST; pre-formatted strings
24
+ * also pass through. Drizzle's native `mode: 'date'` is avoided because it stringifies `Date` to
25
+ * UTC before the timezone layer, shifting values by -9h. `date` columns keep `toJstDate` because
26
+ * MySQL `DATE` rejects ISO/empty strings and a JST day-boundary normalization is required.
27
+ */
18
28
  const JST_OFFSET_MS = 9 * 60 * 60 * 1000;
19
29
  /**
20
- * クライアント送出の日付(ISO 8601 `...Z` / `YYYY-MM-DD` / 空文字)を MySQL DATE 用の
21
- * `YYYY-MM-DD`(JST)へ正規化。nullish/空/解釈不能は null。MySQL DATE は ISO を弾く
22
- * (ER_TRUNCATED_WRONG_VALUE)ため driver では代替できず、列の toDriver に必要。
30
+ * Normalize a client-supplied date to the `YYYY-MM-DD` (JST) form accepted by a MySQL `DATE` column.
31
+ *
32
+ * Accepts ISO 8601 (`...Z`), `YYYY-MM-DD`, or an empty string. Nullish, empty, or unparseable input
33
+ * resolves to `null`.
34
+ *
35
+ * @remarks
36
+ * MySQL `DATE` rejects ISO strings with `ER_TRUNCATED_WRONG_VALUE`, so this cannot be handled by the
37
+ * driver alone; it is needed as the `toDriver` transform for a `date` column.
38
+ *
39
+ * @param value - the raw date string from the client (ISO 8601, `YYYY-MM-DD`, or empty), or nullish.
40
+ * @returns the JST calendar date as `YYYY-MM-DD`, or `null` when the input is empty or unparseable.
23
41
  */
24
42
  export function toJstDate(value) {
25
43
  if (!value) {
@@ -33,15 +51,63 @@ export function toJstDate(value) {
33
51
  const p = (n) => String(n).padStart(2, '0');
34
52
  return `${jst.getUTCFullYear()}-${p(jst.getUTCMonth() + 1)}-${p(jst.getUTCDate())}`;
35
53
  }
36
- /** `customType` に渡す params: `timestamp(fsp)` 列(created_at 群)。Date 素通し(pass-through)。 */
54
+ /**
55
+ * Build the params for a `customType` backing a MySQL `timestamp` column with `Date` pass-through.
56
+ *
57
+ * The column omits `toDriver`, so `Date` values flow straight to mysql2 and are formatted as JST by
58
+ * the connection's `timezone: '+09:00'` default.
59
+ *
60
+ * @param fsp - optional fractional-seconds precision; when provided, emits `timestamp(fsp)`.
61
+ * @returns the `customType` params object exposing the column's `dataType`.
62
+ * @example
63
+ * ```ts
64
+ * import { customType } from 'drizzle-orm/mysql-core';
65
+ * import { jstTimestampParams } from '@rdlabo/workers-hono-kit/db';
66
+ *
67
+ * const jstTimestamp = (name: string) =>
68
+ * customType<{ data: string | Date; driverData: string | Date }>(jstTimestampParams())(name);
69
+ * ```
70
+ */
37
71
  export const jstTimestampParams = (fsp) => ({
38
72
  dataType: () => (fsp != null ? `timestamp(${fsp})` : 'timestamp'),
39
73
  });
40
- /** `customType` に渡す params: `datetime` 列(payment.limit_at 等)。Date 素通し(pass-through)。 */
74
+ /**
75
+ * Build the params for a `customType` backing a MySQL `datetime` column with `Date` pass-through.
76
+ *
77
+ * Behaves like {@link jstTimestampParams} but emits a `datetime` data type; `Date` values pass
78
+ * through and are formatted as JST by the connection's `timezone: '+09:00'` default.
79
+ *
80
+ * @param fsp - optional fractional-seconds precision; when provided, emits `datetime(fsp)`.
81
+ * @returns the `customType` params object exposing the column's `dataType`.
82
+ * @example
83
+ * ```ts
84
+ * import { customType } from 'drizzle-orm/mysql-core';
85
+ * import { jstDatetimeParams } from '@rdlabo/workers-hono-kit/db';
86
+ *
87
+ * const jstDatetime = (name: string) =>
88
+ * customType<{ data: string | Date; driverData: string | Date }>(jstDatetimeParams())(name);
89
+ * ```
90
+ */
41
91
  export const jstDatetimeParams = (fsp) => ({
42
92
  dataType: () => (fsp != null ? `datetime(${fsp})` : 'datetime'),
43
93
  });
44
- /** `customType` に渡す params: `date` 列(expiry_date 等)。toJstDate で文字列を正規化。 */
94
+ /**
95
+ * Build the params for a `customType` backing a MySQL `date` column with JST normalization.
96
+ *
97
+ * Unlike the timestamp/datetime params, this defines a `toDriver` transform that runs
98
+ * {@link toJstDate} so client-supplied ISO/empty strings are normalized to a JST `YYYY-MM-DD` value
99
+ * the column accepts.
100
+ *
101
+ * @returns the `customType` params object exposing the column's `dataType` and `toDriver`.
102
+ * @example
103
+ * ```ts
104
+ * import { customType } from 'drizzle-orm/mysql-core';
105
+ * import { jstDateParams } from '@rdlabo/workers-hono-kit/db';
106
+ *
107
+ * const jstDate = (name: string) =>
108
+ * customType<{ data: string | null; driverData: string | null }>(jstDateParams())(name);
109
+ * ```
110
+ */
45
111
  export const jstDateParams = () => ({
46
112
  dataType: () => 'date',
47
113
  toDriver: (value) => toJstDate(value),