hono 2.7.0 → 3.0.0-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 (37) hide show
  1. package/dist/cjs/compose.js +6 -0
  2. package/dist/cjs/context.js +29 -6
  3. package/dist/cjs/hono.js +21 -6
  4. package/dist/cjs/middleware/cache/index.js +1 -1
  5. package/dist/cjs/middleware/validator/index.js +29 -2
  6. package/dist/cjs/request.js +94 -36
  7. package/dist/compose.js +6 -0
  8. package/dist/context.js +29 -6
  9. package/dist/hono.js +21 -6
  10. package/dist/middleware/cache/index.js +1 -1
  11. package/dist/middleware/validator/index.js +29 -2
  12. package/dist/request.js +94 -36
  13. package/dist/types/compose.d.ts +1 -1
  14. package/dist/types/context.d.ts +25 -9
  15. package/dist/types/hono.d.ts +33 -26
  16. package/dist/types/index.d.ts +2 -4
  17. package/dist/types/middleware/serve-static/module.d.ts +1 -1
  18. package/dist/types/middleware/validator/index.d.ts +8 -2
  19. package/dist/types/request.d.ts +41 -36
  20. package/dist/types/types.d.ts +87 -14
  21. package/dist/types/utils/types.d.ts +1 -0
  22. package/package.json +5 -3
  23. package/dist/cjs/middleware/validator/middleware.js +0 -137
  24. package/dist/cjs/validator/rule.js +0 -94
  25. package/dist/cjs/validator/sanitizer.js +0 -30
  26. package/dist/cjs/validator/schema.js +0 -16
  27. package/dist/cjs/validator/validator.js +0 -441
  28. package/dist/middleware/validator/middleware.js +0 -114
  29. package/dist/types/middleware/validator/middleware.d.ts +0 -15
  30. package/dist/types/validator/rule.d.ts +0 -21
  31. package/dist/types/validator/sanitizer.d.ts +0 -3
  32. package/dist/types/validator/schema.d.ts +0 -10
  33. package/dist/types/validator/validator.d.ts +0 -134
  34. package/dist/validator/rule.js +0 -71
  35. package/dist/validator/sanitizer.js +0 -7
  36. package/dist/validator/schema.js +0 -0
  37. package/dist/validator/validator.js +0 -408
