hono-utils 0.4.0 → 0.5.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.
package/dist/index.d.cts CHANGED
@@ -4,6 +4,7 @@ import { Logger, Details } from 'hierarchical-area-logger';
4
4
  import * as hono_utils_http_status from 'hono/utils/http-status';
5
5
  import { ContentfulStatusCode, SuccessStatusCode, ClientErrorStatusCode, StatusCode } from 'hono/utils/http-status';
6
6
  import z$1, { z, ZodObject } from 'zod';
7
+ import * as _cloudflare_workers_types from '@cloudflare/workers-types';
7
8
  import { Message, MessageBatch, Queue, Iso3166Alpha2Code, ContinentCode } from '@cloudflare/workers-types';
8
9
  import * as hono_utils_types from 'hono/utils/types';
9
10
  import { HTTPException } from 'hono/http-exception';
@@ -221,7 +222,7 @@ declare class QueueHandler<Schema extends ZodObject<any>, Environment, Context>
221
222
  * @param params - Global parameters to include in every message (e.g., trace IDs).
222
223
  * @returns A producer function that accepts a `handler` key and the corresponding typed content.
223
224
  */
224
- getProducer(queue: Queue<unknown>, params: QueueSendParams): <HandlerName extends keyof z.infer<Schema>>(handler: HandlerName, content: z.infer<Schema>[HandlerName]) => Promise<void>;
225
+ getProducer(queue: Queue<unknown>, params: QueueSendParams): <HandlerName extends keyof z.infer<Schema>>(handler: HandlerName, content: z.infer<Schema>[HandlerName]) => Promise<_cloudflare_workers_types.QueueSendResponse>;
225
226
  }
226
227
 
