@rdlabo/workers-hono-kit 0.3.5 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,12 +66,16 @@ npm install ai ai-gateway-provider # createAiGatewayProvider
66
66
  | `HttpStatus` | HTTP status enum identical to NestJS `@nestjs/common`. |
67
67
  | `createNestErrorHandler(options?)` / `NestErrorHandlerOptions` | `app.onError()` handler that maps a thrown `HTTPException` to the NestJS exception-filter body (`{ statusCode, message, error? }`; `401` omits `error`). Configurable field order, reason phrases, error predicate, and unhandled-error report hook. |
68
68
  | `nestNotFoundHandler(c)` | `app.notFound()` handler with the Express/Nest default `{ message: 'Cannot METHOD path', error, statusCode }` 404 body. |
69
+ | `normalizeTrailingSlash(request)` | Strip trailing slash(es) from the request URL before routing (Express/Nest parity). Does **not** 301-redirect — preserves POST/PUT/DELETE bodies. |
69
70
  | `NEST_REASON_PHRASES` | `{ 400, 401, 403, 404 }` → NestJS reason phrases. |
70
71
  | `createAuthMiddleware(options)` / `AuthMiddlewareOptions` | Factory for a Firebase-token auth middleware: reads the token header, verifies, resolves the DB user id, and stashes the result on the context. Omit `resolveUserId` for a token-only (login) guard. |
71
72
  | `ErrorReporter` / `ErrorReportContext` | Types for a `reportError`-style unhandled-error reporter (e.g. wired to Sentry), paired with `createNestErrorHandler`'s `onUnhandledError`. |
72
73
  | `createAiGatewayProvider(config)` / `AiGatewayConfig` / `AiGatewayProvider` | Route `@ai-sdk` models through the Cloudflare AI Gateway, via either a Workers `AI` binding or REST credentials (`accountId` / `gateway` / `token`). |
73
74
  | `KVCache` / `KVNamespace` / `KVCacheOptions` | Workers-KV cache-aside helper (key `appName+version+table_type_column`, sha256 for string ids, TTL clamped ≥60s). Set `appName` / `version` per application. |
74
75
  | `createStripeClient(secret, opts?)` / `verifyStripeWebhook(...)` / `CreateStripeClientOptions` | Workers-native Stripe client (fetch transport) + async webhook verification (SubtleCrypto). `apiVersion` optional (pin to a fixed Stripe API version). |
76
+ | `sendInChunks(queue, messages, chunkSize?)` / `QueueLike` / `QueueSendMessage` | Send queue messages in bounded chunks to stay under the Workers subrequest cap per invocation. |
77
+ | `processBatch(batch, handler, options?)` / `MessageBatchLike` / `QueueMessageLike` / `ProcessBatchOptions` / `ProcessBatchResult` | Process a queue batch with bounded concurrency (consumer-side counterpart to `sendInChunks`). |
78
+ | `ExecutionContextLike` | Minimal `waitUntil`-only Workers execution context shape (for `withMysqlConnections` in worker entry modules without importing `./db`). |
75
79
 
76
80
  ### Data layer — `@rdlabo/workers-hono-kit/db`
77
81
 
@@ -81,6 +85,7 @@ Requires the `drizzle-orm` and `mysql2` peers. Reads run against a replica via r
81
85
  | --- | --- |
82
86
  | `createHyperdriveDatabase(options)` | `DisposableDatabase` that lazily opens primary/replica connections from Hyperdrive bindings per request; `dispose()` closes them. |
83
87
  | `createMysqlDatabase(options)` | Assemble a `Database` from an already-connected Drizzle ORM + replica `QueryRunner`. |
88
+ | `databaseFrom(orm, replica)` | Build a `Database` from an existing Drizzle instance + replica handle. |
84
89
  | `Database` / `DisposableDatabase` / `QueryRunner` / `TxOf` | The `read` / `write` / `transaction` API and its supporting types. |
