@rdlabo/workers-hono-kit 0.10.6 → 0.11.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.
@@ -1,4 +1,3 @@
1
- import type { DecimalNumberConfig } from './decimal.js';
2
1
  /**
3
2
  * SQL expression for `ON UPDATE CURRENT_TIMESTAMP` (the MySQL session clock).
4
3
  * customType columns have no `.onUpdateNow()`, so pair this with `.$onUpdateFn(() => jstOnUpdateNow(fsp))`.
@@ -37,12 +36,3 @@ export declare const jstDate: (name: string) => import("drizzle-orm/mysql-core")
37
36
  driverParam: string | null;
38
37
  enumValues: undefined;
39
38
  }>;
40
- /** MySQL `decimal` — SELECT coerces string→number via `fromDriver`; writes bind the number as-is. */
41
- export declare const decimalNumber: (name: string, config: DecimalNumberConfig) => import("drizzle-orm/mysql-core").MySqlCustomColumnBuilder<{
42
- name: string;
43
- dataType: "custom";
44
- columnType: "MySqlCustomColumn";
45
- data: number | null;
46
- driverParam: string | number | null;
47
- enumValues: undefined;
48
- }>;
@@ -5,8 +5,7 @@
5
5
  * @remarks
6
6
  * `drizzle-orm` is a **peer** (the consumer resolves a single copy); the kit does not bundle it. The
7
7
  * return types are the `customType` inference as-is (`MySqlCustomColumnBuilder<…>`) with no `any`, so
8
- * the column's semantic type (`string | Date`, `number | null`, etc.) propagates to the consumer
9
- * table's `$inferSelect`.
8
+ * the column's semantic type (`string | Date`, etc.) propagates to the consumer table's `$inferSelect`.
10
9
  *
11
10
  * **Precondition (a single drizzle copy)**: Drizzle's `SQL` is a **nominal** type carrying a private
12
11
  * field `shouldInlineParams`, so if the kit and the consumer resolve different copies of drizzle,
@@ -23,7 +22,6 @@
23
22
  */
24
23
  import { sql } from 'drizzle-orm';
25
24
  import { customType } from 'drizzle-orm/mysql-core';
26
- import { decimalNumberParams } from './decimal.js';
27
25
  import { jstDateParams, jstDatetimeParams, jstTimestampParams } from './jst.js';
28
26
  /**
29
27
  * SQL expression for `ON UPDATE CURRENT_TIMESTAMP` (the MySQL session clock).
@@ -38,5 +36,3 @@ export const jstTimestamp = (name, opts) => customType(jstTimestampParams(opts?.
38
36
  export const jstDatetime = (name, opts) => customType(jstDatetimeParams(opts?.fsp))(name);
39
37
  /** MySQL `date` — on INSERT/UPDATE, normalizes ISO / empty strings to `YYYY-MM-DD` (via `toDriver`). */
40
38
  export const jstDate = (name) => customType(jstDateParams())(name);