227
228
  /**
@@ -410,7 +411,10 @@ declare function verify(input: string, salt: string, storedHash: string, iterati
410
411
 
411
412
  declare const pbkdf2_verify: typeof verify;
412
413
  declare namespace pbkdf2 {
413
- export { hash$1 as hash, pbkdf2_verify as verify };
414
+ export {
415
+ hash$1 as hash,
416
+ pbkdf2_verify as verify,
417
+ };
414
418
  }
415
419
 
416
420
  /**
@@ -434,7 +438,10 @@ declare function hash({ input, algorithm, pepper, salt, }: {
434
438
  declare const sha_generateSalt: typeof generateSalt;
435
439
  declare const sha_hash: typeof hash;
436
440
  declare namespace sha {
437
- export { sha_generateSalt as generateSalt, sha_hash as hash };
441
+ export {
442
+ sha_generateSalt as generateSalt,
443
+ sha_hash as hash,
444
+ };
438
445
  }
439
446
 
440
447
  declare const onError: <Environment extends Env>(parseError?: (err: Error | HTTPException, env: Environment["Bindings"], get: <K extends keyof Environment["Variables"]>(key: K) => Environment["Variables"][K]) => Promise<string>) => ErrorHandler<Environment>;
@@ -456,4 +463,5 @@ interface CreateTypedClientOptions {
456
463
  }
457
464
  declare const createTypedClient: <TApp extends Hono<any, any, any>>() => (options: CreateTypedClientOptions) => <TSuccessData>(fn: (c: ReturnType<typeof hc<TApp>>) => Promise<ClientResponse<TSuccessData>>, callbacks?: TypedClientCallbacks) => Promise<TSuccessData>;
458
465
 
459
- export { type ContextFn, type CreateTypedClientOptions, type HonoClientInfoVariables, type HonoI18nVariables, type HonoIsBotVariables, type HonoLanguageVariables, type HonoLoggerVariables, type HonoResponseVariables, type MessageHandlers, type MiddlewareWithLoggingCapability, pbkdf2 as PBKDF2, QueueHandler, sha as SHA, type TypedClientCallbacks, clientInfo, createTypedClient, i18n, isBot, jsonValidator, logger, onError, onNotFound, queue, response };
466
+ export { pbkdf2 as PBKDF2, QueueHandler, sha as SHA, clientInfo, createTypedClient, i18n, isBot, jsonValidator, logger, onError, onNotFound, queue, response };
467
+ export type { ContextFn, CreateTypedClientOptions, HonoClientInfoVariables, HonoI18nVariables, HonoIsBotVariables, HonoLanguageVariables, HonoLoggerVariables, HonoResponseVariables, MessageHandlers, MiddlewareWithLoggingCapability, TypedClientCallbacks };
@@ -0,0 +1,467 @@
1
+ import * as hono from 'hono';
2
+ import { MiddlewareHandler, Context, Env, ErrorHandler, NotFoundHandler, Hono } from 'hono';
3
+ import { Logger, Details } from 'hierarchical-area-logger';
4
+ import * as hono_utils_http_status from 'hono/utils/http-status';
5
+ import { ContentfulStatusCode, SuccessStatusCode, ClientErrorStatusCode, StatusCode } from 'hono/utils/http-status';
6
+ import z$1, { z, ZodObject } from 'zod';
7
+ import * as _cloudflare_workers_types from '@cloudflare/workers-types';
8
+ import { Message, MessageBatch, Queue, Iso3166Alpha2Code, ContinentCode } from '@cloudflare/workers-types';
9
+ import * as hono_utils_types from 'hono/utils/types';
10
+ import { HTTPException } from 'hono/http-exception';
11
+ import { hc, ClientResponse } from 'hono/client';
12
+
13
+ type HonoLoggerVariables = {
14
+ logger: Logger;
15
+ eventId: string;
16
+ };
17
+ /**
18
+ * Logger middleware
19
+ *
20
+ * @description
21
+ * This middleware sets up a logger.
22
+ *
23
+ * @param details - Details to pass to the logger
24
+ * @param parentEventIdHeader - Header name to use for parent event ID
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * app.use('*', logger(
29
+ * {
30
+ * service: 'logger',
31
+ * },
32
+ * parentEventIdHeader: 'parent-event-id',
33
+ * ));
34
+ * ```
35
+ */
36
+ declare const logger: (details: Details, parentEventIdHeader?: string) => hono.MiddlewareHandler<{
37
+ Variables: HonoLoggerVariables;
38
+ }, string, {}, Response>;
39
+
40
+ /**
41
+ * @description
42
+ * Validator middleware for JSON data.
43
+ *
44
+ * @param schema - Zod schema for validation
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * app.post('/user', jsonValidator(z.object({
49
+ * name: z.string(),
50
+ * age: z.number(),
51
+ * })), (c) => {
52
+ * const { name, age } = await c.req.valid('json');
53
+ * return c.json({ name, age });
54
+ * });
55
+ * ```
56
+ */
57
+ declare const jsonValidator: <T extends z.ZodRawShape>(schema: z.ZodObject<T>) => hono.MiddlewareHandler<any, string, {
58
+ in: {
59
+ json: z.core.$InferObjectOutput<T, {}> extends infer T_1 ? T_1 extends z.core.$InferObjectOutput<T, {}> ? T_1 extends Promise<infer PR> ? PR extends Response | hono.TypedResponse<any, any, any> ? never : PR : T_1 extends Response | hono.TypedResponse<any, any, any> ? never : T_1 : never : never;
60
+ };
61
+ out: {
62
+ json: z.core.$InferObjectOutput<T, {}> extends infer T_2 ? T_2 extends z.core.$InferObjectOutput<T, {}> ? T_2 extends Promise<infer PR> ? PR extends Response | hono.TypedResponse<any, any, any> ? never : PR : T_2 extends Response | hono.TypedResponse<any, any, any> ? never : T_2 : never : never;
63
+ };
64
+ }, z.core.$InferObjectOutput<T, {}> extends infer T_3 ? T_3 extends z.core.$InferObjectOutput<T, {}> ? T_3 extends Promise<infer PR_1> ? PR_1 extends hono.TypedResponse<infer T_4, infer S extends hono_utils_http_status.StatusCode, infer F extends string> ? hono.TypedResponse<T_4, S, F> : PR_1 extends Response ? PR_1 : PR_1 extends undefined ? never : never : T_3 extends hono.TypedResponse<infer T_5, infer S_1 extends hono_utils_http_status.StatusCode, infer F_1 extends string> ? hono.TypedResponse<T_5, S_1, F_1> : T_3 extends Response ? T_3 : T_3 extends undefined ? never : never : never : never>;
65
+
66
+ type MiddlewareWithLoggingCapabilityProps<RestProps extends Record<string, unknown>> = {
67
+ useLogger?: boolean;
68
+ } & RestProps;
69
+ interface MiddlewareWithLoggingCapability<RestProps extends Record<string, unknown>> {
70
+ (props?: MiddlewareWithLoggingCapabilityProps<RestProps>): MiddlewareHandler;
71
+ }
72
+
73
+ type HonoIsBotVariables = {
74
+ isBot: boolean;
75
+ };
76
+ /**
77
+ * Middleware to detect and optionally block requests based on Cloudflare's Bot Management score.
78
+ * @param {Object} options - Configuration options for bot detection.
79
+ * @param {number} [options.threshold=49] - The bot score threshold (1-100).
80
+ * Cloudflare scores below this value are treated as bots. A lower score indicates a higher
81
+ * probability that the request is automated.
82
+ * @param {boolean} [options.allowVerifiedBot] - If true, the middleware strictly requires
83
+ * bots to be "verified" (e.g., Googlebot, Bingbot).
84
+ * Note: If this is enabled, non-verified bots will be blocked regardless of their score.
85
+ * @returns {MiddlewareHandler} A Hono middleware handler.
86
+ * @throws {HTTPException} Throws a 401 "Bot detected" error if the score is below the
87
+ * threshold or if a non-verified bot is detected when `allowVerifiedBot` is true.
88
+ * @example
89
+ * ```ts
90
+ * const app = new Hono<{ Variables: HonoIsBotVariables }>();
91
+ * // Block suspected bots with a score lower than 50
92
+ * app.use('/api/*', isBot({ threshold: 50, allowVerifiedBot: true }));
93
+ * ```
94
+ */
95
+ declare const isBot: MiddlewareWithLoggingCapability<{
96
+ threshold: number;
97
+ allowVerifiedBot?: boolean;
98
+ }>;
99
+
100
+ type HonoLanguageVariables = {
101
+ language: string;
102
+ };
103
+ type I18nShape = {
104
+ [key: string]: I18nShape | string;
105
+ };
106
+ type HonoI18nVariables = {
107
+ t: ReturnType<typeof setI18n>;
108
+ };
109
+ /**
110
+ * Set i18n
111
+ *
112
+ * @param translations - Translations object
113
+ * @param language - Language
114
+ * @param defaultLanguage - Default language
115
+ */
116
+ declare const setI18n: <T extends I18nShape>(translations: T, language: keyof T, defaultLanguage: string) => (input: string, params?: Record<string, string | number>, overrideLanguage?: keyof T) => string;
117
+ /**
118
+ * I18n Middleware and Queue Factory.
119
+ * @description
120
+ * Sets up the `t` translation function in the Hono context.
121
+ * Note: Requires a preceding middleware to set the `language` variable.
122
+ * @template T - The shape of the translations object.
123
+ * @param translations - The dictionary of translations.
124
+ * @param defaultLanguage - The fallback language code.
125
+ * @returns An object containing the `middleware` for Hono and a `queue` helper for background tasks.
126
+ * @example
127
+ * ```ts
128
+ * const translations = { en: { hi: "Hi {{name}}" }, fr: { hi: "Salut {{name}}" } };
129
+ * // 1. Set language first
130
+ * app.use('*', async (c, next) => {
131
+ * c.set('language', 'en');
132
+ * await next();
133
+ * });
134
+ * // 2. Initialize i18n
135
+ * const { middleware } = i18n(translations, 'en');
136
+ * app.use('*', middleware);
137
+ * // 3. Use in routes
138
+ * app.get('/', (c) => c.text(c.var.t('hi', { name: 'User' })));
139
+ * ```
140
+ */
141
+ declare const i18n: <T extends I18nShape>(translations: T, defaultLanguage: string) => {
142
+ middleware: hono.MiddlewareHandler<{
143
+ Variables: HonoLanguageVariables & HonoI18nVariables;
144
+ }, string, {}, Response>;
145
+ queue: (language?: keyof T) => (input: string, params?: Record<string, string | number>, overrideLanguage?: keyof T | undefined) => string;
146
+ };
147
+
148
+ type DataShape = Record<string, unknown>;
149
+
150
+ type QueueSendParams = {
151
+ parentEventId?: string;
152
+ language?: string;
153
+ };
154
+
155
+ type GenericQueueDataParams = {
156
+ eventId: string;
157
+ } & QueueSendParams;
158
+
159
+ type GenericQueueData<Content extends DataShape> = {
160
+ handler: keyof Content;
161
+ content: Content[keyof Content];
162
+ } & GenericQueueDataParams;
163
+
164
+ interface Variables<Context> {
165
+ context: Context & Pick<Message, 'retry' | 'ack'>;
166
+ metadata: Omit<GenericQueueData<DataShape>, 'content'> &
167
+ Omit<Message, 'body' | 'retry' | 'ack'>;
168
+ }
169
+
170
+ interface Handler<Content, Context> {
171
+ (message: Content, context: Context): Promise<void>;
172
+ }
173
+
174
+ type MessageHandlers<QueueData extends DataShape, Context> = {
175
+ [Term in keyof QueueData]: Handler<QueueData[Term], Variables<Context>>;
176
+ };
177
+
178
+ interface ContextFn<Environment, Context> {
179
+ (env: Environment, params: GenericQueueDataParams): Context;
180
+ }
181
+
182
+ /**
183
+ * A type-safe wrapper for Cloudflare Worker Queues using Zod for validation.
184
+ * * This class orchestrates the relationship between incoming queue messages and
185
+ * specific logic handlers, ensuring that data is validated at the edge before
186
+ * reaching your business logic.
187
+ *
188
+ * @template Schema - The Zod schema defining the message shapes.
189
+ * @template Environment - The Cloudflare Worker environment bindings (Env).
190
+ * @template Context - The application context derived from the environment and message.
191
+ */
192
+ declare class QueueHandler<Schema extends ZodObject<any>, Environment, Context> {
193
+ private readonly config;
194
+ private readonly handlers;
195
+ /**
196
+ * @param config - Configuration object.
197
+ * @param config.schema - The Zod schema used to parse and validate incoming message content.
198
+ * @param config.setContext - A factory function to generate context (e.g., DB connections, logging) for each message.
199
+ */
200
+ constructor(config: {
201
+ schema: Schema;
202
+ setContext: ContextFn<Environment, Context>;
203
+ });
204
+ /**
205
+ * Registers a specific processing function for a given message type (handlerName).
206
+ * * @template {keyof z.infer<Schema>} HandlerName - A specific key defined in your Zod schema.
207
+ * @param handlerName - The key identifying which handler to use.
208
+ * @param handler - The asynchronous logic to execute when this message type is received.
209
+ * @returns The current instance for fluent chaining.
210
+ */
211
+ addHandler<HandlerName extends keyof z.infer<Schema>>(handlerName: HandlerName, handler: Handler<z.infer<Schema>[HandlerName], Variables<Context>>): this;
212
+ /**
213
+ * Generates the Cloudflare Worker queue consumer function.
214
+ * * This handles the batch processing loop, parses the message body against the
215
+ * schema, injects context, and manages concurrency via `Promise.allSettled`.
216
+ * * @returns An async function compatible with the Cloudflare `queue` export.
217
+ */
218
+ getConsumer(): (batch: MessageBatch<GenericQueueData<z.infer<Schema>>>, env: Environment) => Promise<void>;
219
+ /**
220
+ * Creates a factory function for sending typed messages to a specific queue.
221
+ * * @param queue - The Cloudflare Queue binding (e.g., `env.MY_QUEUE`).
222
+ * @param params - Global parameters to include in every message (e.g., trace IDs).
223
+ * @returns A producer function that accepts a `handler` key and the corresponding typed content.
224
+ */
225
+ getProducer(queue: Queue<unknown>, params: QueueSendParams): <HandlerName extends keyof z.infer<Schema>>(handler: HandlerName, content: z.infer<Schema>[HandlerName]) => Promise<_cloudflare_workers_types.QueueSendResponse>;
226
+ }
227
+
228
+ /**
229
+ * Middleware to initialize a Queue producer and attach it to the Hono context.
230
+ * @description
231
+ * This middleware manages Cloudflare Queue interactions. If `finalizeLogHandler` is provided,
232
+ * it will automatically capture the current logger state and send it to the queue after
233
+ * the request is processed (post-`next()`).
234
+ * @param options.name - The name of the Queue binding defined in your `wrangler.toml`.
235
+ * @param options.queueHandler - An instance of your custom QueueHandler.
236
+ * @param [options.finalizeLogHandler] - Optional: The specific message type/key to use when finalizing the log.
237
+ * @example
238
+ * ```ts
239
+ * // OPTIONAL
240
+ * app.use('*', logger(
241
+ * {
242
+ * service: 'logger',
243
+ * },
244
+ * parentEventIdHeader: 'parent-event-id',
245
+ * ));
246
+ *
247
+ * app.use('*', queue({
248
+ * name: 'queue',
249
+ * queueHandler: new QueueHandler(),
250
+ * finalizeLogHandler: 'log'
251
+ * }));
252
+ * ```
253
+ */
254
+ declare const queue: <Schema extends ZodObject<any>, Environment, Context, Key extends keyof z$1.infer<Schema>>({ name, queueHandler, finalizeLogHandler, }: {
255
+ name: string;
256
+ queueHandler: QueueHandler<Schema, Environment, Context>;
257
+ finalizeLogHandler?: Key;
258
+ }) => hono.MiddlewareHandler<{
259
+ Bindings: Record<string, Queue>;
260
+ Variables: HonoLoggerVariables & Record<string, ReturnType<QueueHandler<Schema, Environment, Context>["getProducer"]>>;
261
+ }, string, {}, Response>;
262
+
263
+ type HonoResponseVariables = {
264
+ res: ReturnType<typeof setResponseHandlers>;
265
+ };
266
+ declare const setResponseHandlers: (c: Context) => {
267
+ raw: <T extends {
268
+ status?: ContentfulStatusCode;
269
+ }>(data: T) => Response & hono.TypedResponse<hono_utils_types.JSONParsed<Omit<T, "status">, bigint | readonly bigint[]>, 100 | 102 | 103 | 200 | 201 | 202 | 203 | 206 | 207 | 208 | 226 | 300 | 301 | 302 | 303 | 305 | 306 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 | -1, "json">;
270
+ success: <T extends object>(message: string, data: T, status?: SuccessStatusCode) => Response & hono.TypedResponse<string | T extends bigint | readonly bigint[] ? never : { [K in keyof {
271
+ message: string;
272
+ data: T;
273
+ } as ({
274
+ message: string;
275
+ data: T;
276
+ }[K] extends infer T_1 ? T_1 extends {
277
+ message: string;
278
+ data: T;
279
+ }[K] ? T_1 extends hono_utils_types.InvalidJSONValue ? true : false : never : never) extends true ? never : K]: boolean extends ({
280
+ message: string;
281
+ data: T;
282
+ }[K] extends infer T_2 ? T_2 extends {
283
+ message: string;
284
+ data: T;
285
+ }[K] ? T_2 extends hono_utils_types.InvalidJSONValue ? true : false : never : never) ? hono_utils_types.JSONParsed<{
286
+ message: string;
287
+ data: T;
288
+ }[K], bigint | readonly bigint[]> | undefined : hono_utils_types.JSONParsed<{
289
+ message: string;
290
+ data: T;
291
+ }[K], bigint | readonly bigint[]>; }, 100 | 102 | 103 | 200 | 201 | 202 | 203 | 206 | 207 | 208 | 226 | 300 | 301 | 302 | 303 | 305 | 306 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 | -1, "json">;
292
+ successNoContent: (message: string, status?: SuccessStatusCode) => Response & hono.TypedResponse<{
293
+ message: string;
294
+ }, 100 | 102 | 103 | 200 | 201 | 202 | 203 | 206 | 207 | 208 | 226 | 300 | 301 | 302 | 303 | 305 | 306 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 | -1, "json">;
295
+ error: (message: string, status: ClientErrorStatusCode) => never;
296
+ websocket: (socket: WebSocket) => Response;
297
+ };
298
+ /**
299
+ * Response Middleware
300
+ * @description
301
+ * Injects a `res` object into the Hono context (`c.var.res`).
302
+ * This ensures all outgoing responses follow a consistent schema and include
303
+ * tracing metadata (like `eventId`) automatically.
304
+ * @example
305
+ * ```ts
306
+ * app.use('*', response());
307
+ * ```
308
+ */
309
+ declare const response: hono.MiddlewareHandler<{
310
+ Variables: HonoResponseVariables & HonoLoggerVariables;
311
+ }, string, {}, Response>;
312
+
313
+ type CFData = {
314
+ isEUCountry: boolean;
315
+ latitude: string;
316
+ longitude: string;
317
+ city: string;
318
+ country: Iso3166Alpha2Code | 'T1';
319
+ continent: ContinentCode;
320
+ region?: string;
321
+ regionCode?: string;
322
+ postalCode: string;
323
+ timezone: string;
324
+ colo: string;
325
+ asn?: number;
326
+ };
327
+ type UserAgentData = {
328
+ browser: {
329
+ name: string;
330
+ version: string;
331
+ };
332
+ device: {
333
+ model: string;
334
+ vendor: string;
335
+ type: UAParser.IDevice['type'] | 'desktop';
336
+ };
337
+ engine: {
338
+ name: string;
339
+ version: string;
340
+ };
341
+ os: {
342
+ name: string;
343
+ version: string;
344
+ };
345
+ cpu: string;
346
+ };
347
+ type HonoClientInfoVariables = {
348
+ client: CFData & {
349
+ ip: string;
350
+ userAgent: string;
351
+ securityHash: string;
352
+ } & UserAgentData;
353
+ };
354
+ /**
355
+ * Hono middleware that extracts and injects comprehensive client information
356
+ * into the request context, including geolocation data from Cloudflare and
357
+ * parsed User-Agent details.
358
+ * @param {Object} [config] - Optional configuration for the middleware.
359
+ * @param {Function} [config.securityHashString] - A custom function to generate the seed string
360
+ * used for the security hash. Receives Cloudflare and User-Agent data as input.
361
+ * Defaults to `${city}${country}${continent}`.
362
+ * @param {string} [config.hashSecretBinding] - The name of the environment variable
363
+ * containing the hash secret. Defaults to 'HASH_SECRET'.
364
+ * @returns {MiddlewareHandler} A Hono middleware handler.
365
+ * @throws {Error} Throws an error if Cloudflare (`req.raw.cf`) data is missing.
366
+ * @example
367
+ * ```ts
368
+ * const app = new Hono<{ Variables: HonoClientInfoVariables }>();
369
+ *
370
+ * app.use('*', clientInfo({
371
+ * useLogger: true // for debugging purposes
372
+ * }));
373
+ *
374
+ * app.get('/me', (c) => {
375
+ * const client = c.get('client');
376
+ * return c.json({
377
+ * location: `${client.city}, ${client.country}`,
378
+ * device: client.device.type
379
+ * });
380
+ * });
381
+ * ```
382
+ */
383
+ declare const clientInfo: MiddlewareWithLoggingCapability<{
384
+ hashSecretBinding?: string;
385
+ securityHashString?: (content: CFData & UserAgentData & {
386
+ ip: string;
387
+ }) => string;
388
+ }>;
389
+
390
+ /**
391
+ * Derives a secure hex-encoded hash from an input string using PBKDF2-HMAC-SHA256.
392
+ * * @example
393
+ * const passwordHash = await hash("myPassword123", "random-salt-string");
394
+ * * @param {string} input - The plain-text string to hash.
395
+ * @param {string} salt - The salt string used to randomize the hash.
396
+ * @param {number} [iterations=600000] - The CPU cost factor. Default is 600,000.
397
+ * @returns {Promise<string>} A hex-encoded string representing the derived key.
398
+ */
399
+ declare function hash$1(input: string, salt: string, iterations?: number): Promise<string>;
400
+ /**
401
+ * Verifies if an input string matches a stored hash using a constant-time comparison.
402
+ * This prevents timing attacks by ensuring the execution time does not reveal
403
+ * how many characters of the hash were correct.
404
+ * * @param {string} input - The plain-text string to verify.
405
+ * @param {string} salt - The salt used during the original hashing.
406
+ * @param {string} storedHash - The hex-encoded hash previously stored in the database.
407
+ * @param {number} iterations - The iteration count used for the original hash.
408
+ * @returns {Promise<boolean>} Resolves to `true` if the input matches the hash, otherwise `false`.
409
+ */
410
+ declare function verify(input: string, salt: string, storedHash: string, iterations: number): Promise<boolean>;
411
+
412
+ declare const pbkdf2_verify: typeof verify;
413
+ declare namespace pbkdf2 {
414
+ export {
415
+ hash$1 as hash,
416
+ pbkdf2_verify as verify,
417
+ };
418
+ }
419
+
420
+ /**
421
+ * Generates a cryptographically strong random salt.
422
+ */
423
+ declare function generateSalt(length?: number): string;
424
+ /**
425
+ * Calculates the SHA hash of the given input string.
426
+ * @param algorithm - The algorithm to be used for hashing. Defaults to 256.
427
+ * @param pepper - An optional string to be prepended to the input before hashing.
428
+ * @param salt - An optional string to be appended to the input before hashing.
429
+ * @returns A Promise that resolves to the hashed string.
430
+ */
431
+ declare function hash({ input, algorithm, pepper, salt, }: {
432
+ input: string;
433
+ algorithm: 'SHA-256' | 'SHA-384' | 'SHA-512';
434
+ pepper?: string;
435
+ salt?: string;
436
+ }): Promise<string>;
437
+
438
+ declare const sha_generateSalt: typeof generateSalt;
439
+ declare const sha_hash: typeof hash;
440
+ declare namespace sha {
441
+ export {
442
+ sha_generateSalt as generateSalt,
443
+ sha_hash as hash,
444
+ };
445
+ }
446
+
447
+ declare const onError: <Environment extends Env>(parseError?: (err: Error | HTTPException, env: Environment["Bindings"], get: <K extends keyof Environment["Variables"]>(key: K) => Environment["Variables"][K]) => Promise<string>) => ErrorHandler<Environment>;
448
+
449
+ declare const onNotFound: NotFoundHandler;
450
+
451
+ type ErrorBody = Record<string, unknown>;
452
+ interface TypedClientCallbacks {
453
+ onStart?: () => void;
454
+ onSuccess?: (parsedData: unknown, headers: Headers) => void;
455
+ onError?: (parsedData: unknown, headers: Headers) => void;
456
+ onEnd?: () => void;
457
+ }
458
+ interface CreateTypedClientOptions {
459
+ url: string;
460
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
461
+ fetch?: typeof fetch;
462
+ errorHandler?: (status: StatusCode | number, body?: ErrorBody) => never;
463
+ }
464
+ declare const createTypedClient: <TApp extends Hono<any, any, any>>() => (options: CreateTypedClientOptions) => <TSuccessData>(fn: (c: ReturnType<typeof hc<TApp>>) => Promise<ClientResponse<TSuccessData>>, callbacks?: TypedClientCallbacks) => Promise<TSuccessData>;
465
+
466
+ export { pbkdf2 as PBKDF2, QueueHandler, sha as SHA, clientInfo, createTypedClient, i18n, isBot, jsonValidator, logger, onError, onNotFound, queue, response };
467
+ export type { ContextFn, CreateTypedClientOptions, HonoClientInfoVariables, HonoI18nVariables, HonoIsBotVariables, HonoLanguageVariables, HonoLoggerVariables, HonoResponseVariables, MessageHandlers, MiddlewareWithLoggingCapability, TypedClientCallbacks };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ import { Logger, Details } from 'hierarchical-area-logger';
4
4
  import * as hono_utils_http_status from 'hono/utils/http-status';
