elysia 1.4.30 → 1.4.32

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.
@@ -7,76 +7,19 @@ import {
7
7
  ValidationError
8
8
  } from "./error.mjs";
9
9
  import { parseQuery } from "./parse-query.mjs";
10
- import { getSchemaProperties } from "./schema.mjs";
11
- import { hasSetImmediate, redirect, StatusMap, signCookie } from "./utils.mjs";
12
- const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), isDangerousKey = (key) => {
13
- if (DANGEROUS_KEYS.has(key)) return !0;
14
- const match = key.match(ARRAY_INDEX_REGEX);
15
- return match ? DANGEROUS_KEYS.has(match[1]) : !1;
16
- }, parseArrayKey = (key) => {
17
- const match = key.match(ARRAY_INDEX_REGEX);
18
- return match ? {
19
- name: match[1],
20
- index: parseInt(match[2], 10)
21
- } : null;
22
- }, parseObjectString = (entry) => {
23
- if (!(typeof entry != "string" || entry.charCodeAt(0) !== 123))
24
- try {
25
- const parsed = JSON.parse(entry);
26
- if (parsed && typeof parsed == "object" && !Array.isArray(parsed))
27
- return parsed;
28
- } catch {
29
- return;
30
- }
31
- }, setNestedValue = (obj, path, value) => {
32
- const keys = path.split("."), lastKey = keys.pop();
33
- if (isDangerousKey(lastKey) || keys.some(isDangerousKey)) return;
34
- let current = obj;
35
- for (const key of keys) {
36
- const arrayInfo2 = parseArrayKey(key);
37
- if (arrayInfo2) {
38
- Array.isArray(current[arrayInfo2.name]) || (current[arrayInfo2.name] = []);
39
- const existing = current[arrayInfo2.name][arrayInfo2.index], isFile = typeof File < "u" && existing instanceof File;
40
- (!existing || typeof existing != "object" || Array.isArray(existing) || isFile) && (current[arrayInfo2.name][arrayInfo2.index] = parseObjectString(existing) ?? {}), current = current[arrayInfo2.name][arrayInfo2.index];
41
- } else
42
- (!current[key] || typeof current[key] != "object") && (current[key] = {}), current = current[key];
43
- }
44
- const arrayInfo = parseArrayKey(lastKey);
45
- arrayInfo ? (Array.isArray(current[arrayInfo.name]) || (current[arrayInfo.name] = []), current[arrayInfo.name][arrayInfo.index] = value) : current[lastKey] = value;
46
- }, normalizeFormValue = (value) => {
47
- if (value.length === 1) {
48
- const stringValue2 = value[0];
49
- if (typeof stringValue2 == "string" && (stringValue2.charCodeAt(0) === 123 || stringValue2.charCodeAt(0) === 91))
50
- try {
51
- const parsed2 = JSON.parse(stringValue2);
52
- if (parsed2 && typeof parsed2 == "object")
53
- return parsed2;
54
- } catch {
55
- }
56
- return value[0];
57
- }
58
- const stringValue = value.find(
59
- (entry) => typeof entry == "string"
60
- );
61
- if (!stringValue || typeof File > "u") return value;
62
- const files = value.filter((entry) => entry instanceof File);
63
- if (!files.length || stringValue.charCodeAt(0) !== 123) return value;
64
- let parsed;
65
- try {
66
- parsed = JSON.parse(stringValue);
67
- } catch {
68
- return value;
69
- }
70
- return typeof parsed != "object" || parsed === null ? value : (!("file" in parsed) && files.length === 1 ? parsed.file = files[0] : !("files" in parsed) && files.length > 1 && (parsed.files = files), parsed);
71
- }, injectDefaultValues = (typeChecker, obj) => {
72
- let schema = typeChecker.schema;
73
- if (!schema) return;
74
- schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]);
75
- const properties = getSchemaProperties(schema);
76
- if (properties)
77
- for (const [key, keySchema] of Object.entries(properties))
78
- obj[key] ??= keySchema.default;
79
- };
10
+ import { parseFormData } from "./form-data.mjs";
11
+ import {
12
+ applySchemaDefaults,
13
+ getSchemaProperties
14
+ } from "./schema.mjs";
15
+ import {
16
+ hasSetImmediate,
17
+ mergeCookie,
18
+ redirect,
19
+ safeAssign,
20
+ StatusMap,
21
+ signCookie
22
+ } from "./utils.mjs";
80
23
  async function validateStandardSchema(type, validator, value) {
81
24
  const result = await validator.Validate(value);
82
25
  if (result.issues)
@@ -124,10 +67,10 @@ const createDynamicHandler = (app) => {
124
67
  if (!handler)
125
68
  throw context.query = qi === -1 ? {} : parseQuery(url.substring(qi + 1)), new NotFoundError();
126
69
  const { handle, validator, content, route } = handler.store;
127
- if (hooks = handler.store.hooks, hooks.config?.mount)
128
- return await hooks.config.mount(request);
70
+ hooks = handler.store.hooks;
71
+ const isMount = !!hooks.config?.mount;
129
72
  let body;
130
- if (request.method !== "GET" && request.method !== "HEAD")
73
+ if (!isMount && request.method !== "GET" && request.method !== "HEAD")
131
74
  if (content)
132
75
  switch (content) {
133
76
  case "application/json":
@@ -143,17 +86,7 @@ const createDynamicHandler = (app) => {
143
86
  body = await request.arrayBuffer();
144
87
  break;
145
88
  case "multipart/form-data": {
146
- body = {};
147
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
148
- form.forEach((v, k) => {
149
- const list = grouped.get(k);
150
- list ? list.push(v) : grouped.set(k, [v]);
151
- });
152
- for (const [key, value] of grouped) {
153
- if (body[key]) continue;
154
- const finalValue = normalizeFormValue(value);
155
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
156
- }
89
+ body = parseFormData(await request.formData());
157
90
  break;
158
91
  }
159
92
  }
@@ -186,17 +119,9 @@ const createDynamicHandler = (app) => {
186
119
  break;
187
120
  case "formdata":
188
121
  case "multipart/form-data": {
189
- body = {};
190
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
191
- form.forEach((v, k) => {
192
- const list = grouped.get(k);
193
- list ? list.push(v) : grouped.set(k, [v]);
194
- });
195
- for (const [key, value] of grouped) {
196
- if (body[key]) continue;
197
- const finalValue = normalizeFormValue(value);
198
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
199
- }
122
+ body = parseFormData(
123
+ await request.formData()
124
+ );
200
125
  break;
201
126
  }
202
127
  default: {
@@ -237,17 +162,9 @@ const createDynamicHandler = (app) => {
237
162
  body = await request.arrayBuffer();
238
163
  break;
239
164
  case "multipart/form-data": {
240
- body = {};
241
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
242
- form.forEach((v, k) => {
243
- const list = grouped.get(k);
244
- list ? list.push(v) : grouped.set(k, [v]);
245
- });
246
- for (const [key, value] of grouped) {
247
- if (body[key]) continue;
248
- const finalValue = normalizeFormValue(value);
249
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
250
- }
165
+ body = parseFormData(
166
+ await request.formData()
167
+ );
251
168
  break;
252
169
  }
253
170
  }
@@ -256,29 +173,29 @@ const createDynamicHandler = (app) => {
256
173
  context.route = route, context.body = body, context.params = handler?.params || void 0, context.query = qi === -1 ? {} : parseQuery(url.substring(qi + 1)), context.headers = {};
257
174
  for (const [key, value] of request.headers.entries())
258
175
  context.headers[key] = value;
259
- const cookieMeta = {
260
- domain: app.config.cookie?.domain ?? // @ts-expect-error
176
+ const cookieValidator = validator?.createCookie?.(), defaultCookie = hooks.config?.cookie ? mergeCookie(app.config.cookie ?? {}, hooks.config.cookie) : app.config.cookie, cookieMeta = {
177
+ domain: defaultCookie?.domain ?? // @ts-expect-error
261
178
  validator?.cookie?.config.domain,
262
- expires: app.config.cookie?.expires ?? // @ts-expect-error
179
+ expires: defaultCookie?.expires ?? // @ts-expect-error
263
180
  validator?.cookie?.config.expires,
264
- httpOnly: app.config.cookie?.httpOnly ?? // @ts-expect-error
181
+ httpOnly: defaultCookie?.httpOnly ?? // @ts-expect-error
265
182
  validator?.cookie?.config.httpOnly,
266
- maxAge: app.config.cookie?.maxAge ?? // @ts-expect-error
183
+ maxAge: defaultCookie?.maxAge ?? // @ts-expect-error
267
184
  validator?.cookie?.config.maxAge,
268
185
  // @ts-expect-error
269
- path: app.config.cookie?.path ?? validator?.cookie?.config.path,
270
- priority: app.config.cookie?.priority ?? // @ts-expect-error
186
+ path: defaultCookie?.path ?? validator?.cookie?.config.path,
187
+ priority: defaultCookie?.priority ?? // @ts-expect-error
271
188
  validator?.cookie?.config.priority,
272
- partitioned: app.config.cookie?.partitioned ?? // @ts-expect-error
189
+ partitioned: defaultCookie?.partitioned ?? // @ts-expect-error
273
190
  validator?.cookie?.config.partitioned,
274
- sameSite: app.config.cookie?.sameSite ?? // @ts-expect-error
191
+ sameSite: defaultCookie?.sameSite ?? // @ts-expect-error
275
192
  validator?.cookie?.config.sameSite,
276
- secure: app.config.cookie?.secure ?? // @ts-expect-error
193
+ secure: defaultCookie?.secure ?? // @ts-expect-error
277
194
  validator?.cookie?.config.secure,
278
- secrets: app.config.cookie?.secrets ?? // @ts-expect-error
195
+ secrets: defaultCookie?.secrets ?? // @ts-expect-error
279
196
  validator?.cookie?.config.secrets,
280
197
  // @ts-expect-error
281
- sign: app.config.cookie?.sign ?? validator?.cookie?.config.sign
198
+ sign: defaultCookie?.sign ?? validator?.cookie?.config.sign
282
199
  }, cookieHeaderValue = request.headers.get("cookie");
283
200
  context.cookie = await parseCookie(
284
201
  context.set,
@@ -286,11 +203,23 @@ const createDynamicHandler = (app) => {
286
203
  cookieMeta
287
204
  );
288
205
  const headerValidator = validator?.createHeaders?.();
289
- headerValidator && injectDefaultValues(headerValidator, context.headers);
206
+ headerValidator?.hasDefault && (context.headers = applySchemaDefaults(
207
+ headerValidator,
208
+ context.headers,
209
+ !0
210
+ ));
290
211
  const paramsValidator = validator?.createParams?.();
291
- paramsValidator && injectDefaultValues(paramsValidator, context.params);
212
+ paramsValidator?.hasDefault && (context.params = applySchemaDefaults(
213
+ paramsValidator,
214
+ context.params,
215
+ !0
216
+ ));
292
217
  const queryValidator = validator?.createQuery?.();
293
- if (queryValidator && injectDefaultValues(queryValidator, context.query), hooks.transform)
218
+ if (queryValidator?.hasDefault && (context.query = applySchemaDefaults(
219
+ queryValidator,
220
+ context.query,
221
+ !0
222
+ )), hooks.transform)
294
223
  for (let i = 0; i < hooks.transform.length; i++) {
295
224
  const hook = hooks.transform[i];
296
225
  let response2 = hook.fn(context);
@@ -299,7 +228,7 @@ const createDynamicHandler = (app) => {
299
228
  if (result)
300
229
  return context.response = result;
301
230
  }
302
- hook.subType === "derive" && Object.assign(context, response2);
231
+ hook.subType === "derive" && safeAssign(context, response2);
303
232
  }
304
233
  if (validator) {
305
234
  if (headerValidator) {
@@ -359,32 +288,34 @@ const createDynamicHandler = (app) => {
359
288
  );
360
289
  validator.query?.Decode && (context.query = validator.query.Decode(context.query));
361
290
  }
362
- if (validator.createCookie?.()) {
291
+ if (cookieValidator) {
363
292
  let cookieValue = {};
364
293
  for (const [key, value] of Object.entries(context.cookie))
365
294
  cookieValue[key] = value.value;
366
- if (validator.cookie.provider === "standard") {
295
+ if (cookieValidator.provider === "standard") {
367
296
  cookieValue = await validateStandardSchema(
368
297
  "cookie",
369
- validator.cookie,
298
+ cookieValidator,
370
299
  cookieValue
371
300
  );
372
301
  for (const key of Object.keys(cookieValue))
373
302
  context.cookie[key].value = cookieValue[key];
374
303
  } else {
375
- if (validator.cookie.Check(cookieValue) === !1)
304
+ if (cookieValidator.Check(cookieValue) === !1)
376
305
  throw new ValidationError(
377
306
  "cookie",
378
- validator.cookie,
307
+ cookieValidator,
379
308
  cookieValue
380
309
  );
381
- validator.cookie?.Decode && (cookieValue = validator.cookie.Decode(
382
- cookieValue
383
- ));
310
+ if (cookieValidator.Decode) {
311
+ cookieValue = cookieValidator.Decode(cookieValue);
312
+ for (const key of Object.keys(cookieValue))
313
+ context.cookie[key].value = cookieValue[key];
314
+ }
384
315
  }
385
316
  }
386
317
  const bodyValidator = validator.createBody?.();
387
- if (bodyValidator?.provider === "standard")
318
+ if (bodyValidator?.hasDefault && (body = applySchemaDefaults(bodyValidator, body), context.body = body), bodyValidator?.provider === "standard")
388
319
  context.body = await validateStandardSchema(
389
320
  "body",
390
321
  bodyValidator,
@@ -409,7 +340,7 @@ const createDynamicHandler = (app) => {
409
340
  return context.response = result;
410
341
  }
411
342
  if (hook.subType === "resolve") {
412
- Object.assign(context, response2);
343
+ safeAssign(context, response2);
413
344
  continue;
414
345
  }
415
346
  if (response2 !== void 0) {
@@ -525,7 +456,9 @@ const createDynamicHandler = (app) => {
525
456
  secret
526
457
  );
527
458
  } else {
528
- const properties = getSchemaProperties(validator?.cookie?.schema);
459
+ const properties = getSchemaProperties(
460
+ validator?.cookie?.schema
461
+ );
529
462
  if (secret)
530
463
  for (const name of cookieMeta.sign)
531
464
  !properties || !(name in properties) || context.set.cookie[name]?.value && (context.set.cookie[name].value = await signCookie(
package/dist/error.d.ts CHANGED
@@ -111,6 +111,12 @@ export declare const mapValueError: (error: ValueError | undefined) => ValueErro
111
111
  * Maximum amount of validation error
112
112
  */
113
113
  export declare const MAX_ERRORS = 64;
114
+ export declare const MAX_VALIDATION_ERROR_DEPTH = 16;
115
+ export declare const MAX_VALIDATION_ERROR_NODES = 8192;
116
+ export declare const MAX_VALIDATION_ERROR_ENTRIES = 4096;
117
+ export declare const MAX_VALIDATION_ERROR_CONTAINER_ENTRIES = 512;
118
+ export declare const MAX_VALIDATION_ERROR_STRING_LENGTH = 4096;
119
+ export declare const MAX_VALIDATION_ERROR_OUTPUT_LENGTH = 65536;
114
120
  export declare class InvalidFileType extends Error {
115
121
  property: string;
116
122
  expected: string | string[];
@@ -178,24 +184,6 @@ export declare class ValidationError extends Error {
178
184
  * })
179
185
  * ```
180
186
  */
181
- detail(message: unknown, allowUnsafeValidatorDetails?: boolean): string | {
182
- type: string;
183
- on: string;
184
- found: unknown;
185
- message: unknown;
186
- property?: undefined;
187
- summary?: undefined;
188
- expected?: undefined;
189
- errors?: undefined;
190
- } | {
191
- type: string;
192
- on: string;
193
- property: string;
194
- message: unknown;
195
- summary: string | undefined;
196
- found: unknown;
197
- expected: unknown;
198
- errors: ValueErrorWithSummary[];
199
- };
187
+ detail(message: unknown, allowUnsafeValidatorDetails?: boolean): unknown;
200
188
  }
201
189
  export {};