41
- /** MySQL `decimal` — SELECT coerces string→number via `fromDriver`; writes bind the number as-is. */
42
- export const decimalNumber = (name, config) => customType(decimalNumberParams(config))(name);
@@ -53,7 +53,8 @@ export type TxOf<TDrizzle> = TDrizzle extends {
53
53
  */
54
54
  export interface Database<TDrizzle, TTx = TxOf<TDrizzle>> {
55
55
  /**
56
- * Run a raw SQL read against the replica, with deadlock retry.
56
+ * Run a raw SQL read against the replica. Hyperdrive-backed databases retry deadlocks and repeat
57
+ * the SELECT once on a fresh connection after mysql2 reports a fatal connection error.
57
58
  *
58
59
  * @typeParam T - the row shape.
59
60
  * @param sql - the SQL text, with `?` placeholders for `params`.
@@ -161,7 +162,9 @@ export interface CreateHyperdriveDatabaseOptions<TDrizzle> {
161
162
  * Construct one per request. Connections and the ORM are created on first use and reused for the
162
163
  * lifetime of the instance; the read/write/transaction surface is identical to
163
164
  * {@link createMysqlDatabase}. Workers automatically cleans up connections at the end of the
164
- * invocation, so callers do not need to close them manually.
165
+ * invocation, so callers do not need to close them manually. Replica SELECTs are repeated once on
166
+ * a fresh connection after a fatal mysql2 connection error. Writes and transactions are never
167
+ * repeated for connection errors because their commit state can be ambiguous.
165
168
  *
166
169
  * @typeParam TDrizzle - the consumer's Drizzle ORM type.
167
170
  * @param options - the primary/replica Hyperdrive bindings, the ORM factory, and connection options.
@@ -30,7 +30,9 @@ export function createMysqlDatabase(options) {
30
30
  * Construct one per request. Connections and the ORM are created on first use and reused for the
31
31
  * lifetime of the instance; the read/write/transaction surface is identical to
32
32
  * {@link createMysqlDatabase}. Workers automatically cleans up connections at the end of the
33
- * invocation, so callers do not need to close them manually.
33
+ * invocation, so callers do not need to close them manually. Replica SELECTs are repeated once on
34
+ * a fresh connection after a fatal mysql2 connection error. Writes and transactions are never
35
+ * repeated for connection errors because their commit state can be ambiguous.
34
36
  *
35
37
  * @typeParam TDrizzle - the consumer's Drizzle ORM type.
36
38
  * @param options - the primary/replica Hyperdrive bindings, the ORM factory, and connection options.
@@ -54,12 +56,24 @@ export function createHyperdriveDatabase(options) {
54
56
  const primary = () => (primaryConn ??= connect(primaryHyperdrive, connectionOptions));
55
57
  const replica = () => (replicaConn ??= connect(replicaHyperdrive, connectionOptions));
56
58
  const ormFor = async () => (orm ??= createOrm(await primary()));
59
+ const readFrom = (connection, sql, params) => retryWhenDeadlock(async () => {
60
+ const [rows] = (await (await connection).query(sql, params));
61
+ return rows;
62
+ });
57
63
  return {
58
- read(sql, params = []) {
59
- return retryWhenDeadlock(async () => {
60
- const [rows] = (await (await replica()).query(sql, params));
61
- return rows;
62
- });
64
+ async read(sql, params = []) {
65
+ const connection = replica();
66
+ const outcome = await readFrom(connection, sql, params).then((rows) => ({ ok: true, rows }), (error) => ({ ok: false, error }));
67
+ if (outcome.ok) {
68
+ return outcome.rows;
69
+ }
70
+ if (!isFatalConnectionError(outcome.error)) {
71
+ throw outcome.error;
72
+ }
73
+ if (replicaConn === connection) {
74
+ replicaConn = undefined;
75
+ }
76
+ return readFrom(replica(), sql, params);
63
77
  },
64
78
  async write(fn) {
65
79
  const dz = await ormFor();
@@ -104,3 +118,16 @@ export function databaseFrom(orm, replica) {
104
118
  function connect(hyperdrive, extra) {
105
119
  return createConnection(hyperdriveConnectionOptions(hyperdrive, extra));
106
120
  }
121
+ function isFatalConnectionError(error) {
122
+ let current = error;
123
+ const seen = new Set();
124
+ while (typeof current === 'object' && current !== null && !seen.has(current)) {
125
+ seen.add(current);
126
+ const value = current;
127
+ if (value.fatal === true) {
128
+ return true;
129
+ }
130
+ current = value.cause;
131
+ }
132
+ return false;
133
+ }
@@ -17,9 +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 { MYSQL_TIMEZONE, toJstDate, jstTimestampParams, jstDatetimeParams, jstDateParams } from './jst.js';
20
- export { coerceDecimalNumber, decimalNumberParams } from './decimal.js';
21
- export type { DecimalNumberConfig } from './decimal.js';
22
- export { jstTimestamp, jstDatetime, jstDate, decimalNumber, jstOnUpdateNow } from './columns.js';
20
+ export { jstTimestamp, jstDatetime, jstDate, jstOnUpdateNow } from './columns.js';
23
21
  export { DRIZZLE_ORM_OPTIONS, honoDrizzleConfig, resolveDbSecret } from './orm-config.js';
24
22
  export type { HonoDrizzleConfigOptions, ResolvedDbSecret } from './orm-config.js';
25
23
  export { baselineMigrations, readBaselineEntry } from './migrate.js';
package/dist/db/index.js CHANGED
@@ -14,8 +14,7 @@ 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 { MYSQL_TIMEZONE, toJstDate, jstTimestampParams, jstDatetimeParams, jstDateParams } from './jst.js';
17
- export { coerceDecimalNumber, decimalNumberParams } from './decimal.js';
18
- export { jstTimestamp, jstDatetime, jstDate, decimalNumber, jstOnUpdateNow } from './columns.js';
17
+ export { jstTimestamp, jstDatetime, jstDate, jstOnUpdateNow } from './columns.js';
19
18
  export { DRIZZLE_ORM_OPTIONS, honoDrizzleConfig, resolveDbSecret } from './orm-config.js';
20
19
  export { baselineMigrations, readBaselineEntry } from './migrate.js';
21
20
  export { reopenGuardedPaymentFailedSet } from './payment-failed.js';
@@ -0,0 +1,33 @@
1
+ # API: `@rdlabo/workers-hono-kit/business-time`
2
+
3
+ String-level JST business-time conversions (Workers UTC instant ↔ business calendar date / date-time), with **no `mysql2` / `drizzle-orm` dependency**. This is a different layer from the `./db` column helpers (which handle the MySQL wire format): the DB stays on JST, and the app handles JST explicitly through this module instead of relying implicitly on the connection `timezone`.
4
+
5
+ | Export | Description |
6
+ | --- | --- |
7
+ | `today(ref?)` | The JST business calendar date (`YYYY-MM-DD`) of `ref` (defaults to now). |
8
+ | `toBusinessDate(instant)` | UTC instant → JST business calendar date (`YYYY-MM-DD`). |
9
+ | `normalizeBusinessDate(value)` | Normalize a `string` / `Date` / nullish to `YYYY-MM-DD`; a `YYYY-MM-DD` string passes through unchanged, nullish/empty/invalid → `null`. |
10
+ | `toBusinessDateTime(instant)` | UTC instant → JST business date-time (`YYYY-MM-DD HH:mm:ss`). |
11
+ | `parseBusinessDateTime(value)` | JST business date-time string → UTC instant (accepts a space or `T` separator). |
12
+ | `formatBusinessDateTime(instant, pattern?)` | Format an instant in the business TZ (Nest `helper.formatDate`-compatible tokens). |
13
+ | `startOfBusinessDay(date)` / `endOfBusinessDay(date)` | UTC instant of `00:00:00` / `23:59:59` on a JST business date. |
14
+ | `businessDateTimeInstant(date, time)` | JST business date + wall-clock time → UTC instant. |
15
+ | `addBusinessDays(date, days)` | Add calendar days to a JST business date. |
16
+ | `ageOnBusinessDate(birthDate, asOfDate?)` | Full years of age on a business date (`asOfDate` defaults to `today()`). |
17
+ | `DEFAULT_BUSINESS_DATETIME_PATTERN` | Default `formatBusinessDateTime` pattern (`YYYY-MM-DDThh:mm:ss`). |
18
+ | `BUSINESS_TIMEZONE` / `BusinessDate` / `BusinessDateTime` | JST timezone constant and the business-date / date-time string types. |
19
+
20
+ ```ts
21
+ import {
22
+ toBusinessDate,
23
+ toBusinessDateTime,
24
+ formatBusinessDateTime,
25
+ addBusinessDays,
26
+ } from '@rdlabo/workers-hono-kit/business-time';
27
+
28
+ const now = new Date('2026-07-05T21:00:00Z');
29
+ toBusinessDate(now); // '2026-07-06' (JST)
30
+ toBusinessDateTime(now); // '2026-07-06 06:00:00'
31
+ formatBusinessDateTime(now); // '2026-07-06T06:00:00'
32
+ addBusinessDays('2026-07-06', 3); // '2026-07-09'
33
+ ```
package/docs/api-db.md ADDED
@@ -0,0 +1,49 @@
1
+ # API: `@rdlabo/workers-hono-kit/db`
2
+
3
+ Requires the `drizzle-orm` and `mysql2` peers. Reads run against a replica via raw SQL; writes/transactions run against the primary through the Drizzle ORM with deadlock retry. The kit deliberately does not depend on the ORM's type identity — you pass the Drizzle instance in.
4
+
5
+ | Export | Description |
6
+ | --- | --- |
7
+ | `createHyperdriveDatabase(options)` | `DisposableDatabase` that lazily opens primary/replica connections from Hyperdrive bindings per request. A replica SELECT is repeated at most once on a fresh connection after a fatal mysql2 connection error; writes and transactions are not repeated. Workers cleans connections up at invocation end; the legacy `dispose()` is a no-op. |
8
+ | `createMysqlDatabase(options)` | Assemble a `Database` from an already-connected Drizzle ORM + replica `QueryRunner`. |
9
+ | `databaseFrom(orm, replica)` | Build a `Database` from an existing Drizzle instance + replica handle. |
10
+ | `Database` / `DisposableDatabase` / `QueryRunner` / `TxOf` | The `read` / `write` / `transaction` API and its supporting types. |
11
+ | `hyperdriveConnectionOptions(hyperdrive, overrides?)` / `HyperdriveLike` / `ExecutionContextLike` | Build mysql2 `createConnection` options from a Hyperdrive binding (`disableEval`, `decimalNumbers`, `timezone '+09:00'` by default). `timezone` controls mysql2's JavaScript `Date` conversion; it does not change the MySQL session timezone. |
12
+ | `withMysqlConnections(...)` | Open primary/replica connections in parallel and run a function. Workers cleans them up at invocation end. |
13
+ | `retryWhenDeadlock(fn, retries?, delay?)` | Same deadlock-retry helper as the root export. |
14
+ | `insertIdOf` / `affectedRowsOf` / `insertedIdsOf` / `DzWriteResult` | Extract `insertId` / `affectedRows` (and derive contiguous bulk-insert ids) from a mysql2 write result. |
15
+ | `toJstDate` / `jstTimestampParams` / `jstDatetimeParams` / `jstDateParams` | JST date/time normalization params (advanced use). |
16
+ | `MYSQL_TIMEZONE` | Default mysql2 connection `timezone` (`'+09:00'`) for the JST DB deployment. |
17
+ | `jstTimestamp` / `jstDatetime` / `jstDate` | Drizzle column helpers (no repo-side wrapper needed). |
18
+ | `jstOnUpdateNow` | SQL expression for `ON UPDATE CURRENT_TIMESTAMP`. The `jstTimestamp` customType (and friends) do not support `.onUpdateNow()`, so pair it with `.$onUpdateFn(() => jstOnUpdateNow(fsp))`. |
19
+ | `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. |
20
+ | `resolveDbSecret()` / `ResolvedDbSecret` | Resolve DB connection info from the `DB_SECRET` env var (an AWS RDS managed-secret JSON string) for CI migrate / local tooling. Returns `undefined` when `DB_SECRET` is unset; throws on invalid JSON or a missing required key. |
21
+ | `baselineMigrations(options)` / `readBaselineEntry(migrationsFolder)` / `BaselineMigrationsOptions` / `BaselineResult` / `BaselineEntry` | Brownfield first-deploy helper: mark an existing `0000_*` migration as applied without re-running DDL. |
22
+
23
+ ## Drizzle column helpers (`jstTimestamp`, etc.)
24
+
25
+ - `drizzle-orm` is a **peer** only. The kit does not include `drizzle-orm` as a dependency (even after publishing, it uses the consumer's single copy).
26
+ - The consumer just keeps `drizzle-orm` in its `dependencies` as usual. **No `overrides` in `package.json` are needed.**
27
+ - The npm-published artifact contains no `devDependencies`, so installing it does not add a kit-specific `drizzle-orm` (there is only the one peer copy).
28
+ - The column helpers `import` the consumer's `drizzle-orm` at runtime, and the types are the `customType` inference as-is (`MySqlCustomColumnBuilder<…>`). No `any` is used, so the column's semantic type propagates to the consumer table's `$inferSelect`.
29
+ - **Precondition: resolve drizzle to a single copy.** Drizzle's `SQL` is a **nominal** type carrying a private field `shouldInlineParams`, so if the kit and the consumer resolve different copies, `jstTimestamp(…).default(sql\`…\`)` fails the whole schema with `TS2345 separate declarations of a private property 'shouldInlineParams'`. Under `file:`-link development, `drizzle-orm` nests under the kit and becomes a second copy, so **pin `drizzle-orm` to the consumer's own single copy in `tsconfig.json`**:
30
+
31
+ ```jsonc
32
+ // tsconfig.json compilerOptions (merge with existing paths if any)
33
+ "paths": {
34
+ "drizzle-orm": ["./node_modules/drizzle-orm"],
35
+ "drizzle-orm/*": ["./node_modules/drizzle-orm/*"]
36
+ }
37
+ ```
38
+
39
+ With `moduleResolution: "Bundler"`, `baseUrl` is not required (if `baseUrl` is already set, drop the leading `./`). On the published package (a single copy) these `paths` are harmless. **No `overrides` needed.**
40
+ - When developing against the kit via a direct `file:` link, run `npm install` in the kit repo itself to satisfy its peers (do not add `overrides` on the consumer side).
41
+
42
+ ## `CURRENT_TIMESTAMP` vs the connection `timezone:'+09:00'`
43
+
44
+ | Path | Who decides the time | Relationship to JST |
45
+ | --- | --- | --- |
46
+ | The app binds a `Date` (INSERT/UPDATE) | mysql2 + connection `timezone:'+09:00'` | Treated as JST on the wire (`datetime-wire` test) |
47
+ | `DEFAULT CURRENT_TIMESTAMP` / `ON UPDATE CURRENT_TIMESTAMP` | The MySQL server (session `time_zone`) | A **separate path** from the connection option. JST if the RDS `time_zone` is `+09:00`, UTC if UTC |
48
+
49
+ `jstTimestamp` / `jstDatetime` only handle read/write pass-through and DATE normalization; they do not change the timezone of server-side defaults. For columns that need `ON UPDATE`, keep the DDL intent with `.$onUpdateFn(() => jstOnUpdateNow(6))`.
@@ -0,0 +1,67 @@
1
+ # API: `@rdlabo/workers-hono-kit/offline`
2
+
3
+ Table-agnostic building blocks for product-owned REST ↔ DB method converters and their offline replica wire values. This subpath does not define table projections, Zod object shapes, public-column allowlists, schema hashes, or domain rules; those remain in each Hono application.
4
+
5
+ This is an additive subpath: existing root and subpath exports are unchanged. Consumers can migrate converter internals independently without changing REST payloads, schema hashes, or persisted SQLite rows. For an `AUTO_INCREMENT` table, omit `id` from a create method's table scheme; keep the client-generated UUID in `local_id` and keep `server_id` null until the server confirms its id.
6
+
7
+ | Export | Description |
8
+ | --- | --- |
9
+ | `defineRestDbMethodConverter(converter)` | Type a product-owned, pure `MethodScheme ↔ TableScheme` converter without hiding HTTP or persistence side effects. |
10
+ | `RestDbMethodConverter` | Product-owned converter contract. Select and insert bundles may differ; every represented table and column remains required. |
11
+ | `CompleteRestDbTableScheme` | Compile-time lock requiring every represented table key and row column. |
12
+ | `toReplicaIsoDatetime(value)` | `Date` / datetime string → canonical UTC ISO-8601 wire value. |
13
+ | `toReplicaDateOnly(value)` | `Date` / date string / `null` → canonical `YYYY-MM-DD` / `null`. |
14
+ | `replicaTimestampMs(value)` | Replica datetime → epoch milliseconds for legacy DTOs. |
15
+ | `toTinyIntFlag(value)` / `fromTinyIntFlag(value)` | Boolean-like value ↔ numeric tinyint flag. |
16
+ | `replicaNowIso(clock?)` | Injectable wall clock → canonical UTC ISO-8601 wire value. |
17
+
18
+ ```ts
19
+ import {
20
+ defineRestDbMethodConverter,
21
+ replicaNowIso,
22
+ toReplicaIsoDatetime,
23
+ } from '@rdlabo/workers-hono-kit/offline';
24
+
25
+ type Tables = {
26
+ foods: FoodRow[];
27
+ allergens: AllergenRow[];
28
+ };
29
+
30
+ export const foodMethodConverter = defineRestDbMethodConverter<FoodMethodScheme, Tables>({
31
+ toMethodScheme: ({ foods, allergens }) => ({
32
+ ...foods[0],
33
+ allergens: allergens.map(({ value }) => value),
34
+ }),
35
+ toTableScheme: (method) => ({
36
+ foods: [{ id: method.id, memo: method.memo ?? null }],
37
+ allergens: method.allergens.map((value) => ({ threadId: method.id, value })),
38
+ }),
39
+ });
40
+ ```
41
+
42
+ `toTableScheme` requires every key represented by its DB row types. This includes nullable/default columns that Drizzle marks optional in `$inferInsert`; write `memo: method.memo ?? null` instead of omitting `memo`. If a REST method intentionally does not own an `AUTO_INCREMENT` column, remove it from that method's product-owned table scheme explicitly:
43
+
44
+ ```ts
45
+ type CreateTables = {
46
+ foods: Omit<typeof foods.$inferInsert, 'id'>[];
47
+ };
48
+ ```
49
+
50
+ The converter then cannot demand or manufacture `id`; the server adds the generated id to the confirmed response before it is stored as `server_id`.
51
+
52
+ When a write needs authenticated ownership or scope that is intentionally absent from the public REST body, use separate select/insert bundles and an explicit write context. The original two-generic form remains valid.
53
+
54
+ ```ts
55
+ defineRestDbMethodConverter<Method, SelectTables, InsertTables, { userId: number }>({
56
+ toMethodScheme: ({ foods, allergens }) => composeFood(foods, allergens),
57
+ toTableScheme: (method, { userId }) => ({
58
+ foods: [{ userId, name: method.name, memo: method.memo ?? null }],
59
+ allergens: method.allergens.map((value) => ({ value })),
60
+ }),
61
+ });
62
+ ```
63
+
64
+ ```ts
65
+ replicaNowIso(() => new Date('2026-07-23T10:00:00Z')); // '2026-07-23T10:00:00.000Z'
66
+ toReplicaIsoDatetime('2026-07-23T19:00:00+09:00'); // '2026-07-23T10:00:00.000Z'
67
+ ```
@@ -0,0 +1,71 @@
1
+ # API: `@rdlabo/workers-hono-kit`
2
+
3
+ The root export is web-standard only: it runs on `workerd` and never depends on Node.js APIs or `mysql2`. The table below lists the helpers exported from the root entry point.
4
+
5
+ | Export | Description |
6
+ | --- | --- |
7
+ | `finalizeResponse()` | Middleware that adds a weak `ETag` (delegates to `hono/etag`; also handles `If-None-Match` → `304`). |
8
+ | `validate(target, schema, options?)` | Zod validator → NestJS `ValidationPipe`-shaped `400` (`{ statusCode, message[], error }`). `options.onValidationError(err, c)` to report (e.g. Sentry). |
9
+ | `createValidate({ sentry? })` | Bound `validate` factory. Pass `sentry` on Sentry apps; omit for console-only (review, cbs-ai). |
10
+ | `createSentryValidate(sentry)` | **Deprecated** — use `createValidate({ sentry })`. |
11
+ | `zNum` / `zNumWithDefault` / `zNumOptional` / `zNumNullable` | Number-coercion zod schemas (mirror class-transformer `@Transform`). |
12
+ | `getAuthenticationSecret<T>(options, secretId)` / `AwsSecretsOptions` | Fetch a secret from AWS Secrets Manager (SigV4 `fetch`, per-isolate cache). |
13
+ | `getTemporaryCredentials(options)` / `GetTemporaryCredentialsOptions` / `StsCredentials` | STS `AssumeRole` via SigV4 `fetch` (global `sts.amazonaws.com`); returns temporary credentials for browser S3 uploads. |
14
+ | `getCloudFrontSignedUrl(url, privateKeyPem, keyPairId, dateLessThan)` | CloudFront signed URL (canned policy, RSA-SHA1, URL-safe base64) — Web Crypto reimpl of `@aws-sdk/cloudfront-signer`, byte-identical query order. |
15
+ | `JoseFirebaseVerifier` / `FirebaseVerifier` / `DecodedIdToken` | Firebase ID-token verification (`verifyIdToken`, `getUser`, `deleteUser`). |
16
+ | `createRemoteFirebaseVerifier(projectId)` | Convenience factory: production verifier with a cached remote JWKS (verification only). |
17
+ | `createServiceAccountVerifier(serviceAccountJson)` | Cached verifier built from a service-account JSON, **with `IdentityToolkit`** (getUser/deleteUser). One per isolate, re-created only when the SA JSON changes. |
18
+ | `IdentityToolkit` / `ServiceAccount` / `SECURETOKEN_JWK_URL` | Identity Toolkit REST client + constants for `getUser` / `deleteUser`. |
19
+ | `retryWhenDeadlock(fn, retries?, delay?)` | Retry on MySQL `ER_LOCK_DEADLOCK` with exponential backoff. |
20
+ | `getUserProtocol(c)` / `IUserProtocol` | Read client IP / UA (`CF-Connecting-IP` → `X-Forwarded-For`). |
21
+ | `getAppInfo(c)` / `AppInfo` | Read `x-amz-meta-version` / `x-amz-meta-uuid`. |
22
+ | `resolveAppEnv(env)` / `isProductionEnv(env)` / `AppEnv` | Resolve `'development'` / `'production'` from `env.APP_ENV` (defaults to `'production'` for safety). |
23
+ | `HttpStatus` | Standard HTTP status code enum (IANA registry). |
24
+ | `createHttpErrorHandler(options?)` / `HttpErrorHandlerOptions` | `app.onError()` handler that maps a thrown `HTTPException` to `{ statusCode, message, error? }` (`401` omits `error`). Optional custom error predicate and unhandled-error report hook. Unhandled errors log via `console.error` (mysql2 errors include `sqlMessage` / `errno` when detectable). |
25
+ | `createAppErrorHandler(options?)` / `CreateAppErrorHandlerOptions` | Standard `app.onError`: {@link createQueryFailedErrorHandler} + default {@link classifyGenericMysqlDriverError} + optional `sentry` (Sentry apps), `getReportError` / `reportError` (tests / container), or neither (no external reporting). |
26
+ | `createQueryFailedErrorHandler(options)` / `QueryFailedClassifier` / `ClassifiedDbError` | Lower-level compose when you need full control over `classify` + `onUnhandledError` without defaults. |
27
+ | `classifyGenericMysqlDriverError(err)` | Default classifier: any mysql2 driver error → `{ statusCode: 500, message: 'Internal server error' }`; non-DB errors → `null`. |
28
+ | `findMysqlDriverError(err)` / `logMysqlDriverError(err, statusCode)` | Low-level mysql2 driver-error detection (follows `err.cause`) and structured logging. For custom classifiers (e.g. odss). |
29
+ | `notFoundHandler(c)` | `app.notFound()` handler with `{ message: 'Cannot METHOD path', error, statusCode }` 404 body. |
30
+ | `normalizeTrailingSlash(request)` | Strip trailing slash(es) from the request URL before routing (Express/Nest parity). Does **not** 301-redirect — preserves POST/PUT/DELETE bodies. |
31
+ | `HTTP_ERROR_PHRASES` | `{ 400, 401, 403, 404 }` → standard `error` field phrases. |
32
+ | `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. |
33
+ | `createIdentityAuthFailureBody()` / `createLegacyIdentityAuthFailureBody()` / `createAuthFailureBody(scope, code, message)` / `AuthFailureScope` | Stable wire contract for distinguishing a lost global identity (`identity`) from recent-login (`reauthentication`) and feature credential (`credential`) failures. The legacy helper tags products whose installed clients still require auth failure as `403`. |
34
+ | `perfLog(options?)` / `PerfLogOptions` / `AnalyticsEngineDatasetLike` | Middleware that records one per-request latency data point (`t_app`, colo, cold/warm, route, status) and emits it to **Workers Logs** (`console.log`) and/or **Workers Analytics Engine** (`writeDataPoint`). Lets you measure low-traffic Workers without a live `wrangler tail`. |
35
+ | `createMaintenanceMiddleware(options)` / `createMaintenanceWaitHandler(options)` / `isMaintenanceEnabled(env)` / `MAINTENANCE_CODE` / `MAINTENANCE_WAIT_PATH` | Fleet maintenance short-circuit: when enabled (`MAINTENANCE=1`), every non-allowlisted request returns `503` + `{ statusCode, message, code: 'MAINTENANCE' }` **before** container/DB. Pair with `GET /public/maintenance/wait` SSE (`event: ping` / `event: ended`) so clients can auto-dismiss a lock UI. Mount after `cors`, before `containerMiddleware`. |
36
+ | `ErrorReporter` / `ErrorReportContext` | Types for a `reportError`-style unhandled-error reporter (e.g. wired to Sentry), paired with `createHttpErrorHandler`'s `onUnhandledError`. |
37
+ | `createSentryErrorReporter(sentry)` / `SentryExceptionReporterLike` | Build an `ErrorReporter` that forwards to Sentry with an optional `request_id` tag (no hard `@sentry/cloudflare` dependency). |
38
+ | `DeferExecutor` / `defaultDefer` / `createWaitUntilDefer(ctx)` | Fire-and-forget executor for Workers: both variants log background rejections without propagating them; `createWaitUntilDefer` also registers work via `ctx.waitUntil`. |
39
+ | `configureHibernationAutoResponse` / `upgradeHibernationWebSocket` / `broadcastHibernationWebSockets` | Hibernation WebSocket room primitives: runtime ping/pong without waking JavaScript, attachment-before-accept upgrade, and broadcast through sockets restored by `getWebSockets()`. |
40
+ | `acknowledgeHibernationWebSocketClose` / `closeHibernationWebSocket` | Safe close helpers, including normalization of reserved received-only close codes. |
41
+ | `retryDurableObjectOperation(operation, options?)` / `isRetryableDurableObjectError(error)` | Retry idempotent DO work only for `retryable && !overloaded`, with jittered exponential backoff. `operation` runs per attempt so callers create a fresh stub after an exception. |
42
+ | `createIdempotencyInput(...)` / `runIdempotentMutation(...)` | Canonical payload hashing and a transaction-bound mutation state machine. Missing keys preserve legacy behavior; replay/conflict/in-flight semantics are shared while each app owns its schema and ORM adapter. |
43
+ | `withIdempotencyHttpErrors(run)` | Maps only standard idempotency failures to 400/409/503 and rethrows unrelated failures. |
44
+ | `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`). |
45
+ | `KVCache` / `KVNamespace` / `KVCacheOptions` / `KVCacheErrorContext` / `KVCacheOperation` | Workers-KV cache-aside helper (key `appName+version+table_type_column`, sha256 for string ids, TTL clamped ≥60s). Set `appName` / `version` per application; optional `onError(error, context)` observes fail-soft read/parse/serialize/write/delete failures. Context contains only the operation and logical table, not cache types, keys, ids, or values. |
46
+ | `createStripeClient(secret, opts?)` / `verifyStripeWebhook(...)` / `CreateStripeClientOptions` | Workers-native Stripe client (fetch transport) + async webhook verification (SubtleCrypto). `apiVersion` optional (pin to a fixed Stripe API version). |
47
+ | `extractStripeFailureReason(source)` / `StripeFailureReason` | Duck-type a Stripe `PaymentIntent` / `Invoice` / `{ paymentIntent?, invoice? }` / thrown error into a normalized `{ code, declineCode, message, paymentIntentId, invoiceId, subscriptionId }` (SDK-free), or `null`. |
48
+ | `stripeFailureMessageJa(reason)` | Render a `StripeFailureReason` (or `null`) as a single user-facing Japanese sentence (`decline_code` > `code`; fraud codes masked; unknown → generic). |
49
+ | `PaymentDeclinedError` / `toPaymentDeclinedError(error, status?)` / `PaymentDeclinedBody` | `HTTPException` carrying a verbatim `{ statusCode, message, code?, declineCode? }` body for a synchronous card decline (defaults to `400`). `toPaymentDeclinedError` returns `null` for non-declines (re-throw → 500). |
50
+ | `classifyStripeReconcile(subscription)` / `StripeReconcileAction` | Classify an expanded Stripe subscription into `trial` / `clear` / `canceled` / `failed` / `action_required` / `none` (termination evaluated before `succeeded`). Consumer does the DB write. |
51
+ | `serializePaymentFailure(record)` / `parsePaymentFailure(receipt)` / `PaymentFailureRecord` / `PaymentFailureReason` / `PaymentFailureSource` | (De)serialize the `payment_failed.receipt` JSON. `parsePaymentFailure` restores both a full Stripe record and a bare IAP reason. |
52
+ | `serializeIapFailureReason(reason)` / `IapFailureReason` | Serialize an IAP reason (`billing_retry` / `auto_renew_off` / `subscription_canceled` / `subscription_gone` + provider codes) directly, without the source/timestamp wrapper. |
53
+ | `paymentFailureMessageJa(input)` / `PaymentFailureStatus` / `PaymentFailureType` / `UNRESOLVED_PAYMENT_STATUSES` | Provider-agnostic Japanese message for a `payment_failed` row (`canceled` re-subscribe prompt, IAP `failed` App Store/Google Play prompt, else Stripe wording). `UNRESOLVED_PAYMENT_STATUSES` = everything except `resolved` for read/resolve `WHERE`. |
54
+ | `iapFailureKey(input)` | Provider-native `payment_failed.recursions_id`: iOS `${original_transaction_id}:${expires_date_ms}`, Android `${orderId}` (provider is in the `type` column). |
55
+ | `verifyAppleReceipt(receipt, opts)` / `classifyAppleRenewal(verify, now)` / `AppleRenewalClassification` / `AppleRenewalState` / `AppleVerifyReceiptResponse` / `ApplePendingRenewalInfo` / `AppleLatestReceiptInfo` | Verify an App Store receipt (production → sandbox fallback; inject `password` / `fetchImpl`) and classify it into `billing_retry` / `lapsed` / `active` / `unknown` plus the raw fields used (`statusCode` / `billingRetryStatus` / `autoRenewStatus`, latest `original_transaction_id` / `expires_date_ms`). |
56
+ | `googleAccessToken(creds, fetch?)` / `getGoogleSubscription(opts)` / `classifyGoogleSubscription(purchase, now)` / `GoogleSubscriptionClassification` / `GoogleSubscriptionState` / `GoogleSubscriptionPurchase` / `GoogleOAuthCredentials` | Exchange a refresh token for an Android Publisher access token (throws on `invalid_grant`), fetch a subscription purchase, and classify it into `canceled` / `gone` / `active` / `unknown` plus raw `statusCode` / `cancelReason`. |
57
+ | `sendInChunks(queue, messages, options?)` / `QueueLike` / `QueueSendMessage` | Send queue messages in bounded chunks to stay under the Workers subrequest cap per invocation. `options.chunkSize` sets the per-batch size (defaults to and is capped at 100). |
58
+ | `processBatch(batch, handler, options?)` / `isNonRetryableQueueError(error)` / `NonRetryableQueueErrorLike` / `MessageBatchLike` / `QueueMessageLike` / `ProcessBatchOptions` / `ProcessBatchResult` | Process a queue batch with bounded concurrency. Errors explicitly tagged with `queueDisposition: 'discard'` are reported and acked as permanent failures; all other errors are retried. |
59
+ | `createQueueErrorHandler(options)` / `CreateQueueErrorHandlerOptions` | Factory for `processBatch`'s `onError`: logs every failure; optional Sentry capture with queue/message context; optional `maxRetries` gate (report only on final attempt, except permanent failures which are reported immediately). |
60
+ | `assertStripeCustomerUpdated(options)` | Preserve the shared Stripe UPDATE→existence-check algorithm. `createNotFoundError(customerId)` can supply a domain-specific error without forking the algorithm. |
61
+ | `ExecutionContextLike` | Minimal `waitUntil`-only Workers execution context shape used by lifecycle-compatible APIs and deferred work helpers. |
62
+
63
+ Permanent Queue failures must opt in with the Queue-specific marker; unrelated `retryable` fields are ignored:
64
+
65
+ ```ts
66
+ import type { NonRetryableQueueErrorLike } from '@rdlabo/workers-hono-kit';
67
+
68
+ class CustomerLinkMissingError extends Error implements NonRetryableQueueErrorLike {
69
+ readonly queueDisposition = 'discard' as const;
70
+ }
71
+ ```
@@ -0,0 +1,16 @@
1
+ # API: `@rdlabo/workers-hono-kit/testing`
2
+
3
+ Requires the `drizzle-orm` and `mysql2` peers. Consolidates duplicated test boilerplate.
4
+
5
+ | Export | Description |
6
+ | --- | --- |
7
+ | `createTestDb(options)` / `TestDb` / `CreateTestDbOptions` / `TestDbConnection` | Test database built from committed Drizzle migrations as the single source of truth: `resetSchema` / `createTestPool` / `truncateAll` / `seed` / `mysqlReachable`. |
8
+ | `FakeFirebaseVerifier` | In-memory `FirebaseVerifier` for offline route tests (`register` / `verifyIdToken` / `getUser` / `deleteUser`). |
9
+ | `createPoolDatabase(options)` / `CreatePoolDatabaseOptions` | A `Database` backed by a single pool used as both primary and replica. |
10
+ | `createNoopDatabase()` | A `Database` stub that throws on `write` / `transaction` to catch accidental DB use in DB-less routes. |
11
+ | `authHeaders(token, opts?)` | Build interceptor-compatible auth headers for requests. |
12
+ | `registerFirebaseToken(firebase, uid, record?, token?)` | Register a token in a `FakeFirebaseVerifier` (no DB). |
13
+ | `provisionUser(pool, firebase, opts)` | Register a token and provision a conventional `users(id, firebase_uid, agree)` row; returns the user id (idempotent). |
14
+ | `configurableFake(impl, name?)` | Build a test double from a partial implementation; un-stubbed members throw `"${name}.${method} not configured"`. |
15
+ | `fakeApiList` / `fakePaymentIntent` / `fakeStripeEvent` / `fakeCheckoutSession` / `fakeCustomer` / `fakePrice` / `fakeSubscription` | Stripe object fixtures with sensible defaults, overridable per test. |
16
+ | `fakeKv()` / `fakeQueue()` / `FakeQueue` | In-memory Workers KV / Queues producer doubles (`sent` + `batchCount` on queues for subrequest-bound assertions). |
package/docs/api.md ADDED
@@ -0,0 +1,12 @@
1
+ # API
2
+
3
+ `@rdlabo/workers-hono-kit` exposes these entry points. This page maps each entry point to its dedicated reference page. For feature-level examples, see [HTTP and Authentication](./http-auth.md), [Data Layer](./data-layer.md), [Realtime and Offline](./realtime-offline.md), and [Testing and Operations](./testing-operations.md).
4
+
5
+ | Entry point | Description | Reference |
6
+ | --- | --- | --- |
7
+ | `@rdlabo/workers-hono-kit` | Web-standard helpers (middleware, HTTP, Firebase, AWS, AI, Stripe, KV, queues, idempotency). | [Root](./api-root.md) |
8
+ | `@rdlabo/workers-hono-kit/db` | MySQL data layer (mysql2 + Drizzle), JST column helpers, baseline migrations. | [DB](./api-db.md) |
9
+ | `@rdlabo/workers-hono-kit/business-time` | JST business calendar and date-time conversions. | [Business time](./api-business-time.md) |
10
+ | `@rdlabo/workers-hono-kit/offline` | Table-agnostic REST/DB method converters and replica wire helpers. | [Offline](./api-offline.md) |
11
+ | `@rdlabo/workers-hono-kit/realtime` | Durable Object WebSocket and retry helpers. | [Realtime and Offline](./realtime-offline.md) |
12
+ | `@rdlabo/workers-hono-kit/testing` | Drizzle-backed test DB, fakes, fixtures, and binding doubles. | [Testing](./api-testing.md) |
package/docs/cli.md ADDED
@@ -0,0 +1,33 @@
1
+ # CLI
2
+
3
+ The package ships `bin` commands that can be run with `npx` or wired into npm scripts in the consuming app. They are operational helpers: AWS credential sync, subrequest fan-out gating, and brownfield database baselining.
4
+
5
+ | Command | Use |
6
+ | --- | --- |
7
+ | `workers-hono-kit-sync-dev-aws <wrangler-args…>` | Launch `wrangler` with AWS credentials injected as `--var`, resolved from the active AWS profile (honors `AWS_PROFILE`, supports short-lived SSO/temporary creds). Nothing is written to disk — replaces `.dev.vars`. Wire it as the `dev` script, e.g. `AWS_PROFILE=<p> workers-hono-kit-sync-dev-aws dev --var APP_ENV:development`. |
8
+ | `workers-hono-kit-check-subrequest-fanout [dir…]` | CI gate that greps for per-item external-call fan-outs (`runWithConcurrency(` / `PromisePool` / `.withConcurrency(`) that would eventually exceed the Workers subrequest cap. Annotate a genuinely-safe site with `subrequest-ok`. Scans `src` by default; exits 1 on an un-annotated marker. |
9
+ | `workers-hono-kit-db-baseline [--migrations ./drizzle]` | Brownfield first-deploy helper: record the baseline `0000` migration as *already applied* on an existing MySQL DB without running its DDL (the CLI wrapper around `baselineMigrations` / `readBaselineEntry`). Reads DB credentials from `DB_SECRET` (AWS RDS managed secret) or the individual `DB_*` env vars. |
10
+
11
+ ## `workers-hono-kit-sync-dev-aws`
12
+
13
+ Use this in the `dev` npm script when you want AWS credentials from the active profile to be available inside `wrangler dev` without committing them to `.dev.vars`. It resolves short-lived SSO or temporary credentials and passes them as `--var` arguments. Nothing is written to disk.
14
+
15
+ ```bash
16
+ AWS_PROFILE=my-sso-profile workers-hono-kit-sync-dev-aws dev --var APP_ENV:development
17
+ ```
18
+
19
+ ## `workers-hono-kit-check-subrequest-fanout`
20
+
21
+ Run this in CI to catch per-item external call patterns (for example `runWithConcurrency`, `PromisePool`, or `.withConcurrency`) that could fan out beyond the Workers subrequest cap. If a call site is safe, annotate it with `subrequest-ok`. The command scans `src` by default and exits with `1` if it finds an un-annotated marker.
22
+
23
+ ```bash
24
+ workers-hono-kit-check-subrequest-fanout src
25
+ ```
26
+
27
+ ## `workers-hono-kit-db-baseline`
28
+
29
+ Use this for a brownfield first deploy against a MySQL database that already matches the schema in your first migration (`0000_*`). It records that migration as already applied without running its DDL, so later migrations can apply normally. Database credentials are read from `DB_SECRET` (an AWS RDS managed-secret JSON string) or from individual `DB_*` environment variables.
30
+
31
+ ```bash
32
+ workers-hono-kit-db-baseline --migrations ./drizzle
33
+ ```
@@ -0,0 +1,44 @@
1
+ Import database helpers from `@rdlabo/workers-hono-kit/db`. This entry point requires `drizzle-orm` and `mysql2`.
2
+
3
+ ## Hyperdrive database
4
+
5
+ `createHyperdriveDatabase()` lazily opens primary and replica connections from Hyperdrive bindings. Reads use the replica query runner; writes and transactions use the primary Drizzle instance. After a fatal mysql2 connection error, a replica read opens a fresh connection and repeats the SELECT at most once. Writes and transactions are not repeated because their commit state may be ambiguous. Workers owns connection cleanup at invocation end.
6
+
7
+ ```ts
8
+ import { createHyperdriveDatabase } from '@rdlabo/workers-hono-kit/db';
9
+ import { drizzle } from 'drizzle-orm/mysql2';
10
+
11
+ const db = createHyperdriveDatabase({
12
+ primaryHyperdrive: env.DB_PRIMARY,
13
+ replicaHyperdrive: env.DB_REPLICA,
14
+ createOrm: (primary) => drizzle(primary, { schema }),
15
+ });
16
+
17
+ const rows = await db.read<Item>('SELECT * FROM items WHERE id = ?', [id]);
18
+ await db.write((dz) => dz.insert(items).values(input));
19
+ await db.transaction((tx) => tx.insert(items).values(input));
20
+ ```
21
+
22
+ Use `hyperdriveConnectionOptions()` when constructing lower-level mysql2 connections. The default JavaScript date conversion timezone is `+09:00`; it does not change the MySQL session timezone.
23
+
24
+ ## Writes and retries
25
+
26
+ - `retryWhenDeadlock()` retries `ER_LOCK_DEADLOCK` with exponential backoff.
27
+ - `insertIdOf()`, `affectedRowsOf()`, and `insertedIdsOf()` normalize mysql2 write results.
28
+ - `withMysqlConnections()` opens primary and replica connections in parallel for a scoped operation.
29
+
30
+ ## Drizzle and JST helpers
31
+
32
+ Use `jstTimestamp`, `jstDatetime`, and `jstDate` for shared date behavior. Pair update timestamps with `jstOnUpdateNow()` because custom timestamp types do not expose Drizzle's `.onUpdateNow()`. For decimal columns, use Drizzle's `decimal(name, { precision, scale, mode: 'number' })` directly.
33
+
34
+ The `/business-time` entry point converts instants and business dates in the JST business timezone:
35
+
36
+ ```ts
37
+ import { addBusinessDays, toBusinessDateTime } from '@rdlabo/workers-hono-kit/business-time';
38
+
39
+ toBusinessDateTime(new Date('2026-07-05T21:00:00Z'));
40
+ // '2026-07-06 06:00:00'
41
+
42
+ addBusinessDays('2026-07-06', 3);
43
+ // '2026-07-09'
44
+ ```
@@ -0,0 +1,32 @@
1
+ # Development
2
+
3
+ These commands are used when working on the package itself:
4
+
5
+ ```bash
6
+ npm install
7
+ npm run typecheck # tsc --noEmit
8
+ npm run lint # eslint
9
+ npm test # vitest
10
+ npm run build # tsc -p tsconfig.build.json → dist/
11
+ ```
12
+
13
+ ## Local development / linking
14
+
15
+ If you consume this package via a local path (e.g. `"@rdlabo/workers-hono-kit": "../../hono-kit"`) rather than from npm, TypeScript and esbuild resolve the package's bare imports from *its own* `node_modules`, which can create a second `zod` instance. That breaks types where your zod-inferred values flow into other libraries (e.g. Drizzle inserts). Dedupe with tsconfig `paths`:
16
+
17
+ ```jsonc
18
+ {
19
+ "compilerOptions": {
20
+ "baseUrl": ".",
21
+ "paths": {
22
+ "zod": ["node_modules/zod"],
23
+ "zod/*": ["node_modules/zod/*"],
24
+ "@hono/zod-validator": ["node_modules/@hono/zod-validator"]
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ When installed from npm normally, package managers dedupe `zod` to a single copy and this is not needed.
31
+
32
+ When developing against the kit via a direct `file:` link, run `npm install` in the kit repo itself to satisfy its peers (do not add `overrides` on the consumer side).
@@ -0,0 +1,36 @@
1
+ ## Validation
2
+
3
+ `validate(target, schema, options?)` adapts a Zod schema to Hono and returns a NestJS `ValidationPipe`-shaped `400` response. Use `createValidate({ sentry })` to bind optional reporting once.
4
+
5
+ ```ts
6
+ import { createValidate, zNumOptional } from '@rdlabo/workers-hono-kit';
7
+ import { z } from 'zod';
8
+
9
+ const validate = createValidate({ sentry });
10
+ const querySchema = z.object({ page: zNumOptional() });
11
+
12
+ app.get('/items', validate('query', querySchema), async (c) => {
13
+ const query = c.req.valid('query');
14
+ return c.json(await listItems(query.page));
15
+ });
16
+ ```
17
+
18
+ ## Authentication
19
+
20
+ `createAuthMiddleware()` reads a token header, verifies a Firebase ID token, optionally resolves the application user ID, and stores the result on the Hono context. Use `createRemoteFirebaseVerifier(projectId)` for cached remote JWKS verification or `createServiceAccountVerifier()` when Identity Toolkit `getUser` and `deleteUser` operations are required.
21
+
22
+ Keep identity, reauthentication, and feature credential failures distinct with the stable auth-failure body helpers.
23
+
24
+ ## Error and routing contracts
25
+
26
+ - `createAppErrorHandler()` composes query failure classification, generic mysql2 classification, and optional reporting.
27
+ - `createHttpErrorHandler()` maps `HTTPException` to the shared JSON error body.
28
+ - `notFoundHandler()` returns `Cannot METHOD path` with a 404 status.
29
+ - `normalizeTrailingSlash()` removes trailing slashes without redirecting, preserving request bodies.
30
+ - `finalizeResponse()` adds weak ETags and handles matching `If-None-Match` requests.
31
+
32
+ Mount `createMaintenanceMiddleware()` after CORS and before container or database middleware so maintenance responses do not initialize expensive infrastructure.
33
+
34
+ ## Deferred work and observability
35
+
36
+ `createWaitUntilDefer(ctx)` registers background work through `waitUntil` and logs rejected work. `perfLog()` emits per-request application latency, colo, cold/warm state, route, and status to Workers Logs and optionally Analytics Engine.
@@ -0,0 +1,27 @@
1
+ ## Durable Object realtime
2
+
3
+ The root and `/realtime` entry points expose the same focused realtime primitives:
4
+
5
+ - `configureHibernationAutoResponse()` configures runtime ping/pong without waking JavaScript.
6
+ - `upgradeHibernationWebSocket()` attaches state before accepting the socket.
7
+ - `broadcastHibernationWebSockets()` broadcasts through sockets restored by `getWebSockets()`.
8
+ - `acknowledgeHibernationWebSocketClose()` and `closeHibernationWebSocket()` normalize close handling.
9
+ - `retryDurableObjectOperation()` retries only errors marked `retryable` and not `overloaded`. Create a fresh stub inside the operation for every attempt.
10
+ - `invokeDurableObjectFetch()` preserves the structured response/error contract for DO calls.
11
+
12
+ WebSocket protocol parsers validate offered subprotocols before upgrade.
13
+
14
+ ## Offline replica contracts
15
+
16
+ `@rdlabo/workers-hono-kit/offline` is table-agnostic. Product schemas, Zod objects, public-column allowlists, schema hashes, and domain policy stay in the application.
17
+
18
+ `defineRestDbMethodConverter()` types a pure REST method ↔ table converter. Every represented table and column is required, including nullable/default columns. Omit an auto-increment `id` from the product-owned table scheme when a create method intentionally does not own it.
19
+
20
+ Wire helpers canonicalize values:
21
+
22
+ - `toReplicaIsoDatetime()` → UTC ISO-8601
23
+ - `toReplicaDateOnly()` → `YYYY-MM-DD` or `null`
24
+ - `toTinyIntFlag()` / `fromTinyIntFlag()` → boolean/tinyint conversion
25
+ - `replicaNowIso(clock?)` → injectable current time
26
+
27
+ Journal helpers enforce cursor coverage, retention, mutation transactions, and rebaseline behavior. Wire compatibility helpers let an application accept explicit previous fingerprints while maintaining a canonical current fingerprint.