@@ -1,441 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var validator_exports = {};
20
- __export(validator_exports, {
21
- VArray: () => VArray,
22
- VBase: () => VBase,
23
- VBoolean: () => VBoolean,
24
- VBooleanArray: () => VBooleanArray,
25
- VNumber: () => VNumber,
26
- VNumberArray: () => VNumberArray,
27
- VObject: () => VObject,
28
- VObjectBase: () => VObjectBase,
29
- VString: () => VString,
30
- VStringArray: () => VStringArray,
31
- Validator: () => Validator
32
- });
33
- module.exports = __toCommonJS(validator_exports);
34
- var import_json = require("./../utils/json");
35
- var import_rule = require("./rule");
36
- var import_sanitizer = require("./sanitizer");
37
- class VObjectBase {
38
- constructor(container, key) {
39
- this.keys = [];
40
- this._isOptional = false;
41
- this.getValidators = () => {
42
- const validators = [];
43
- const walk = (container, keys, isOptional) => {
44
- for (const v of Object.values(container)) {
45
- if (v instanceof VArray || v instanceof VObject) {
46
- isOptional || (isOptional = v._isOptional);
47
- walk(v.container, [...keys, ...v.keys], isOptional);
48
- } else if (v instanceof VBase) {
49
- if (isOptional)
50
- v.isOptional();
51
- v.baseKeys.push(...keys);
52
- validators.push(v);
53
- }
54
- }
55
- };
56
- walk(this.container, this.keys, this._isOptional);
57
- return validators;
58
- };
59
- this.container = container;
60
- if (this instanceof VArray) {
61
- this.keys.push(key, "[*]");
62
- } else if (this instanceof VObject) {
63
- this.keys.push(key);
64
- }
65
- }
66
- isOptional() {
67
- this._isOptional = true;
68
- return this;
69
- }
70
- }
71
- class VObject extends VObjectBase {
72
- constructor(container, key) {
73
- super(container, key);
74
- }
75
- }
76
- class VArray extends VObjectBase {
77
- constructor(container, key) {
78
- super(container, key);
79
- this.type = "array";
80
- }
81
- }
82
- class Validator {
83
- constructor(inArray = false) {
84
- this.inArray = inArray;
85
- this.query = (key) => new VString({ target: "query", key });
86
- this.queries = (key) => new VStringArray({ target: "queries", key });
87
- this.header = (key) => new VString({ target: "header", key });
88
- this.body = (key) => new VString({ target: "body", key });
89
- this.json = (key) => {
90
- if (this.inArray) {
91
- return new VStringArray({ target: "json", key });
92
- } else {
93
- return new VString({ target: "json", key });
94
- }
95
- };
96
- this.array = (path, validatorFn) => {
97
- const validator = new Validator(true);
98
- const res = validatorFn(validator);
99
- const arr = new VArray(res, path);
100
- return arr;
101
- };
102
- this.object = (path, validatorFn) => {
103
- const validator = new Validator(this.inArray);
104
- const res = validatorFn(validator);
105
- const obj = new VObject(res, path);
106
- return obj;
107
- };
108
- }
109
- }
110
- class VBase {
111
- constructor(options) {
112
- this.baseKeys = [];
113
- this._nested = () => this.baseKeys.length ? true : false;
114
- this.addSanitizer = (sanitizer2) => {
115
- this.sanitizers.push(sanitizer2);
116
- return this;
117
- };
118
- this.message = (text) => {
119
- const len = this.rules.length;
120
- if (len >= 1) {
121
- this.rules[len - 1].customMessage = text;
122
- }
123
- return this;
124
- };
125
- this.isRequired = () => {
126
- return this.addRule("isRequired", (value) => {
127
- if (value !== void 0 && value !== null && value !== "")
128
- return true;
129
- return false;
130
- });
131
- };
132
- this.isOptional = () => {
133
- this._optional = true;
134
- return this.addRule("isOptional", () => true);
135
- };
136
- this.isEqual = (comparison) => {
137
- return this.addRule("isEqual", (value) => {
138
- return value === comparison;
139
- });
140
- };
141
- this.asNumber = () => {
142
- return new VNumber({ ...this, type: "number" });
143
- };
144
- this.asBoolean = () => {
145
- return new VBoolean({ ...this, type: "boolean" });
146
- };
147
- this.validate = async (req) => {
148
- let value = void 0;
149
- let jsonData = void 0;
150
- if (this.target === "query") {
151
- value = req.query(this.key);
152
- }
153
- if (this.target === "queries") {
154
- value = req.queries(this.key);
155
- }
156
- if (this.target === "header") {
157
- value = req.header(this.key);
158
- }
159
- if (this.target === "body") {
160
- const body = await req.parseBody();
161
- value = body[this.key];
162
- }
163
- if (this.target === "json") {
164
- if (this._nested()) {
165
- this.key = `${this.baseKeys.join(".")}.${this.key}`;
166
- }
167
- let obj = {};
168
- try {
169
- obj = await req.json();
170
- } catch (e) {
171
- throw new Error("Malformed JSON in request body");
172
- }
173
- const dst = {};
174
- value = (0, import_json.JSONPathCopy)(obj, dst, this.key);
175
- if (this._nested())
176
- jsonData = dst;
177
- }
178
- value = this.sanitizeValue(value);
179
- const results = [];
180
- let typeRule = this.rules.shift();
181
- for (const rule2 of this.rules) {
182
- if (rule2.type === "type") {
183
- typeRule = rule2;
184
- } else if (rule2.type === "value") {
185
- const result = this.validateRule(rule2, value);
186
- result.jsonData || (result.jsonData = jsonData);
187
- results.push(result);
188
- }
189
- }
190
- if (typeRule) {
191
- const typeResult = this.validateRule(typeRule, value);
192
- typeResult.jsonData || (typeResult.jsonData = jsonData);
193
- results.unshift(typeResult);
194
- this.rules.unshift(typeRule);
195
- }
196
- return results;
197
- };
198
- this.sanitizeValue = (value) => this.sanitizers.reduce((acc, sanitizer2) => sanitizer2(acc), value);
199
- this.validateType = (value) => {
200
- if (this.isArray) {
201
- if (!Array.isArray(value)) {
202
- return this._optional && typeof value === "undefined";
203
- }
204
- for (const val of value) {
205
- if (typeof val === "undefined" && this._nested()) {
206
- value.pop();
207
- }
208
- for (const val2 of value) {
209
- if (typeof val2 !== this.type) {
210
- if (!this._optional || typeof val2 !== "undefined")
211
- return false;
212
- }
213
- }
214
- }
215
- } else {
216
- if (typeof value !== this.type) {
217
- if (this._optional && (typeof value === "undefined" || Array.isArray(value))) {
218
- } else {
219
- return false;
220
- }
221
- }
222
- }
223
- return true;
224
- };
225
- this.validateValue = (func, value) => {
226
- if (this._optional && typeof value === "undefined")
227
- return true;
228
- if (Array.isArray(value)) {
229
- if (value.length === 0 && !this._optional)
230
- return false;
231
- for (const val of value) {
232
- if (!func(val)) {
233
- return false;
234
- }
235
- }
236
- return true;
237
- } else {
238
- if (!func(value)) {
239
- return false;
240
- }
241
- return true;
242
- }
243
- };
244
- this.getMessage = (opts) => {
245
- let keyText;
246
- const valueText = Array.isArray(opts.value) ? `${opts.value.map(
247
- (val) => val === void 0 ? "undefined" : typeof val === "string" ? `"${val}"` : val
248
- ).join(", ")}` : opts.value;
249
- switch (this.target) {
250
- case "query":
251
- keyText = `the query parameter "${this.key}"`;
252
- break;
253
- case "queries":
254
- keyText = `the query parameters "${this.key}"`;
255
- break;
256
- case "header":
257
- keyText = `the request header "${this.key}"`;
258
- break;
259
- case "body":
260
- keyText = `the request body "${this.key}"`;
261
- break;
262
- case "json":
263
- keyText = `the JSON body "${this.key}"`;
264
- break;
265
- }
266
- return `Invalid Value [${valueText}]: ${keyText} is invalid - ${opts.ruleName}`;
267
- };
268
- this.target = options.target;
269
- this.key = options.key;
270
- this.type = options.type || "string";
271
- this.rules = [
272
- {
273
- name: this.getTypeRuleName(),
274
- type: "type",
275
- func: this.validateType
276
- }
277
- ];
278
- this.sanitizers = [];
279
- this._optional = false;
280
- this.isArray = options.isArray || false;
281
- }
282
- addRule(arg, func) {
283
- if (typeof arg === "string" && func) {
284
- this.rules.push({ name: arg, func, type: "value" });
285
- } else if (arg instanceof Function) {
286
- this.rules.push({ name: arg.name, func: arg, type: "value" });
287
- }
288
- return this;
289
- }
290
- get(value) {
291
- const len = this.rules.length;
292
- if (len > 0) {
293
- this.rules[this.rules.length - 1].customMessage = value;
294
- }
295
- return this;
296
- }
297
- getTypeRuleName() {
298
- const prefix = "should be";
299
- return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`;
300
- }
301
- validateRule(rule2, value) {
302
- let isValid = false;
303
- if (this._nested() && this.target != "json") {
304
- isValid = false;
305
- } else if (rule2.type === "value") {
306
- isValid = this.validateValue(rule2.func, value);
307
- } else if (rule2.type === "type") {
308
- isValid = this.validateType(value);
309
- }
310
- const message = isValid ? void 0 : rule2.customMessage || this.getMessage({ ruleName: rule2.name, value });
311
- const result = {
312
- isValid,
313
- message,
314
- target: this.target,
315
- key: this.key,
316
- value,
317
- ruleName: rule2.name,
318
- ruleType: rule2.type
319
- };
320
- return result;
321
- }
322
- }
323
- class VString extends VBase {
324
- constructor(options) {
325
- super(options);
326
- this.asArray = () => {
327
- return new VStringArray(this);
328
- };
329
- this.isEmpty = (options = { ignore_whitespace: false }) => {
330
- return this.addRule("isEmpty", (value) => import_rule.rule.isEmpty(value, options));
331
- };
332
- this.isLength = (options, arg2) => {
333
- return this.addRule("isLength", (value) => import_rule.rule.isLength(value, options, arg2));
334
- };
335
- this.isAlpha = () => {
336
- return this.addRule("isAlpha", (value) => import_rule.rule.isAlpha(value));
337
- };
338
- this.isNumeric = () => {
339
- return this.addRule("isNumeric", (value) => import_rule.rule.isNumeric(value));
340
- };
341
- this.contains = (elem, options = {
342
- ignoreCase: false,
343
- minOccurrences: 1
344
- }) => {
345
- return this.addRule("contains", (value) => import_rule.rule.contains(value, elem, options));
346
- };
347
- this.isIn = (options) => {
348
- return this.addRule("isIn", (value) => import_rule.rule.isIn(value, options));
349
- };
350
- this.match = (regExp) => {
351
- return this.addRule("match", (value) => import_rule.rule.match(value, regExp));
352
- };
353
- this.trim = () => {
354
- return this.addSanitizer((value) => import_sanitizer.sanitizer.trim(value));
355
- };
356
- this.type = "string";
357
- }
358
- }
359
- class VNumber extends VBase {
360
- constructor(options) {
361
- super(options);
362
- this.asArray = () => {
363
- return new VNumberArray(this);
364
- };
365
- this.isGte = (min) => {
366
- return this.addRule("isGte", (value) => import_rule.rule.isGte(value, min));
367
- };
368
- this.isLte = (min) => {
369
- return this.addRule("isLte", (value) => import_rule.rule.isLte(value, min));
370
- };
371
- this.type = "number";
372
- }
373
- }
374
- class VBoolean extends VBase {
375
- constructor(options) {
376
- super(options);
377
- this.asArray = () => {
378
- return new VBooleanArray(this);
379
- };
380
- this.isTrue = () => {
381
- return this.addRule("isTrue", (value) => import_rule.rule.isTrue(value));
382
- };
383
- this.isFalse = () => {
384
- return this.addRule("isFalse", (value) => import_rule.rule.isFalse(value));
385
- };
386
- this.type = "boolean";
387
- }
388
- }
389
- class VNumberArray extends VNumber {
390
- constructor(options) {
391
- super(options);
392
- this.asNumber = () => {
393
- return new VNumberArray({ ...this, type: "number" });
394
- };
395
- this.asBoolean = () => {
396
- return new VBooleanArray({ ...this, type: "boolean" });
397
- };
398
- this.isArray = true;
399
- this.rules[0].name = this.getTypeRuleName();
400
- }
401
- }
402
- class VStringArray extends VString {
403
- constructor(options) {
404
- super(options);
405
- this.asNumber = () => {
406
- return new VNumberArray({ ...this, type: "number" });
407
- };
408
- this.asBoolean = () => {
409
- return new VBooleanArray({ ...this, type: "boolean" });
410
- };
411
- this.isArray = true;
412
- this.rules[0].name = this.getTypeRuleName();
413
- }
414
- }
415
- class VBooleanArray extends VBoolean {
416
- constructor(options) {
417
- super(options);
418
- this.asNumber = () => {
419
- return new VNumberArray({ ...this, type: "number" });
420
- };
421
- this.asBoolean = () => {
422
- return new VBooleanArray({ ...this, type: "boolean" });
423
- };
424
- this.isArray = true;
425
- this.rules[0].name = this.getTypeRuleName();
426
- }
427
- }
428
- // Annotate the CommonJS export names for ESM import in node:
429
- 0 && (module.exports = {
430
- VArray,
431
- VBase,
432
- VBoolean,
433
- VBooleanArray,
434
- VNumber,
435
- VNumberArray,
436
- VObject,
437
- VObjectBase,
438
- VString,
439
- VStringArray,
440
- Validator
441
- });
@@ -1,114 +0,0 @@
1
- // src/middleware/validator/middleware.ts
2
- import { getStatusText } from "../../utils/http-status.js";
3
- import { mergeObjects } from "../../utils/object.js";
4
- import { Validator, VBase, VObjectBase } from "../../validator/validator.js";
5
- var validatorMiddleware = (validationFunction, options) => {
6
- const v = new Validator();
7
- const handler = async (c, next) => {
8
- var _a;
9
- const resultSet = {
10
- hasError: false,
11
- messages: [],
12
- results: []
13
- };
14
- const schema = validationFunction(v, c);
15
- const validatorList = getValidatorList(schema);
16
- let data = {};
17
- for (const [keys, validator] of validatorList) {
18
- let results;
19
- try {
20
- results = await validator.validate(c.req);
21
- } catch (e) {
22
- if (e instanceof Error) {
23
- const result = getErrorResult(e);
24
- resultSet.hasError = true;
25
- resultSet.messages = [result.message || ""];
26
- resultSet.results = [result];
27
- break;
28
- } else {
29
- return c.text(getStatusText(400), 400);
30
- }
31
- }
32
- let isValid = true;
33
- const value = results[0].value;
34
- const jsonData = results[0].jsonData;
35
- for (const result of results) {
36
- if (!result.isValid) {
37
- isValid = false;
38
- resultSet.hasError = true;
39
- if (result.ruleType === "value" && result.message !== void 0) {
40
- resultSet.messages.push(result.message);
41
- }
42
- }
43
- resultSet.results.push(result);
44
- }
45
- if (!isValid && resultSet.messages.length === 0) {
46
- resultSet.results.map((r) => {
47
- if (!r.isValid && r.ruleType === "type" && r.message) {
48
- resultSet.messages.push(r.message);
49
- }
50
- });
51
- }
52
- if (isValid) {
53
- if (jsonData) {
54
- const dst = data;
55
- data = mergeObjects(dst, jsonData);
56
- } else {
57
- let tmp = data;
58
- for (let i = 0; i < keys.length - 1; i++) {
59
- tmp = tmp[_a = keys[i]] || (tmp[_a] = {});
60
- }
61
- tmp[keys[keys.length - 1]] = value;
62
- }
63
- }
64
- }
65
- if (!resultSet.hasError) {
66
- c.req.valid(data);
67
- }
68
- if (options && options.done) {
69
- const res = options.done(resultSet, c);
70
- if (res) {
71
- return res;
72
- }
73
- }
74
- if (resultSet.hasError) {
75
- return c.text(resultSet.messages.join("\n"), 400);
76
- }
77
- await next();
78
- };
79
- return handler;
80
- };
81
- function getValidatorList(schema) {
82
- const map = [];
83
- for (const [key, value] of Object.entries(schema)) {
84
- if (value instanceof VObjectBase) {
85
- const validators = value.getValidators();
86
- for (const validator of validators) {
87
- map.push([value.keys, validator]);
88
- }
89
- } else if (value instanceof VBase) {
90
- map.push([[key], value]);
91
- } else {
92
- const children = getValidatorList(value);
93
- for (const [keys, validator] of children) {
94
- map.push([[key, ...keys], validator]);
95
- }
96
- }
97
- }
98
- return map;
99
- }
100
- var getErrorResult = (e) => {
101
- const result = {
102
- isValid: false,
103
- message: e.message,
104
- target: "unknown",
105
- key: null,
106
- value: null,
107
- ruleName: e.message,
108
- ruleType: "value"
109
- };
110
- return result;
111
- };
112
- export {
113
- validatorMiddleware
114
- };
@@ -1,15 +0,0 @@
1
- import type { Context } from '../../context';
2
- import type { Environment, MiddlewareHandler } from '../../types';
3
- import type { ValidateResult } from '../../validator/validator';
4
- import { Validator } from '../../validator/validator';
5
- declare type ResultSet = {
6
- hasError: boolean;
7
- messages: string[];
8
- results: ValidateResult[];
9
- };
10
- declare type Done<P extends string, E extends Partial<Environment> = Environment> = (resultSet: ResultSet, c: Context<P, E>) => Response | void;
11
- declare type ValidationFunction<P extends string, E extends Partial<Environment> = Environment, S = unknown> = (v: Validator, c: Context<P, E>) => S;
12
- export declare const validatorMiddleware: <P extends string, E extends Partial<Environment> = Environment, S = unknown>(validationFunction: ValidationFunction<P, E, S>, options?: {
13
- done?: Done<P, E> | undefined;
14
- } | undefined) => MiddlewareHandler<string, E, S>;
15
- export {};
@@ -1,21 +0,0 @@
1
- export declare const rule: {
2
- isEmpty(value: string, options?: {
3
- ignore_whitespace: boolean;
4
- }): boolean;
5
- isLength: (value: string, options: Partial<{
6
- min: number;
7
- max: number;
8
- }> | number, arg2?: number) => boolean;
9
- isAlpha: (value: string) => boolean;
10
- isNumeric: (value: string) => boolean;
11
- contains: (value: string, elem: string, options?: Partial<{
12
- ignoreCase: boolean;
13
- minOccurrences: number;
14
- }>) => boolean;
15
- isIn: (value: string, options: string[]) => boolean;
16
- match: (value: string, regExp: RegExp) => boolean;
17
- isGte: (value: number, min: number) => boolean;
18
- isLte: (value: number, max: number) => boolean;
19
- isTrue: (value: boolean) => boolean;
20
- isFalse: (value: boolean) => boolean;
21
- };
@@ -1,3 +0,0 @@
1
- export declare const sanitizer: {
2
- trim: (value: string) => string;
3
- };
@@ -1,10 +0,0 @@
1
- import type { VString, VNumber, VBoolean, VObject, VArray, VNumberArray, VStringArray, VBooleanArray, VBase } from './validator';
2
- export declare type Schema = {
3
- [key: string]: VString | VNumber | VBoolean | Schema | VObject<Schema> | VArray<Schema>;
4
- };
5
- declare type Primitive<T> = T extends VNumberArray ? number[] : T extends VNumber ? number : T extends VStringArray ? string[] : T extends VString ? string : T extends VBooleanArray ? boolean[] : T extends VBoolean ? boolean : T;
6
- declare type P<T> = T extends VArray<infer R> ? P<R>[] : T extends VObject<infer R> ? P<R> : {
7
- [K in keyof T]: T[K] extends VBase ? Primitive<T[K]> : T[K] extends VArray<infer R> ? P<R>[] : T[K] extends VObject<infer R> ? P<R> : T[K] extends Schema ? P<T[K]> : never;
8
- };
9
- export declare type SchemaToProp<T> = P<T>;
10
- export {};