85
90
  | `hyperdriveConnectionOptions(hyperdrive, overrides?)` / `HyperdriveLike` / `ExecutionContextLike` | Build mysql2 `createConnection` options from a Hyperdrive binding (`disableEval`, `decimalNumbers`, `timezone '+09:00'` by default). |
86
91
  | `withMysqlConnections(...)` | Open primary/replica connections, run a function, close them in `finally` (via `ctx.waitUntil`). |
@@ -88,6 +93,8 @@ Requires the `drizzle-orm` and `mysql2` peers. Reads run against a replica via r
88
93
  | `insertIdOf` / `affectedRowsOf` / `insertedIdsOf` / `DzWriteResult` | Extract `insertId` / `affectedRows` (and derive contiguous bulk-insert ids) from a mysql2 write result. |
89
94
  | `toJstDate` / `jstTimestampParams` / `jstDatetimeParams` / `jstDateParams` | JST date/time normalization applied at the Drizzle `customType` column boundary. |
90
95
  | `DRIZZLE_ORM_OPTIONS` / `honoDrizzleConfig(options)` / `HonoDrizzleConfigOptions` | Shared Drizzle casing (`snake_case`) for both the runtime `drizzle()` call and `drizzle.config.ts`, keeping config ↔ runtime in sync. |
96
+ | `resolveDbSecret(options, secretId?)` / `ResolvedDbSecret` | Resolve RDS-managed or plain DB credentials from AWS Secrets Manager for CI migrate / local tooling. |
97
+ | `baselineMigrations(options)` / `readBaselineEntry(migrationsFolder)` / `BaselineMigrationsOptions` / `BaselineResult` / `BaselineEntry` | Brownfield first-deploy helper: mark an existing `0000_*` migration as applied without re-running DDL. |
91
98
 
92
99
  ### Testing — `@rdlabo/workers-hono-kit/testing`
93
100
 
@@ -1,4 +1,6 @@
1
1
  import type { Connection } from 'mysql2/promise';
2
+ import type { ExecutionContextLike } from '../http/execution-context.js';
3
+ export type { ExecutionContextLike } from '../http/execution-context.js';
2
4
  /**
3
5
  * Minimal structural shape of a Cloudflare Hyperdrive binding.
4
6
  *
@@ -40,16 +42,6 @@ export interface HyperdriveLike {
40
42
  * @returns a plain options object to pass to mysql2 `createConnection`.
41
43
  */
42
44
  export declare function hyperdriveConnectionOptions(hyperdrive: HyperdriveLike, extra?: Record<string, unknown>): Record<string, unknown>;
