@rdlabo/workers-hono-kit 0.9.3 → 0.9.5

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
@@ -210,7 +210,8 @@ client-generated UUID in `local_id` and keep `server_id` null until the server c
210
210
  | Export | Description |
211
211
  | --- | --- |
212
212
  | `defineRestDbMethodConverter(converter)` | Type a product-owned, pure `MethodScheme ↔ TableScheme` converter without hiding HTTP or persistence side effects. |
213
- | `RestDbMethodConverter` | Product-owned converter contract. Its table scheme requires every represented table and column, including optional nullable/default keys from `$inferInsert`. |
213
+ | `RestDbMethodConverter` | Product-owned converter contract. Select and insert bundles may differ; every represented table and column remains required. |
214
+ | `CompleteRestDbTableScheme` | Compile-time lock requiring every represented table key and row column. |
214
215
  | `toReplicaIsoDatetime(value)` | `Date` / datetime string → canonical UTC ISO-8601 wire value. |
215
216
  | `toReplicaDateOnly(value)` | `Date` / date string / `null` → canonical `YYYY-MM-DD` / `null`. |
216
217
  | `replicaTimestampMs(value)` | Replica datetime → epoch milliseconds for legacy DTOs. |
@@ -255,6 +256,20 @@ type CreateTables = {
255
256
  The converter then cannot demand or manufacture `id`; the server adds the generated id to the
256
257
  confirmed response before it is stored as `server_id`.
257
258
 
259
+ When a write needs authenticated ownership or scope that is intentionally absent from the public
260
+ REST body, use separate select/insert bundles and an explicit write context. The original
261
+ two-generic form remains valid.
262
+
263
+ ```ts
264
+ defineRestDbMethodConverter<Method, SelectTables, InsertTables, { userId: number }>({
265
+ toMethodScheme: ({ foods, allergens }) => composeFood(foods, allergens),
266
+ toTableScheme: (method, { userId }) => ({
267
+ foods: [{ userId, name: method.name, memo: method.memo ?? null }],
268
+ allergens: method.allergens.map((value) => ({ value })),
269
+ }),
270
+ });
271
+ ```
272
+
258
273
  ```ts
259
274
  replicaNowIso(() => new Date('2026-07-23T10:00:00Z')); // '2026-07-23T10:00:00.000Z'
260
275
  toReplicaIsoDatetime('2026-07-23T19:00:00+09:00'); // '2026-07-23T10:00:00.000Z'
@@ -31,6 +31,8 @@ export interface PerfLogOptions {
31
31
  * When provided, write one data point per request to a **Workers Analytics Engine** dataset. Query
32
32
  * percentiles by route/colo with the SQL API (≈90-day retention). Non-blocking. Layout:
33
33
  * `doubles = [t_app_ms, cold(0|1), status]`, `blobs = [path, colo, method]`, `indexes = [path]`.
34
+ * Route patterns longer than Analytics Engine's 96-byte index limit use a stable hash as the index;
35
+ * the complete route remains available in `blob1`.
34
36
  */
35
37
  dataset?: AnalyticsEngineDatasetLike;
36
38
  /**
@@ -18,6 +18,20 @@
18
18
  // a cold start are labelled warm (only the very first flips the flag) even though they pay cold-init
19
19
  // waits — a minor warm-side contamination, negligible at the low request rates this targets.
20
20
  let isolateWarm = false;
21
+ const ANALYTICS_INDEX_MAX_BYTES = 96;
22
+ function analyticsIndex(path) {
23
+ const bytes = new TextEncoder().encode(path);
24
+ if (bytes.byteLength <= ANALYTICS_INDEX_MAX_BYTES) {
25
+ return path;
26
+ }
27
+ // FNV-1a 64-bit keeps sampling deterministic without adding async crypto work to every response.
28
+ let hash = 0xcbf29ce484222325n;
29
+ for (const byte of bytes) {
30
+ hash ^= BigInt(byte);
31
+ hash = BigInt.asUintN(64, hash * 0x100000001b3n);
32
+ }
33
+ return `route:${hash.toString(16).padStart(16, '0')}`;
34
+ }
21
35
  /**
22
36
  * Create a Hono middleware that records a per-request latency data point and emits it to Workers
23
37
  * Logs (`console`) and/or Workers Analytics Engine (`dataset`).
@@ -84,11 +98,17 @@ export function perfLog(options = {}) {
84
98
  // In-code sampling thins Analytics Engine writes only; Workers Logs volume is controlled separately
85
99
  // by the observability `head_sampling_rate`. Low-traffic Workers should leave `sampleRate` at 1.
86
100
  if (sink && (rate >= 1 || Math.random() < rate)) {
87
- sink.writeDataPoint({
88
- doubles: [tApp, cold ? 1 : 0, status],
89
- blobs: [path, colo, method],
90
- indexes: [path],
91
- });
101
+ try {
102
+ sink.writeDataPoint({
103
+ doubles: [tApp, cold ? 1 : 0, status],
104
+ blobs: [path, colo, method],
105
+ indexes: [analyticsIndex(path)],
106
+ });
107
+ }
108
+ catch (error) {
109
+ // Telemetry must never replace an otherwise successful application response with a 500.
110
+ console.warn('[perfLog] Analytics Engine write failed', error);
111
+ }
92
112
  }
93
113
  if (emitConsole) {
94
114
  console.log(JSON.stringify({ perf: { cold, colo, method, path, status, t_app: tApp } }));
@@ -9,6 +9,6 @@
9
9
  export { fromTinyIntFlag, replicaTimestampMs, toReplicaDateOnly, toReplicaIsoDatetime, toTinyIntFlag } from './wire.js';
10
10
  export { replicaNowIso } from './clock.js';
11
11
  export { defineRestDbMethodConverter } from './rest-db-method-converter.js';
12
- export type { RestDbMethodConverter } from './rest-db-method-converter.js';
12
+ export type { CompleteRestDbTableScheme, RestDbMethodConverter } from './rest-db-method-converter.js';
13
13
  export { decodeOfflineSnapshotCursor, encodeOfflineSnapshotCursor } from './snapshot-cursor.js';
14
14
  export type { OfflineSnapshotCursor } from './snapshot-cursor.js';
@@ -17,7 +17,7 @@ type CompleteDbTableValue<TValue> = TValue extends (infer TRow)[] ? TRow extends
17
17
  * intentionally does not own a generated column must exclude it from its
18
18
  * product-owned scheme first, for example `Omit<InsertRow, 'id'>`.
19
19
  */
20
- type CompleteRestDbTableScheme<TTableScheme extends object> = {
20
+ export type CompleteRestDbTableScheme<TTableScheme extends object> = {
21
21
  [TTableName in keyof TTableScheme]-?: CompleteDbTableValue<TTableScheme[TTableName]>;
22
22
  };
23
23
  /**
@@ -28,9 +28,9 @@ type CompleteRestDbTableScheme<TTableScheme extends object> = {
28
28
  * `$inferInsert` type marks them optional. Nullability does not make a column
29
29
  * optional in the conversion contract.
30
30
  */
31
- export interface RestDbMethodConverter<TMethodScheme, TTableScheme extends object> {
32
- toMethodScheme(tableScheme: Readonly<CompleteRestDbTableScheme<TTableScheme>>): TMethodScheme;
33
- toTableScheme(methodScheme: Readonly<TMethodScheme>): CompleteRestDbTableScheme<TTableScheme>;
31
+ export interface RestDbMethodConverter<TMethodScheme, TSelectTableScheme extends object, TInsertTableScheme extends object = TSelectTableScheme, TWriteContext = never> {
32
+ toMethodScheme(tableScheme: Readonly<CompleteRestDbTableScheme<TSelectTableScheme>>): TMethodScheme;
33
+ toTableScheme(methodScheme: Readonly<TMethodScheme>, ...context: [TWriteContext] extends [never] ? [] : [context: Readonly<TWriteContext>]): CompleteRestDbTableScheme<TInsertTableScheme>;
34
34
  }
35
35
  /**
36
36
  * Define a product-specific REST ↔ DB converter with contextual return types.
@@ -38,5 +38,5 @@ export interface RestDbMethodConverter<TMethodScheme, TTableScheme extends objec
38
38
  * This is intentionally an identity function: conversion remains explicit,
39
39
  * synchronous, and free of hidden persistence or HTTP side effects.
40
40
  */
41
- export declare function defineRestDbMethodConverter<TMethodScheme, TTableScheme extends object>(converter: RestDbMethodConverter<TMethodScheme, TTableScheme>): RestDbMethodConverter<TMethodScheme, TTableScheme>;
41
+ export declare function defineRestDbMethodConverter<TMethodScheme, TSelectTableScheme extends object, TInsertTableScheme extends object = TSelectTableScheme, TWriteContext = never>(converter: RestDbMethodConverter<TMethodScheme, TSelectTableScheme, TInsertTableScheme, TWriteContext>): RestDbMethodConverter<TMethodScheme, TSelectTableScheme, TInsertTableScheme, TWriteContext>;
42
42
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rdlabo/workers-hono-kit",
3
- "version": "0.9.3",
3
+ "version": "0.9.5",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"