5
5
  import { ContentfulStatusCode, SuccessStatusCode, ClientErrorStatusCode, StatusCode } from 'hono/utils/http-status';
6
6
  import z$1, { z, ZodObject } from 'zod';
7
+ import * as _cloudflare_workers_types from '@cloudflare/workers-types';
7
8
  import { Message, MessageBatch, Queue, Iso3166Alpha2Code, ContinentCode } from '@cloudflare/workers-types';
8
9
  import * as hono_utils_types from 'hono/utils/types';
9
10
  import { HTTPException } from 'hono/http-exception';
@@ -221,7 +222,7 @@ declare class QueueHandler<Schema extends ZodObject<any>, Environment, Context>
221
222
  * @param params - Global parameters to include in every message (e.g., trace IDs).
222
223
  * @returns A producer function that accepts a `handler` key and the corresponding typed content.
223
224
  */
224
- getProducer(queue: Queue<unknown>, params: QueueSendParams): <HandlerName extends keyof z.infer<Schema>>(handler: HandlerName, content: z.infer<Schema>[HandlerName]) => Promise<void>;
225
+ getProducer(queue: Queue<unknown>, params: QueueSendParams): <HandlerName extends keyof z.infer<Schema>>(handler: HandlerName, content: z.infer<Schema>[HandlerName]) => Promise<_cloudflare_workers_types.QueueSendResponse>;
225
226
  }