43
- /**
44
- * Minimal structural shape of a Workers `ExecutionContext`, limited to `waitUntil`.
45
- *
46
- * @remarks
47
- * Declared structurally to avoid a dependency on `@cloudflare/workers-types`.
48
- */
49
- export interface ExecutionContextLike {
50
- /** Extend the request's lifetime until `promise` settles (used to close connections after the response). */
51
- waitUntil(promise: Promise<unknown>): void;
52
- }
53
45
  /**
54
46
  * Open primary and replica connections, run `fn` with them, and close both afterwards.
55
47
  *
@@ -17,7 +17,7 @@ export type { DzWriteResult } from './write-result.js';
17
17
  export { hyperdriveConnectionOptions, withMysqlConnections } from './connection.js';
18
18
  export type { HyperdriveLike, ExecutionContextLike } from './connection.js';
19
19
  export { toJstDate, jstTimestampParams, jstDatetimeParams, jstDateParams } from './jst.js';
20
- export { DRIZZLE_ORM_OPTIONS, honoDrizzleConfig } from './orm-config.js';
21
- export type { HonoDrizzleConfigOptions } from './orm-config.js';
20
+ export { DRIZZLE_ORM_OPTIONS, honoDrizzleConfig, resolveDbSecret } from './orm-config.js';
21
+ export type { HonoDrizzleConfigOptions, ResolvedDbSecret } from './orm-config.js';
22
22
  export { baselineMigrations, readBaselineEntry } from './migrate.js';
23
23
  export type { BaselineMigrationsOptions, BaselineResult, BaselineEntry } from './migrate.js';
package/dist/db/index.js CHANGED
@@ -14,5 +14,5 @@ export { createMysqlDatabase, createHyperdriveDatabase, databaseFrom } from './d
14
14
  export { insertIdOf, affectedRowsOf, insertedIdsOf } from './write-result.js';
15
15
  export { hyperdriveConnectionOptions, withMysqlConnections } from './connection.js';
16
16
  export { toJstDate, jstTimestampParams, jstDatetimeParams, jstDateParams } from './jst.js';
17
- export { DRIZZLE_ORM_OPTIONS, honoDrizzleConfig } from './orm-config.js';
17
+ export { DRIZZLE_ORM_OPTIONS, honoDrizzleConfig, resolveDbSecret } from './orm-config.js';
18
18
  export { baselineMigrations, readBaselineEntry } from './migrate.js';
@@ -102,3 +102,22 @@ export declare function honoDrizzleConfig(options: HonoDrizzleConfigOptions): {
102
102
  out: string;
103
103
  casing: "snake_case";
104
104
  };
105
+ /** {@link resolveDbSecret} の戻り値(正規化済みの接続情報)。 */
106
+ export interface ResolvedDbSecret {
107
+ host: string;
108
+ port: number;
109
+ dbname: string;
110
+ username: string;
111
+ password: string;
112
+ }
113
+ /**
114
+ * AWS RDS マネージド secret(`DB_SECRET` に入れた JSON 文字列)を解決する。
115
+ *
116
+ * @remarks
117
+ * - `DB_SECRET` 未設定 → `undefined`(ローカル/`db:generate` の正常フォールバック)。
118
+ * - 設定されている場合は「完全な接続情報」であることを要求し、**不正 JSON / 必須キー欠損は throw**
119
+ * (静かに localhost へフォールバックして事故らせない)。`port` のみ欠損時は 3306 を補う。
120
+ *
121
+ * `honoDrizzleConfig`(db:migrate)と `workers-hono-kit-db-baseline` bin の双方が同じ解釈を使う。
122
+ */
123
+ export declare function resolveDbSecret(): ResolvedDbSecret | undefined;
@@ -92,8 +92,10 @@ export function honoDrizzleConfig(options) {
92
92
  * - `DB_SECRET` 未設定 → `undefined`(ローカル/`db:generate` の正常フォールバック)。
93
93
  * - 設定されている場合は「完全な接続情報」であることを要求し、**不正 JSON / 必須キー欠損は throw**
94
94
  * (静かに localhost へフォールバックして事故らせない)。`port` のみ欠損時は 3306 を補う。
95
+ *
96
+ * `honoDrizzleConfig`(db:migrate)と `workers-hono-kit-db-baseline` bin の双方が同じ解釈を使う。
95
97
  */
96
- function resolveDbSecret() {
98
+ export function resolveDbSecret() {
97
99
  const raw = process.env.DB_SECRET;
98
100
  if (!raw) {
99
101
  return undefined;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Minimal structural shape of a Workers `ExecutionContext`, limited to `waitUntil`.
3
+ *
4
+ * @remarks
5
+ * Declared structurally to avoid a dependency on `@cloudflare/workers-types`.
6
+ * Lives in the root export path so worker entry modules can import it without pulling in `./db`.
7
+ */
8
+ export interface ExecutionContextLike {
9
+ /** Extend the request's lifetime until `promise` settles (used to close connections after the response). */
10
+ waitUntil(promise: Promise<unknown>): void;
11
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -25,6 +25,7 @@ export { HttpStatus } from './http/http-status.js';
25
25
  export { createNestErrorHandler, nestNotFoundHandler, NEST_REASON_PHRASES } from './http/nest-error.js';
26
26
  export type { NestErrorHandlerOptions, ErrorReportContext, ErrorReporter } from './http/nest-error.js';
27
27
  export { normalizeTrailingSlash } from './http/trailing-slash.js';
28
+ export type { ExecutionContextLike } from './http/execution-context.js';
28
29
  export { KVCache } from './cache/kv-cache.js';
29
30
  export type { KVNamespace, KVCacheOptions } from './cache/kv-cache.js';
30
31
  export { createStripeClient, verifyStripeWebhook } from './stripe/client.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rdlabo/workers-hono-kit",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,6 +15,7 @@
15
15
  // npx workers-hono-kit-db-baseline [--migrations ./drizzle]
16
16
  import { createConnection } from 'mysql2/promise';
17
17
  import { baselineMigrations } from '../dist/db/migrate.js';
18
+ import { resolveDbSecret } from '../dist/db/index.js';
18
19
 
19
20
  function arg(name) {
20
21
  const i = process.argv.indexOf(`--${name}`);
@@ -22,16 +23,28 @@ function arg(name) {
22
23
  }
23
24
 
24
25
  const migrationsFolder = arg('migrations') ?? process.env.MIGRATIONS_DIR ?? './drizzle';
25
- const conn = {
26
- host: process.env.DB_HOST ?? '127.0.0.1',
27
- port: Number(process.env.DB_PORT ?? '3306'),
28
- user: process.env.DB_USER ?? 'root',
29
- password: process.env.DB_PASSWORD ?? 'root',
30
- database: process.env.DB_NAME,
31
- };
26
+ // db:migrate(honoDrizzleConfig)と同じ DB_SECRET 解釈を共有する。CI/本番は AWS Secrets Manager の
27
+ // RDS マネージド secret を DB_SECRET に渡す運用(不正/欠損は resolveDbSecret が throw)。未設定時は
28
+ // 従来の個別 DB_* env にフォールバック。
29
+ const secret = resolveDbSecret();
30
+ const conn = secret
31
+ ? {
32
+ host: secret.host,
33
+ port: secret.port,
34
+ user: secret.username,
35
+ password: secret.password,
36
+ database: secret.dbname,
37
+ }
38
+ : {
39
+ host: process.env.DB_HOST ?? '127.0.0.1',
40
+ port: Number(process.env.DB_PORT ?? '3306'),
41
+ user: process.env.DB_USER ?? 'root',
42
+ password: process.env.DB_PASSWORD ?? 'root',
43
+ database: process.env.DB_NAME,
44
+ };
32
45
 
33
46
  if (!conn.database) {
34
- console.error('[db:baseline] DB_NAME is required.');
47
+ console.error('[db:baseline] DB_NAME (or DB_SECRET) is required.');
35
48
  process.exit(1);
36
49
  }
37
50
 
@@ -1,5 +1,8 @@
1
1
  import { createConnection } from 'mysql2/promise';
2
2
  import type { Connection } from 'mysql2/promise';
3
+ import type { ExecutionContextLike } from '../http/execution-context.js';
4
+
5
+ export type { ExecutionContextLike } from '../http/execution-context.js';
3
6
 
4
7
  /**
5
8
  * Minimal structural shape of a Cloudflare Hyperdrive binding.
@@ -59,17 +62,6 @@ export function hyperdriveConnectionOptions(
59
62
  };
60
63
  }
61
64
 
62
- /**
63
- * Minimal structural shape of a Workers `ExecutionContext`, limited to `waitUntil`.
64
- *
65
- * @remarks
66
- * Declared structurally to avoid a dependency on `@cloudflare/workers-types`.
67
- */
68
- export interface ExecutionContextLike {
69
- /** Extend the request's lifetime until `promise` settles (used to close connections after the response). */
70
- waitUntil(promise: Promise<unknown>): void;
71
- }
72
-
73
65
  /**
74
66
  * Open primary and replica connections, run `fn` with them, and close both afterwards.
75
67
  *
package/src/db/index.ts CHANGED
@@ -32,8 +32,8 @@ export type { HyperdriveLike, ExecutionContextLike } from './connection.js';
32
32
 
33
33
  export { toJstDate, jstTimestampParams, jstDatetimeParams, jstDateParams } from './jst.js';
34
34
 
35
- export { DRIZZLE_ORM_OPTIONS, honoDrizzleConfig } from './orm-config.js';
36
- export type { HonoDrizzleConfigOptions } from './orm-config.js';
35
+ export { DRIZZLE_ORM_OPTIONS, honoDrizzleConfig, resolveDbSecret } from './orm-config.js';
36
+ export type { HonoDrizzleConfigOptions, ResolvedDbSecret } from './orm-config.js';
37
37
 
38
38
  export { baselineMigrations, readBaselineEntry } from './migrate.js';
39
39
  export type { BaselineMigrationsOptions, BaselineResult, BaselineEntry } from './migrate.js';
@@ -128,6 +128,15 @@ export function honoDrizzleConfig(options: HonoDrizzleConfigOptions) {
128
128
  };
129
129
  }
130
130
 
131
+ /** {@link resolveDbSecret} の戻り値(正規化済みの接続情報)。 */
132
+ export interface ResolvedDbSecret {
133
+ host: string;
134
+ port: number;
135
+ dbname: string;
136
+ username: string;
137
+ password: string;
138
+ }
139
+
131
140
  /**
132
141
  * AWS RDS マネージド secret(`DB_SECRET` に入れた JSON 文字列)を解決する。
133
142
  *
@@ -135,8 +144,10 @@ export function honoDrizzleConfig(options: HonoDrizzleConfigOptions) {
135
144
  * - `DB_SECRET` 未設定 → `undefined`(ローカル/`db:generate` の正常フォールバック)。
136
145
  * - 設定されている場合は「完全な接続情報」であることを要求し、**不正 JSON / 必須キー欠損は throw**
137
146
  * (静かに localhost へフォールバックして事故らせない)。`port` のみ欠損時は 3306 を補う。
147
+ *
148
+ * `honoDrizzleConfig`(db:migrate)と `workers-hono-kit-db-baseline` bin の双方が同じ解釈を使う。
138
149
  */
139
- function resolveDbSecret(): { host: string; port: number; dbname: string; username: string; password: string } | undefined {
150
+ export function resolveDbSecret(): ResolvedDbSecret | undefined {
140
151
  const raw = process.env.DB_SECRET;
141
152
  if (!raw) {
142
153
  return undefined;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Minimal structural shape of a Workers `ExecutionContext`, limited to `waitUntil`.
3
+ *
4
+ * @remarks
5
+ * Declared structurally to avoid a dependency on `@cloudflare/workers-types`.
6
+ * Lives in the root export path so worker entry modules can import it without pulling in `./db`.
7
+ */
8
+ export interface ExecutionContextLike {
9
+ /** Extend the request's lifetime until `promise` settles (used to close connections after the response). */
10
+ waitUntil(promise: Promise<unknown>): void;
11
+ }
package/src/index.ts CHANGED
@@ -35,6 +35,7 @@ export { HttpStatus } from './http/http-status.js';
35
35
  export { createNestErrorHandler, nestNotFoundHandler, NEST_REASON_PHRASES } from './http/nest-error.js';
36
36
  export type { NestErrorHandlerOptions, ErrorReportContext, ErrorReporter } from './http/nest-error.js';
37
37
  export { normalizeTrailingSlash } from './http/trailing-slash.js';
38
+ export type { ExecutionContextLike } from './http/execution-context.js';
38
39
 
39
40
  // cache
40
41
  export { KVCache } from './cache/kv-cache.js';