elysia 1.4.29 → 1.4.31

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.
@@ -19,75 +19,20 @@ __export(dynamic_handle_exports, {
19
19
  createDynamicHandler: () => createDynamicHandler
20
20
  });
21
21
  module.exports = __toCommonJS(dynamic_handle_exports);
22
- var import_value = require("@sinclair/typebox/value"), import_cookies = require('./cookies.js'), import_error = require('./error.js'), import_parse_query = require('./parse-query.js'), import_schema = require('./schema.js'), import_utils = require('./utils.js');
23
- const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), isDangerousKey = (key) => {
24
- if (DANGEROUS_KEYS.has(key)) return !0;
25
- const match = key.match(ARRAY_INDEX_REGEX);
26
- return match ? DANGEROUS_KEYS.has(match[1]) : !1;
27
- }, parseArrayKey = (key) => {
28
- const match = key.match(ARRAY_INDEX_REGEX);
29
- return match ? {
30
- name: match[1],
31
- index: parseInt(match[2], 10)
32
- } : null;
33
- }, parseObjectString = (entry) => {
34
- if (!(typeof entry != "string" || entry.charCodeAt(0) !== 123))
35
- try {
36
- const parsed = JSON.parse(entry);
37
- if (parsed && typeof parsed == "object" && !Array.isArray(parsed))
38
- return parsed;
39
- } catch {
40
- return;
41
- }
42
- }, setNestedValue = (obj, path, value) => {
43
- const keys = path.split("."), lastKey = keys.pop();
44
- if (isDangerousKey(lastKey) || keys.some(isDangerousKey)) return;
45
- let current = obj;
46
- for (const key of keys) {
47
- const arrayInfo2 = parseArrayKey(key);
48
- if (arrayInfo2) {
49
- Array.isArray(current[arrayInfo2.name]) || (current[arrayInfo2.name] = []);
50
- const existing = current[arrayInfo2.name][arrayInfo2.index], isFile = typeof File < "u" && existing instanceof File;
51
- (!existing || typeof existing != "object" || Array.isArray(existing) || isFile) && (current[arrayInfo2.name][arrayInfo2.index] = parseObjectString(existing) ?? {}), current = current[arrayInfo2.name][arrayInfo2.index];
52
- } else
53
- (!current[key] || typeof current[key] != "object") && (current[key] = {}), current = current[key];
54
- }
55
- const arrayInfo = parseArrayKey(lastKey);
56
- arrayInfo ? (Array.isArray(current[arrayInfo.name]) || (current[arrayInfo.name] = []), current[arrayInfo.name][arrayInfo.index] = value) : current[lastKey] = value;
57
- }, normalizeFormValue = (value) => {
58
- if (value.length === 1) {
59
- const stringValue2 = value[0];
60
- if (typeof stringValue2 == "string" && (stringValue2.charCodeAt(0) === 123 || stringValue2.charCodeAt(0) === 91))
61
- try {
62
- const parsed2 = JSON.parse(stringValue2);
63
- if (parsed2 && typeof parsed2 == "object")
64
- return parsed2;
65
- } catch {
66
- }
67
- return value[0];
68
- }
69
- const stringValue = value.find(
70
- (entry) => typeof entry == "string"
71
- );
72
- if (!stringValue || typeof File > "u") return value;
73
- const files = value.filter((entry) => entry instanceof File);
74
- if (!files.length || stringValue.charCodeAt(0) !== 123) return value;
75
- let parsed;
76
- try {
77
- parsed = JSON.parse(stringValue);
78
- } catch {
79
- return value;
80
- }
81
- 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);
82
- }, injectDefaultValues = (typeChecker, obj) => {
83
- let schema = typeChecker.schema;
84
- if (!schema) return;
85
- schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]);
86
- const properties = (0, import_schema.getSchemaProperties)(schema);
87
- if (properties)
88
- for (const [key, keySchema] of Object.entries(properties))
89
- obj[key] ??= keySchema.default;
90
- }, createDynamicHandler = (app) => {
22
+ var import_value = require("@sinclair/typebox/value"), import_cookies = require('./cookies.js'), import_error = require('./error.js'), import_parse_query = require('./parse-query.js'), import_form_data = require('./form-data.js'), import_schema = require('./schema.js'), import_utils = require('./utils.js');
23
+ async function validateStandardSchema(type, validator, value) {
24
+ const result = await validator.Validate(value);
25
+ if (result.issues)
26
+ throw new import_error.ValidationError(
27
+ type,
28
+ validator,
29
+ value,
30
+ !1,
31
+ result.issues
32
+ );
33
+ return result.value;
34
+ }
35
+ const createDynamicHandler = (app) => {
91
36
  const { mapResponse, mapEarlyResponse } = app["~adapter"].handler, defaultHeader = app.setHeaders;
92
37
  return async (request) => {
93
38
  const url = request.url, s = url.indexOf("/", 11), qi = url.indexOf("?", s + 1), path = qi === -1 ? url.substring(s) : url.substring(s, qi), set = {
@@ -122,10 +67,10 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
122
67
  if (!handler)
123
68
  throw context.query = qi === -1 ? {} : (0, import_parse_query.parseQuery)(url.substring(qi + 1)), new import_error.NotFoundError();
124
69
  const { handle, validator, content, route } = handler.store;
125
- if (hooks = handler.store.hooks, hooks.config?.mount)
126
- return await hooks.config.mount(request);
70
+ hooks = handler.store.hooks;
71
+ const isMount = !!hooks.config?.mount;
127
72
  let body;
128
- if (request.method !== "GET" && request.method !== "HEAD")
73
+ if (!isMount && request.method !== "GET" && request.method !== "HEAD")
129
74
  if (content)
130
75
  switch (content) {
131
76
  case "application/json":
@@ -141,17 +86,7 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
141
86
  body = await request.arrayBuffer();
142
87
  break;
143
88
  case "multipart/form-data": {
144
- body = {};
145
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
146
- form.forEach((v, k) => {
147
- const list = grouped.get(k);
148
- list ? list.push(v) : grouped.set(k, [v]);
149
- });
150
- for (const [key, value] of grouped) {
151
- if (body[key]) continue;
152
- const finalValue = normalizeFormValue(value);
153
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
154
- }
89
+ body = (0, import_form_data.parseFormData)(await request.formData());
155
90
  break;
156
91
  }
157
92
  }
@@ -184,17 +119,9 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
184
119
  break;
185
120
  case "formdata":
186
121
  case "multipart/form-data": {
187
- body = {};
188
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
189
- form.forEach((v, k) => {
190
- const list = grouped.get(k);
191
- list ? list.push(v) : grouped.set(k, [v]);
192
- });
193
- for (const [key, value] of grouped) {
194
- if (body[key]) continue;
195
- const finalValue = normalizeFormValue(value);
196
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
197
- }
122
+ body = (0, import_form_data.parseFormData)(
123
+ await request.formData()
124
+ );
198
125
  break;
199
126
  }
200
127
  default: {
@@ -235,17 +162,9 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
235
162
  body = await request.arrayBuffer();
236
163
  break;
237
164
  case "multipart/form-data": {
238
- body = {};
239
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
240
- form.forEach((v, k) => {
241
- const list = grouped.get(k);
242
- list ? list.push(v) : grouped.set(k, [v]);
243
- });
244
- for (const [key, value] of grouped) {
245
- if (body[key]) continue;
246
- const finalValue = normalizeFormValue(value);
247
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
248
- }
165
+ body = (0, import_form_data.parseFormData)(
166
+ await request.formData()
167
+ );
249
168
  break;
250
169
  }
251
170
  }
@@ -254,29 +173,29 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
254
173
  context.route = route, context.body = body, context.params = handler?.params || void 0, context.query = qi === -1 ? {} : (0, import_parse_query.parseQuery)(url.substring(qi + 1)), context.headers = {};
255
174
  for (const [key, value] of request.headers.entries())
256
175
  context.headers[key] = value;
257
- const cookieMeta = {
258
- domain: app.config.cookie?.domain ?? // @ts-expect-error
176
+ const cookieValidator = validator?.createCookie?.(), defaultCookie = hooks.config?.cookie ? (0, import_utils.mergeCookie)(app.config.cookie ?? {}, hooks.config.cookie) : app.config.cookie, cookieMeta = {
177
+ domain: defaultCookie?.domain ?? // @ts-expect-error
259
178
  validator?.cookie?.config.domain,
260
- expires: app.config.cookie?.expires ?? // @ts-expect-error
179
+ expires: defaultCookie?.expires ?? // @ts-expect-error
261
180
  validator?.cookie?.config.expires,
262
- httpOnly: app.config.cookie?.httpOnly ?? // @ts-expect-error
181
+ httpOnly: defaultCookie?.httpOnly ?? // @ts-expect-error
263
182
  validator?.cookie?.config.httpOnly,
264
- maxAge: app.config.cookie?.maxAge ?? // @ts-expect-error
183
+ maxAge: defaultCookie?.maxAge ?? // @ts-expect-error
265
184
  validator?.cookie?.config.maxAge,
266
185
  // @ts-expect-error
267
- path: app.config.cookie?.path ?? validator?.cookie?.config.path,
268
- priority: app.config.cookie?.priority ?? // @ts-expect-error
186
+ path: defaultCookie?.path ?? validator?.cookie?.config.path,
187
+ priority: defaultCookie?.priority ?? // @ts-expect-error
269
188
  validator?.cookie?.config.priority,
270
- partitioned: app.config.cookie?.partitioned ?? // @ts-expect-error
189
+ partitioned: defaultCookie?.partitioned ?? // @ts-expect-error
271
190
  validator?.cookie?.config.partitioned,
272
- sameSite: app.config.cookie?.sameSite ?? // @ts-expect-error
191
+ sameSite: defaultCookie?.sameSite ?? // @ts-expect-error
273
192
  validator?.cookie?.config.sameSite,
274
- secure: app.config.cookie?.secure ?? // @ts-expect-error
193
+ secure: defaultCookie?.secure ?? // @ts-expect-error
275
194
  validator?.cookie?.config.secure,
276
- secrets: app.config.cookie?.secrets ?? // @ts-expect-error
195
+ secrets: defaultCookie?.secrets ?? // @ts-expect-error
277
196
  validator?.cookie?.config.secrets,
278
197
  // @ts-expect-error
279
- sign: app.config.cookie?.sign ?? validator?.cookie?.config.sign
198
+ sign: defaultCookie?.sign ?? validator?.cookie?.config.sign
280
199
  }, cookieHeaderValue = request.headers.get("cookie");
281
200
  context.cookie = await (0, import_cookies.parseCookie)(
282
201
  context.set,
@@ -284,11 +203,23 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
284
203
  cookieMeta
285
204
  );
286
205
  const headerValidator = validator?.createHeaders?.();
287
- headerValidator && injectDefaultValues(headerValidator, context.headers);
206
+ headerValidator?.hasDefault && (context.headers = (0, import_schema.applySchemaDefaults)(
207
+ headerValidator,
208
+ context.headers,
209
+ !0
210
+ ));
288
211
  const paramsValidator = validator?.createParams?.();
289
- paramsValidator && injectDefaultValues(paramsValidator, context.params);
212
+ paramsValidator?.hasDefault && (context.params = (0, import_schema.applySchemaDefaults)(
213
+ paramsValidator,
214
+ context.params,
215
+ !0
216
+ ));
290
217
  const queryValidator = validator?.createQuery?.();
291
- if (queryValidator && injectDefaultValues(queryValidator, context.query), hooks.transform)
218
+ if (queryValidator?.hasDefault && (context.query = (0, import_schema.applySchemaDefaults)(
219
+ queryValidator,
220
+ context.query,
221
+ !0
222
+ )), hooks.transform)
292
223
  for (let i = 0; i < hooks.transform.length; i++) {
293
224
  const hook = hooks.transform[i];
294
225
  let response2 = hook.fn(context);
@@ -297,27 +228,42 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
297
228
  if (result)
298
229
  return context.response = result;
299
230
  }
300
- hook.subType === "derive" && Object.assign(context, response2);
231
+ hook.subType === "derive" && (0, import_utils.safeAssign)(context, response2);
301
232
  }
302
233
  if (validator) {
303
234
  if (headerValidator) {
304
235
  const _header = structuredClone(context.headers);
305
236
  for (const [key, value] of request.headers)
306
237
  _header[key] = value;
307
- if (validator.headers.Check(_header) === !1)
238
+ if (headerValidator.provider === "standard")
239
+ context.headers = await validateStandardSchema(
240
+ "header",
241
+ headerValidator,
242
+ _header
243
+ );
244
+ else if (validator.headers.Check(_header) === !1)
308
245
  throw new import_error.ValidationError(
309
246
  "header",
310
247
  validator.headers,
311
248
  _header
312
249
  );
313
250
  } else validator.headers?.Decode && (context.headers = validator.headers.Decode(context.headers));
314
- if (paramsValidator?.Check(context.params) === !1)
315
- throw new import_error.ValidationError(
251
+ if (paramsValidator?.provider === "standard")
252
+ context.params = await validateStandardSchema(
316
253
  "params",
317
- validator.params,
254
+ paramsValidator,
318
255
  context.params
319
256
  );
320
- if (validator.params?.Decode && (context.params = validator.params.Decode(context.params)), validator.query?.schema) {
257
+ else {
258
+ if (paramsValidator?.Check(context.params) === !1)
259
+ throw new import_error.ValidationError(
260
+ "params",
261
+ validator.params,
262
+ context.params
263
+ );
264
+ validator.params?.Decode && (context.params = validator.params.Decode(context.params));
265
+ }
266
+ if (validator.query?.schema) {
321
267
  let schema = validator.query.schema;
322
268
  schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]);
323
269
  const properties = (0, import_schema.getSchemaProperties)(schema);
@@ -327,31 +273,61 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
327
273
  (value.type === "array" || value.items?.type === "string") && typeof context.query[property] == "string" && context.query[property] && (context.query[property] = context.query[property].split(","));
328
274
  }
329
275
  }
330
- if (queryValidator?.Check(context.query) === !1)
331
- throw new import_error.ValidationError(
276
+ if (queryValidator?.provider === "standard")
277
+ context.query = await validateStandardSchema(
332
278
  "query",
333
- validator.query,
279
+ queryValidator,
334
280
  context.query
335
281
  );
336
- if (validator.query?.Decode && (context.query = validator.query.Decode(context.query)), validator.createCookie?.()) {
282
+ else {
283
+ if (queryValidator?.Check(context.query) === !1)
284
+ throw new import_error.ValidationError(
285
+ "query",
286
+ validator.query,
287
+ context.query
288
+ );
289
+ validator.query?.Decode && (context.query = validator.query.Decode(context.query));
290
+ }
291
+ if (cookieValidator) {
337
292
  let cookieValue = {};
338
293
  for (const [key, value] of Object.entries(context.cookie))
339
294
  cookieValue[key] = value.value;
340
- if (validator.cookie.Check(cookieValue) === !1)
341
- throw new import_error.ValidationError(
295
+ if (cookieValidator.provider === "standard") {
296
+ cookieValue = await validateStandardSchema(
342
297
  "cookie",
343
- validator.cookie,
298
+ cookieValidator,
344
299
  cookieValue
345
300
  );
346
- validator.cookie?.Decode && (cookieValue = validator.cookie.Decode(
347
- cookieValue
348
- ));
301
+ for (const key of Object.keys(cookieValue))
302
+ context.cookie[key].value = cookieValue[key];
303
+ } else {
304
+ if (cookieValidator.Check(cookieValue) === !1)
305
+ throw new import_error.ValidationError(
306
+ "cookie",
307
+ cookieValidator,
308
+ cookieValue
309
+ );
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
+ }
315
+ }
349
316
  }
350
- if (validator.createBody?.()?.Check(body) === !1)
351
- throw new import_error.ValidationError("body", validator.body, body);
352
- if (validator.body?.Decode) {
353
- let decoded = validator.body.Decode(body);
354
- decoded instanceof Promise && (decoded = await decoded), context.body = decoded?.value ?? decoded;
317
+ const bodyValidator = validator.createBody?.();
318
+ if (bodyValidator?.hasDefault && (body = (0, import_schema.applySchemaDefaults)(bodyValidator, body), context.body = body), bodyValidator?.provider === "standard")
319
+ context.body = await validateStandardSchema(
320
+ "body",
321
+ bodyValidator,
322
+ body
323
+ );
324
+ else {
325
+ if (bodyValidator?.Check(body) === !1)
326
+ throw new import_error.ValidationError("body", validator.body, body);
327
+ if (validator.body?.Decode) {
328
+ let decoded = validator.body.Decode(body);
329
+ decoded instanceof Promise && (decoded = await decoded), context.body = decoded?.value ?? decoded;
330
+ }
355
331
  }
356
332
  }
357
333
  if (hooks.beforeHandle)
@@ -364,7 +340,7 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
364
340
  return context.response = result;
365
341
  }
366
342
  if (hook.subType === "resolve") {
367
- Object.assign(context, response2);
343
+ (0, import_utils.safeAssign)(context, response2);
368
344
  continue;
369
345
  }
370
346
  if (response2 !== void 0) {
@@ -390,7 +366,13 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
390
366
  const isCustomStatuResponse = response2 instanceof import_error.ElysiaCustomStatusResponse, status2 = isCustomStatuResponse ? response2.code : set.status ? typeof set.status == "string" ? import_utils.StatusMap[set.status] : set.status : 200;
391
367
  isCustomStatuResponse && (set.status = status2, response2 = response2.response);
392
368
  const responseValidator = validator?.createResponse?.()?.[status2];
393
- if (responseValidator?.Check(response2) === !1)
369
+ if (responseValidator?.provider === "standard")
370
+ response2 = await validateStandardSchema(
371
+ "response",
372
+ responseValidator,
373
+ response2
374
+ );
375
+ else if (responseValidator?.Check(response2) === !1)
394
376
  if (responseValidator?.Clean)
395
377
  try {
396
378
  const temp = responseValidator.Clean(response2);
@@ -426,7 +408,13 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
426
408
  const isCustomStatuResponse = response instanceof import_error.ElysiaCustomStatusResponse, status2 = isCustomStatuResponse ? response.code : set.status ? typeof set.status == "string" ? import_utils.StatusMap[set.status] : set.status : 200;
427
409
  isCustomStatuResponse && (set.status = status2, response = response.response);
428
410
  const responseValidator = validator?.createResponse?.()?.[status2];
429
- if (responseValidator?.Check(response) === !1)
411
+ if (responseValidator?.provider === "standard")
412
+ response = await validateStandardSchema(
413
+ "response",
414
+ responseValidator,
415
+ response
416
+ );
417
+ else if (responseValidator?.Check(response) === !1)
430
418
  if (responseValidator?.Clean)
431
419
  try {
432
420
  const temp = responseValidator.Clean(response);
@@ -468,7 +456,9 @@ const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ ne
468
456
  secret
469
457
  );
470
458
  } else {
471
- const properties = (0, import_schema.getSchemaProperties)(validator?.cookie?.schema);
459
+ const properties = (0, import_schema.getSchemaProperties)(
460
+ validator?.cookie?.schema
461
+ );
472
462
  if (secret)
473
463
  for (const name of cookieMeta.sign)
474
464
  !properties || !(name in properties) || context.set.cookie[name]?.value && (context.set.cookie[name].value = await (0, import_utils.signCookie)(