@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,17 +1,33 @@
1
1
  import Stripe from 'stripe';
2
2
 
3
3
  /**
4
- * Stripe クライアント生成(フリート共通 = receptray/tipsys hono)。Cloudflare Workers には Node の
5
- * http スタックが無いため、Stripe SDK の fetch ベース HttpClient を使う。
6
- *
7
- * `apiVersion` は **任意**: 各 repo の `/api`(NestJS)と挙動を一致させるため、固定したい repo は
8
- * 渡し(例 tipsys は `'2024-04-10'`)、SDK 既定で良い repo は省く(例 receptray)。
4
+ * Options for {@link createStripeClient}.
9
5
  */
10
6
  export interface CreateStripeClientOptions {
11
- /** 固定する Stripe API バージョン。省略すると SDK 既定。 */
7
+ /**
8
+ * Stripe API version to pin the client to. When omitted, the SDK's built-in default is used.
9
+ * Pin it when you need stable, reproducible API behavior independent of SDK upgrades.
10
+ */
12
11
  apiVersion?: string;
13
12
  }
14
13
 
14
+ /**
15
+ * Create a Stripe client configured to run on Cloudflare Workers.
16
+ *
17
+ * @remarks
18
+ * Workers has no Node.js `http` stack, so the client is built with `Stripe.createFetchHttpClient()`
19
+ * (a `fetch`-based HTTP client) instead of the SDK's default Node transport.
20
+ *
21
+ * @param secret - Stripe secret API key.
22
+ * @param options - Optional client configuration; see {@link CreateStripeClientOptions}.
23
+ * @returns A configured {@link Stripe} instance.
24
+ * @throws Error when `secret` is empty.
25
+ * @example
26
+ * ```ts
27
+ * const stripe = createStripeClient(env.STRIPE_SECRET, { apiVersion: '2024-04-10' });
28
+ * const customer = await stripe.customers.retrieve(customerId);
29
+ * ```
30
+ */
15
31
  export function createStripeClient(secret: string, options: CreateStripeClientOptions = {}): Stripe {
16
32
  if (!secret) {
17
33
  throw new Error('Stripe secret is not set');
@@ -24,9 +40,30 @@ export function createStripeClient(secret: string, options: CreateStripeClientOp
24
40
  }
25
41
 
26
42
  /**
27
- * Webhook 署名の検証。Workers では同期版 `constructEvent` が使えない(SubtleCrypto が非同期)ため
28
- * `constructEventAsync` + `SubtleCryptoProvider` を使う。`secret` は署名検証には無関係だが、検証用の
29
- * クライアント生成に必要(API コールはしない)。
43
+ * Verify a Stripe webhook signature and return the parsed event.
44
+ *
45
+ * @remarks
46
+ * Uses `constructEventAsync` together with `Stripe.createSubtleCryptoProvider()` because the Workers
47
+ * crypto API (SubtleCrypto) is asynchronous and the synchronous `constructEvent` is unavailable.
48
+ * The `secret` is not used by signature verification itself, but a client must be constructed to
49
+ * perform the check; no Stripe API call is made.
50
+ *
51
+ * @param secret - Stripe secret API key, used only to construct the verifying client.
52
+ * @param webhookSecret - Endpoint signing secret used to validate the signature.
53
+ * @param payload - Raw request body exactly as received (string or `ArrayBuffer`).
54
+ * @param signature - Value of the `Stripe-Signature` request header.
55
+ * @returns The verified {@link Stripe.Event}.
56
+ * @throws Error when `webhookSecret` is empty, or when `secret` is empty (the verifying client cannot be constructed).
57
+ * @throws Stripe.errors.StripeSignatureVerificationError when the signature does not match.
58
+ * @example
59
+ * ```ts
60
+ * const event = await verifyStripeWebhook(
61
+ * env.STRIPE_SECRET,
62
+ * env.STRIPE_WEBHOOK_SECRET,
63
+ * await request.text(),
64
+ * request.headers.get('stripe-signature')!,
65
+ * );
66
+ * ```
30
67
  */
31
68
  export function verifyStripeWebhook(
32
69
  secret: string,
@@ -3,11 +3,27 @@ import type { DecodedIdToken } from '../firebase/firebase-verifier.js';
3
3
  import type { FakeFirebaseVerifier } from './fakes.js';
4
4
 
5
5
  /**
6
- * app interceptor 互換の認証ヘッダ(`x-amz-security-token` + `x-amz-meta-*`)を組む。
7
- * fleet hono repo の route spec で同形に重複していたものを集約。
6
+ * Build authentication headers compatible with the client interceptor convention
7
+ * (`x-amz-security-token` + `x-amz-meta-*`).
8
8
  *
9
- * - `version` `app_version`(varchar(10)) に入るため 10 文字以内。
10
- * - `contentType: null` を渡すと content-type を付けない(GET 等)。
9
+ * Consolidates the identically-shaped header boilerplate that route specs tend to duplicate.
10
+ *
11
+ * @remarks
12
+ * `version` is persisted into an `app_version` column (`varchar(10)`), so keep it to 10 characters
13
+ * or fewer. Passing `contentType: null` omits the `content-type` header entirely (e.g. for GET requests).
14
+ *
15
+ * @param token - Security token placed in the `x-amz-security-token` header.
16
+ * @param opts - Optional overrides.
17
+ * @param opts.version - App version for `x-amz-meta-version` (defaults to `'1.0.0'`).
18
+ * @param opts.uuid - Device/client UUID for `x-amz-meta-uuid` (defaults to `'test-uuid'`).
19
+ * @param opts.contentType - Content type; defaults to `'application/json'`. Pass `null` to omit the header.
20
+ * @returns A plain header record suitable for `fetch`/`app.request` calls.
21
+ * @example
22
+ * ```ts
23
+ * const res = await app.request('/me', { headers: authHeaders(token) });
24
+ * // GET without a content-type header:
25
+ * await app.request('/items', { headers: authHeaders(token, { contentType: null }) });
26
+ * ```
11
27
  */
12
28
  export function authHeaders(
13
29
  token: string,
@@ -25,8 +41,22 @@ export function authHeaders(
25
41
  }
26
42
 
27
43
  /**
28
- * fake firebase にトークンを登録するだけの薄いヘルパ(DB を触らない)。戻り値はトークン。
29
- * `users` テーブル形が repo 固有(例: airlec は email 主)で provisionUser が合わない場合に使う。
44
+ * Register a token on a fake Firebase verifier without touching the database.
45
+ *
46
+ * Use this when {@link provisionUser} does not fit because the project's `users` table has a
47
+ * non-conventional shape (for example, keyed by email rather than `firebase_uid`); pair it with a
48
+ * project-specific provisioning step.
49
+ *
50
+ * @param firebase - In-memory verifier to register the token on.
51
+ * @param uid - Firebase UID associated with the token.
52
+ * @param record - Additional decoded-token fields to merge in (e.g. `email`).
53
+ * @param token - Token string to register (defaults to `` `tok-${uid}` ``).
54
+ * @returns The registered token string.
55
+ * @example
56
+ * ```ts
57
+ * const token = registerFirebaseToken(firebase, 'uid-1', { email: 'a@example.com' });
58
+ * const res = await app.request('/me', { headers: authHeaders(token) });
59
+ * ```
30
60
  */
31
61
  export function registerFirebaseToken(
32
62
  firebase: FakeFirebaseVerifier,
@@ -39,10 +69,28 @@ export function registerFirebaseToken(
39
69
  }
40
70
 
41
71
  /**
42
- * fake firebase にトークンを登録し、`users(firebase_uid)` 行を用意して userId を返す。
43
- * `users(id, firebase_uid, agree)` の fleet 共通形を前提(foodlabel/receptray など)。同 uid の
44
- * 既存行があれば再利用する(冪等)。users テーブル形が異なる repo は registerFirebaseToken + 独自
45
- * provision を使う。
72
+ * Register a token on a fake Firebase verifier and ensure a matching `users` row exists, returning
73
+ * its id.
74
+ *
75
+ * @remarks
76
+ * Assumes a conventional `users(id, firebase_uid, agree)` table. The operation is idempotent: if a
77
+ * row with the same `firebase_uid` already exists it is reused rather than re-inserted. For projects
78
+ * whose `users` table has a different shape, use {@link registerFirebaseToken} plus project-specific
79
+ * provisioning instead.
80
+ *
81
+ * @param pool - mysql2 pool connected to the test database.
82
+ * @param firebase - In-memory verifier to register the token on.
83
+ * @param opts - Provisioning options.
84
+ * @param opts.uid - Firebase UID for the user.
85
+ * @param opts.token - Token string to register (defaults to `` `tok-${uid}` ``).
86
+ * @param opts.agree - Value for the `agree` column on insert (defaults to `1`).
87
+ * @param opts.email - Optional email merged into the decoded token record.
88
+ * @returns The resolved `userId`, along with the `uid` and registered `token`.
89
+ * @example
90
+ * ```ts
91
+ * const { userId, token } = await provisionUser(pool, firebase, { uid: 'uid-1' });
92
+ * const res = await app.request('/me', { headers: authHeaders(token) });
93
+ * ```
46
94
  */
47
95
  export async function provisionUser(
48
96
  pool: Pool,
@@ -1,15 +1,26 @@
1
1
  /**
2
- * 部分実装から test double を作る。設定済みメソッドはそのまま、未設定メソッドを呼ぶと
3
- * `${name}.${method} not configured` で明示的に失敗する。
2
+ * Build a test double from a partial implementation: configured members are returned as-is, while
3
+ * calling any unconfigured member fails explicitly with `` `${name}.${method} not configured` ``.
4
4
  *
5
- * 各 repo の Fake*Gateway に散っていた「`Partial<impl>` を受け取り、未設定なら throw する手書き
6
- * クラス」の定型を一本化する。interface がドメインごとに異なる gateway(Stripe 等)でも、これで
7
- * 1 行で必要メソッドだけ差した fake を作れる:
5
+ * @remarks
6
+ * Replaces the hand-written "accept a `Partial<impl>` and throw on anything unset" fake classes that
7
+ * tend to proliferate per gateway. Because gateway interfaces differ by domain (Stripe, etc.), this
8
+ * lets you stub only the members a given test exercises in a single line.
8
9
  *
9
- * const stripe = configurableFake<StripeGateway>(
10
- * { listPaymentIntents: async () => fakeApiList([fakePaymentIntent()]) },
11
- * 'FakeStripeGateway',
12
- * );
10
+ * @typeParam T - The interface being faked.
11
+ * @param impl - Partial implementation; only the members the test needs.
12
+ * @param name - Label used in the "not configured" error message (defaults to `'fake'`).
13
+ * @returns A proxy typed as `T` that delegates to `impl` and throws on unconfigured members.
14
+ * @throws Error `` `${name}.${method} not configured` `` when an unconfigured string-keyed member is called.
15
+ * @example
16
+ * ```ts
17
+ * const stripe = configurableFake<StripeGateway>(
18
+ * { listPaymentIntents: async () => fakeApiList([fakePaymentIntent()]) },
19
+ * 'FakeStripeGateway',
20
+ * );
21
+ * await stripe.listPaymentIntents(); // ok
22
+ * await stripe.cancelPaymentIntent('pi_1'); // throws: FakeStripeGateway.cancelPaymentIntent not configured
23
+ * ```
13
24
  */
14
25
  export function configurableFake<T extends object>(impl: Partial<T>, name = 'fake'): T {
15
26
  return new Proxy(impl, {
@@ -17,8 +28,9 @@ export function configurableFake<T extends object>(impl: Partial<T>, name = 'fak
17
28
  if (prop in target) {
18
29
  return (target as Record<string | symbol, unknown>)[prop];
19
30
  }
20
- // Promise インターロップ用プロパティには「未設定メソッド」関数を返さない。返すと fake 自身が
21
- // thenable 扱いされ、誤って await / Promise.resolve した瞬間に then() が呼ばれて throw する罠になる。
31
+ // Never return the "unconfigured member" function for Promise-interop properties. Doing so would
32
+ // make the fake itself look thenable, so accidentally awaiting it (or passing it to
33
+ // Promise.resolve) would invoke then() and throw — a subtle footgun.
22
34
  if (prop === 'then' || prop === 'catch' || prop === 'finally') {
23
35
  return undefined;
24
36
  }
package/src/testing/db.ts CHANGED
@@ -4,40 +4,87 @@ import { createConnection, createPool } from 'mysql2/promise';
4
4
  import type { Pool } from 'mysql2/promise';
5
5
 
6
6
  /**
7
- * フリート共通のテスト DB ヘルパ(各 repo testing/db.ts を集約)。
8
- * テストスキーマは「コミット済み Drizzle マイグレーション」を単一ソースとして構築する
9
- * (手書き schema.sql ではなく `db:generate` 由来の ./drizzle)。
7
+ * Connection parameters for the test MySQL server.
10
8
  *
11
- * Node 専用(vitest 下で実行)。実行時 parity には無関係なテスト基盤。
9
+ * @see {@link CreateTestDbOptions.connection} for how defaults are resolved.
12
10
  */
13
11
  export interface TestDbConnection {
12
+ /** Server host. */
14
13
  host: string;
14
+ /** Server port. */
15
15
  port: number;
16
+ /** User name. */
16
17
  user: string;
18
+ /** Password. */
17
19
  password: string;
18
20
  }
19
21
 
22
+ /**
23
+ * Options for {@link createTestDb}.
24
+ */
20
25
  export interface CreateTestDbOptions {
21
- /** テスト DB 名(例 'tipsys_test')。並列実行で feature 毎に分けたい場合は呼び出し側で TEST_DB を解決して渡す。 */
26
+ /**
27
+ * Test database name (e.g. `'app_test'`). To isolate parallel runs per feature, resolve a per-run
28
+ * name on the caller side and pass it here.
29
+ */
22
30
  dbName: string;
23
- /** Drizzle マイグレーションフォルダの絶対パス(呼び出し側で `join(here, '..', 'drizzle')` を解決して渡す)。 */
31
+ /**
32
+ * Absolute path to the Drizzle migrations folder. Resolve it on the caller side, e.g.
33
+ * `join(here, '..', 'drizzle')`.
34
+ */
24
35
  migrationsFolder: string;
25
- /** 接続情報。未指定は env(DB_HOST/DB_PORT/DB_USER/DB_PASSWORD)→ 127.0.0.1/3306/root/root。 */
36
+ /**
37
+ * Connection overrides. Unspecified fields fall back to environment variables
38
+ * (`DB_HOST`/`DB_PORT`/`DB_USER`/`DB_PASSWORD`), then to `127.0.0.1`/`3306`/`root`/`root`.
39
+ */
26
40
  connection?: Partial<TestDbConnection>;
27
41
  }
28
42
 
43
+ /**
44
+ * Test database handle returned by {@link createTestDb}, bundling schema setup, pooling, and
45
+ * fixture helpers for a single test database.
46
+ */
29
47
  export interface TestDb {
48
+ /** The resolved test database name. */
30
49
  readonly dbName: string;
50
+ /** The resolved connection parameters. */
31
51
  readonly connection: TestDbConnection;
32
- /** DROP/CREATE して Drizzle マイグレーションを適用しスキーマを構築。 */
52
+ /**
53
+ * Drop and recreate the database, then apply the committed Drizzle migrations to build the schema.
54
+ *
55
+ * @returns A promise that resolves once migrations have been applied.
56
+ */
33
57
  resetSchema(): Promise<void>;
34
- /** テスト DB に繋いだ mysql2 プールを返す(afterAll で pool.end())。 */
58
+ /**
59
+ * Create a mysql2 pool connected to the test database.
60
+ *
61
+ * @remarks Call `pool.end()` (e.g. in `afterAll`) to release connections.
62
+ * @returns A connection pool for the test database.
63
+ */
35
64
  createTestPool(): Pool;
36
- /** 全テーブルを TRUNCATE(information_schema から動的取得。__drizzle_migrations は除外)。 */
65
+ /**
66
+ * Truncate every base table in the database.
67
+ *
68
+ * @remarks Table names are discovered dynamically from `information_schema`; the
69
+ * `__drizzle_migrations` bookkeeping table is excluded. Foreign-key checks are disabled for the
70
+ * duration so truncation order does not matter.
71
+ * @param pool - Pool connected to the test database.
72
+ */
37
73
  truncateAll(pool: Pool): Promise<void>;
38
- /** 1 行 insert する汎用 seed(列名→値)。route spec の fixture 用。 */
74
+ /**
75
+ * Insert a single row, mapping column names to values — a generic fixture helper for specs.
76
+ *
77
+ * @param pool - Pool connected to the test database.
78
+ * @param table - Target table name.
79
+ * @param row - Column-name to value map. A no-op if empty.
80
+ */
39
81
  seed(pool: Pool, table: string, row: Record<string, unknown>): Promise<void>;
40
- /** ローカル MySQL が到達可能か(`describe.skipIf(!(await mysqlReachable()))` のガード用)。 */
82
+ /**
83
+ * Report whether the local MySQL server is reachable.
84
+ *
85
+ * @remarks Useful as a guard, e.g. `describe.skipIf(!(await mysqlReachable()))`.
86
+ * @returns `true` if a connection could be opened, otherwise `false`.
87
+ */
41
88
  mysqlReachable(): Promise<boolean>;
42
89
  }
43
90
 
@@ -51,6 +98,28 @@ function resolveConnection(override?: Partial<TestDbConnection>): TestDbConnecti
51
98
  };
52
99
  }
53
100
 
101
+ /**
102
+ * Create a {@link TestDb} handle for a single test database.
103
+ *
104
+ * @remarks
105
+ * The test schema is built from the committed Drizzle migrations as the single source of truth
106
+ * (the `db:generate` output under `./drizzle`), rather than a hand-written `schema.sql`. This helper
107
+ * is Node-only test infrastructure (run under Vitest) and is unrelated to runtime behavior.
108
+ *
109
+ * @param options - Database name, migrations folder, and optional connection overrides. See
110
+ * {@link CreateTestDbOptions}.
111
+ * @returns A handle exposing schema setup, pooling, truncation, seeding, and a reachability probe.
112
+ * @example
113
+ * ```ts
114
+ * const testDb = createTestDb({ dbName: 'app_test', migrationsFolder: join(here, '..', 'drizzle') });
115
+ * beforeAll(async () => {
116
+ * await testDb.resetSchema();
117
+ * });
118
+ * const pool = testDb.createTestPool();
119
+ * beforeEach(() => testDb.truncateAll(pool));
120
+ * afterAll(() => pool.end());
121
+ * ```
122
+ */
54
123
  export function createTestDb(options: CreateTestDbOptions): TestDb {
55
124
  const { dbName, migrationsFolder } = options;
56
125
  const connection = resolveConnection(options.connection);
@@ -80,7 +149,7 @@ export function createTestDb(options: CreateTestDbOptions): TestDb {
80
149
  timezone: '+09:00',
81
150
  });
82
151
  // Pin ONLY_FULL_GROUP_BY on every pooled connection so GROUP BY violations surface in specs
83
- // regardless of the server's my.cnf (fleet policy centralized here, not per-repo). CONCAT keeps
152
+ // regardless of the server's my.cnf (the policy is centralized here, not left to each server). CONCAT keeps
84
153
  // the server's other sql_mode flags and is harmless if ONLY_FULL_GROUP_BY is already present.
85
154
  // mysql2 queues this SET ahead of the consumer's first query on each new physical connection.
86
155
  pool.on('connection', (conn) => {
@@ -4,17 +4,40 @@ import type { DisposableDatabase } from '../db/database.js';
4
4
  import type { DecodedIdToken, FirebaseVerifier } from '../firebase/firebase-verifier.js';
5
5
 
6
6
  /**
7
- * オフライン route テスト用の in-memory FirebaseVerifier(4 repo 同一実装を集約)。
8
- * `register(token, { uid })` で偽 ID を仕込む。
7
+ * In-memory {@link FirebaseVerifier} implementation for offline route tests.
8
+ *
9
+ * Seed fake identities with {@link FakeFirebaseVerifier.register | register(token, { uid })}, then
10
+ * verification resolves the registered decoded token instead of calling a real Firebase backend.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * const firebase = new FakeFirebaseVerifier();
15
+ * firebase.register('tok-1', { uid: 'uid-1' });
16
+ * const decoded = await firebase.verifyIdToken('tok-1'); // { uid: 'uid-1' }
17
+ * ```
9
18
  */
10
19
  export class FakeFirebaseVerifier implements FirebaseVerifier {
11
20
  private readonly tokens = new Map<string, DecodedIdToken>();
21
+ /** UIDs passed to {@link FakeFirebaseVerifier.deleteUser}, in call order, for assertions. */
12
22
  readonly deleted: string[] = [];
13
23
 
24
+ /**
25
+ * Register a fake decoded token so that {@link FakeFirebaseVerifier.verifyIdToken} resolves it.
26
+ *
27
+ * @param token - Token string clients will present.
28
+ * @param record - Decoded token returned on verification (must include `uid`).
29
+ */
14
30
  register(token: string, record: DecodedIdToken): void {
15
31
  this.tokens.set(token, record);
16
32
  }
17
33
 
34
+ /**
35
+ * Resolve the decoded token previously registered for `idToken`.
36
+ *
37
+ * @param idToken - Token string to verify.
38
+ * @returns The registered decoded token.
39
+ * @throws Error if the token was never registered.
40
+ */
18
41
  async verifyIdToken(idToken: string): Promise<DecodedIdToken> {
19
42
  const record = this.tokens.get(idToken);
20
43
  if (!record) {
@@ -23,25 +46,57 @@ export class FakeFirebaseVerifier implements FirebaseVerifier {
23
46
  return record;
24
47
  }
25
48
 
49
+ /**
50
+ * Return a minimal user record echoing the requested UID.
51
+ *
52
+ * @param uid - UID to look up.
53
+ * @returns An object containing the `uid` (never `null` in this fake).
54
+ */
26
55
  async getUser(uid: string): Promise<{ uid: string; email?: string } | null> {
27
56
  return { uid };
28
57
  }
29
58
 
59
+ /**
60
+ * Record a user deletion by appending the UID to {@link FakeFirebaseVerifier.deleted}.
61
+ *
62
+ * @param uid - UID being deleted.
63
+ */
30
64
  async deleteUser(uid: string): Promise<void> {
31
65
  this.deleted.push(uid);
32
66
  }
33
67
  }
34
68
 
69
+ /**
70
+ * Options for {@link createPoolDatabase}.
71
+ *
72
+ * @typeParam TDrizzle - The Drizzle instance type, supplied by the consumer so that type identity is
73
+ * not coupled to this package's copy of `drizzle-orm`.
74
+ */
35
75
  export interface CreatePoolDatabaseOptions<TDrizzle> {
36
- /** テスト用プール(primary/replica 兼用)。 */
76
+ /** Test pool used as both primary and replica. */
37
77
  pool: Pool;
38
- /** 消費側の drizzle-orm `drizzle(pool, { schema, ... })` を作って渡す。 */
78
+ /** Drizzle instance built by the consumer with its own `drizzle-orm`, e.g. `drizzle(pool, { schema, ... })`. */
39
79
  orm: TDrizzle;
40
80
  }
41
81
 
42
82
  /**
43
- * テスト用にプール 1 本を primary/replica 兼用にした Database(foodlabel PoolDatabase 相当)。
44
- * `dispose()` はプールを閉じる。orm は消費側が自分の drizzle-orm で作って渡す(型同一性の分離)。
83
+ * Create a `Database` backed by a single pool used as both primary and replica, suitable for tests.
84
+ *
85
+ * @remarks
86
+ * `dispose()` ends the pool. The `orm` is provided by the caller (rather than constructed here) so
87
+ * the returned database uses the consumer's own `drizzle-orm` types, avoiding type-identity clashes
88
+ * across duplicated `drizzle-orm` installs.
89
+ *
90
+ * @typeParam TDrizzle - The Drizzle instance type provided by the consumer.
91
+ * @param options - Pool and Drizzle instance. See {@link CreatePoolDatabaseOptions}.
92
+ * @returns A {@link DisposableDatabase} whose `dispose()` closes the pool.
93
+ * @example
94
+ * ```ts
95
+ * const pool = testDb.createTestPool();
96
+ * const db = createPoolDatabase({ pool, orm: drizzle(pool, { schema }) });
97
+ * // ... run tests ...
98
+ * await db.dispose();
99
+ * ```
45
100
  */
46
101
  export function createPoolDatabase<TDrizzle>(
47
102
  options: CreatePoolDatabaseOptions<TDrizzle>,
@@ -57,9 +112,22 @@ export function createPoolDatabase<TDrizzle>(
57
112
  }
58
113
 
59
114
  /**
60
- * DB に触れない route(GET / 等)用の Database スタブ。write/transaction は誤用検知のため throw。
61
- * dispose は no-op(Hyperdrive/Pool 背面の DisposableDatabase を期待する repo でもそのまま使える)。
62
- * orm 型は呼び出し側が指定(既定 unknown)。
115
+ * Create a no-op `Database` stub for routes that never touch the database (e.g. plain GET handlers).
116
+ *
117
+ * @remarks
118
+ * `read` resolves to an empty array, while `write` and `transaction` throw so that any unexpected
119
+ * database access is caught as a misuse. `dispose` is a no-op, so this can stand in for a
120
+ * {@link DisposableDatabase} backing (e.g. a Hyperdrive- or pool-based one) without changes.
121
+ *
122
+ * @typeParam TDrizzle - The Drizzle instance type the consumer expects (defaults to `unknown`).
123
+ * @returns A {@link DisposableDatabase} that reads empty and throws on writes/transactions.
124
+ * @throws Error from `write`/`transaction` if they are accessed.
125
+ * @example
126
+ * ```ts
127
+ * const db = createNoopDatabase();
128
+ * await db.read('SELECT 1'); // []
129
+ * await db.write(async (dz) => dz); // throws: noopDatabase.write accessed unexpectedly
130
+ * ```
63
131
  */
64
132
  export function createNoopDatabase<TDrizzle = unknown>(): DisposableDatabase<TDrizzle> {
65
133
  return {
@@ -1,5 +1,10 @@
1
- // @rdlabo/workers-hono-kit/testing — フリート共通のテスト基盤(mysql2/drizzle 依存)。
2
- // 実行時には読み込まれないテスト専用ヘルパ。各 repo testing/db.ts・fakes.ts を集約。
1
+ /**
2
+ * Shared test infrastructure for Hono on Cloudflare Workers projects (depends on `mysql2`/`drizzle-orm`).
3
+ *
4
+ * Test-only helpers that are never loaded at runtime. This subpath consolidates the duplicated
5
+ * test boilerplate (test DB setup, in-memory fakes, auth header builders, Stripe fixtures) that
6
+ * tends to be copy-pasted across projects into a single, importable surface.
7
+ */
3
8
 
4
9
  export { createTestDb } from './db.js';
5
10
  export type { TestDb, CreateTestDbOptions, TestDbConnection } from './db.js';
@@ -8,13 +13,13 @@ export { FakeFirebaseVerifier, createPoolDatabase, createNoopDatabase } from './
8
13
  export type { CreatePoolDatabaseOptions } from './fakes.js';
9
14
  export type { Database, DisposableDatabase, QueryRunner, TxOf } from '../db/database.js';
10
15
 
11
- // 認証テストヘルパ(route spec のヘッダ生成・ユーザ provision を集約)。
16
+ // Authentication test helpers (route-spec header builders and user provisioning).
12
17
  export { authHeaders, registerFirebaseToken, provisionUser } from './auth.js';
13
18
 
14
- // test double ヘルパ(未設定メソッドで明示 throw する部分実装 fake)。
19
+ // Test double helper (partial-implementation fake that throws explicitly on unconfigured members).
15
20
  export { configurableFake } from './configurable-fake.js';
16
21
 
17
- // Stripe オブジェクトの test fixture factory。
22
+ // Test fixture factories for Stripe objects.
18
23
  export {
19
24
  fakeApiList,
20
25
  fakePaymentIntent,
@@ -1,11 +1,27 @@
1
1
  import type Stripe from 'stripe';
2
2
 
3
3
  /**
4
- * Stripe オブジェクトの test fixture factory。実 SDK 型は巨大なので、テストが参照する範囲だけを
5
- * 妥当な既定値で組み、`over` で上書きする(最後に 1 度だけ Stripe 型へキャスト)。fleet 各 repo の
6
- * 課金テストで同じダミー PaymentIntent/Event/... を手組みしていた重複を集約する。
4
+ * Test fixture factories for Stripe objects.
5
+ *
6
+ * The real SDK types are enormous, so each factory builds only the fields tests typically read,
7
+ * fills them with reasonable defaults, lets you override via `over`, and casts to the Stripe type
8
+ * once at the end. This consolidates the duplicated hand-built dummy `PaymentIntent`/`Event`/... that
9
+ * billing tests tend to reconstruct in every project.
7
10
  */
8
11
 
12
+ /**
13
+ * Build a fake Stripe `ApiList` wrapping the given data.
14
+ *
15
+ * @remarks Defaults: `object: 'list'`, `has_more: false`, `url: '/v1/_test'`.
16
+ * @typeParam T - Element type of the list.
17
+ * @param data - Items to place in `data`.
18
+ * @param over - Field overrides merged last.
19
+ * @returns A `Stripe.ApiList<T>` fixture.
20
+ * @example
21
+ * ```ts
22
+ * const list = fakeApiList([fakePaymentIntent()]);
23
+ * ```
24
+ */
9
25
  export function fakeApiList<T>(data: T[], over: Partial<Stripe.ApiList<T>> = {}): Stripe.ApiList<T> {
10
26
  return {
11
27
  object: 'list',
@@ -16,6 +32,18 @@ export function fakeApiList<T>(data: T[], over: Partial<Stripe.ApiList<T>> = {})
16
32
  };
17
33
  }
18
34
 
35
+ /**
36
+ * Build a fake Stripe `PaymentIntent`.
37
+ *
38
+ * @remarks Defaults: `id: 'pi_test_1'`, `object: 'payment_intent'`, `amount: 1000`, `currency: 'jpy'`,
39
+ * `status: 'succeeded'`, `created: 1_700_000_000`.
40
+ * @param over - Field overrides merged last.
41
+ * @returns A `Stripe.PaymentIntent` fixture.
42
+ * @example
43
+ * ```ts
44
+ * const pi = fakePaymentIntent({ status: 'requires_payment_method' });
45
+ * ```
46
+ */
19
47
  export function fakePaymentIntent(over: Partial<Stripe.PaymentIntent> = {}): Stripe.PaymentIntent {
20
48
  return {
21
49
  id: 'pi_test_1',
@@ -28,6 +56,20 @@ export function fakePaymentIntent(over: Partial<Stripe.PaymentIntent> = {}): Str
28
56
  } as Stripe.PaymentIntent;
29
57
  }
30
58
 
59
+ /**
60
+ * Build a fake Stripe webhook `Event` wrapping the given payload.
61
+ *
62
+ * @remarks Defaults: `id: 'evt_test_1'`, `object: 'event'`, `api_version: '2024-06-20'`,
63
+ * `created: 1_700_000_000`, `livemode: false`. The payload is placed at `data.object`.
64
+ * @param type - Event type (e.g. `'payment_intent.succeeded'`), assigned to `type`.
65
+ * @param dataObject - The object placed at `data.object`.
66
+ * @param over - Field overrides merged last.
67
+ * @returns A `Stripe.Event` fixture.
68
+ * @example
69
+ * ```ts
70
+ * const event = fakeStripeEvent('payment_intent.succeeded', fakePaymentIntent());
71
+ * ```
72
+ */
31
73
  export function fakeStripeEvent(type: string, dataObject: unknown, over: Partial<Stripe.Event> = {}): Stripe.Event {
32
74
  return {
33
75
  id: 'evt_test_1',
@@ -41,6 +83,18 @@ export function fakeStripeEvent(type: string, dataObject: unknown, over: Partial
41
83
  } as Stripe.Event;
42
84
  }
43
85
 
86
+ /**
87
+ * Build a fake Stripe `Checkout.Session`.
88
+ *
89
+ * @remarks Defaults: `id: 'cs_test_1'`, `object: 'checkout.session'`,
90
+ * `url: 'https://checkout.stripe.test/cs_test_1'`, `mode: 'subscription'`, `status: 'open'`.
91
+ * @param over - Field overrides merged last.
92
+ * @returns A `Stripe.Checkout.Session` fixture.
93
+ * @example
94
+ * ```ts
95
+ * const session = fakeCheckoutSession({ status: 'complete' });
96
+ * ```
97
+ */
44
98
  export function fakeCheckoutSession(over: Partial<Stripe.Checkout.Session> = {}): Stripe.Checkout.Session {
45
99
  return {
46
100
  id: 'cs_test_1',
@@ -52,6 +106,18 @@ export function fakeCheckoutSession(over: Partial<Stripe.Checkout.Session> = {})
52
106
  } as Stripe.Checkout.Session;
53
107
  }
54
108
 
109
+ /**
110
+ * Build a fake Stripe `Customer`.
111
+ *
112
+ * @remarks Defaults: `id: 'cus_test_1'`, `object: 'customer'`, `created: 1_700_000_000`,
113
+ * `livemode: false`.
114
+ * @param over - Field overrides merged last.
115
+ * @returns A `Stripe.Customer` fixture.
116
+ * @example
117
+ * ```ts
118
+ * const customer = fakeCustomer({ email: 'a@example.com' });
119
+ * ```
120
+ */
55
121
  export function fakeCustomer(over: Partial<Stripe.Customer> = {}): Stripe.Customer {
56
122
  return {
57
123
  id: 'cus_test_1',
@@ -62,6 +128,18 @@ export function fakeCustomer(over: Partial<Stripe.Customer> = {}): Stripe.Custom
62
128
  } as Stripe.Customer;
63
129
  }
64
130
 
131
+ /**
132
+ * Build a fake Stripe `Price`.
133
+ *
134
+ * @remarks Defaults: `id: 'price_test_1'`, `object: 'price'`, `active: true`, `currency: 'jpy'`,
135
+ * `unit_amount: 1000`.
136
+ * @param over - Field overrides merged last.
137
+ * @returns A `Stripe.Price` fixture.
138
+ * @example
139
+ * ```ts
140
+ * const price = fakePrice({ unit_amount: 2000 });
141
+ * ```
142
+ */
65
143
  export function fakePrice(over: Partial<Stripe.Price> = {}): Stripe.Price {
66
144
  return {
67
145
  id: 'price_test_1',
@@ -73,6 +151,18 @@ export function fakePrice(over: Partial<Stripe.Price> = {}): Stripe.Price {
73
151
  } as Stripe.Price;
74
152
  }
75
153
 
154
+ /**
155
+ * Build a fake Stripe `Subscription`.
156
+ *
157
+ * @remarks Defaults: `id: 'sub_test_1'`, `object: 'subscription'`, `status: 'active'`,
158
+ * `customer: 'cus_test_1'`, `created: 1_700_000_000`.
159
+ * @param over - Field overrides merged last.
160
+ * @returns A `Stripe.Subscription` fixture.
161
+ * @example
162
+ * ```ts
163
+ * const sub = fakeSubscription({ status: 'canceled' });
164
+ * ```
165
+ */
76
166
  export function fakeSubscription(over: Partial<Stripe.Subscription> = {}): Stripe.Subscription {
77
167
  return {
78
168
  id: 'sub_test_1',