226
227
 
227
228
  /**
@@ -410,7 +411,10 @@ declare function verify(input: string, salt: string, storedHash: string, iterati
410
411
 
411
412
  declare const pbkdf2_verify: typeof verify;
412
413
  declare namespace pbkdf2 {
413
- export { hash$1 as hash, pbkdf2_verify as verify };
414
+ export {
415
+ hash$1 as hash,
416
+ pbkdf2_verify as verify,
417
+ };
414
418
  }
415
419
 
416
420
  /**
@@ -434,7 +438,10 @@ declare function hash({ input, algorithm, pepper, salt, }: {
434
438
  declare const sha_generateSalt: typeof generateSalt;
435
439
  declare const sha_hash: typeof hash;
436
440
  declare namespace sha {
437
- export { sha_generateSalt as generateSalt, sha_hash as hash };
441
+ export {
442
+ sha_generateSalt as generateSalt,
443
+ sha_hash as hash,
444
+ };
438
445
  }
439
446
 
440
447
  declare const onError: <Environment extends Env>(parseError?: (err: Error | HTTPException, env: Environment["Bindings"], get: <K extends keyof Environment["Variables"]>(key: K) => Environment["Variables"][K]) => Promise<string>) => ErrorHandler<Environment>;
@@ -456,4 +463,5 @@ interface CreateTypedClientOptions {
456
463
  }
457
464
  declare const createTypedClient: <TApp extends Hono<any, any, any>>() => (options: CreateTypedClientOptions) => <TSuccessData>(fn: (c: ReturnType<typeof hc<TApp>>) => Promise<ClientResponse<TSuccessData>>, callbacks?: TypedClientCallbacks) => Promise<TSuccessData>;
458
465
 
459
- export { type ContextFn, type CreateTypedClientOptions, type HonoClientInfoVariables, type HonoI18nVariables, type HonoIsBotVariables, type HonoLanguageVariables, type HonoLoggerVariables, type HonoResponseVariables, type MessageHandlers, type MiddlewareWithLoggingCapability, pbkdf2 as PBKDF2, QueueHandler, sha as SHA, type TypedClientCallbacks, clientInfo, createTypedClient, i18n, isBot, jsonValidator, logger, onError, onNotFound, queue, response };
466
+ export { pbkdf2 as PBKDF2, QueueHandler, sha as SHA, clientInfo, createTypedClient, i18n, isBot, jsonValidator, logger, onError, onNotFound, queue, response };
467
+ export type { ContextFn, CreateTypedClientOptions, HonoClientInfoVariables, HonoI18nVariables, HonoIsBotVariables, HonoLanguageVariables, HonoLoggerVariables, HonoResponseVariables, MessageHandlers, MiddlewareWithLoggingCapability, TypedClientCallbacks };