@contember/engine-http 2.2.0-alpha.18 → 2.2.0-alpha.19

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 (141) hide show
  1. package/dist/development/index.cjs +0 -1
  2. package/dist/development/index.cjs.map +1 -1
  3. package/dist/development/index.js +1 -2
  4. package/dist/development/src/application/application.cjs +8 -9
  5. package/dist/development/src/application/application.cjs.map +1 -1
  6. package/dist/development/src/application/application.js +8 -9
  7. package/dist/development/src/application/application.js.map +1 -1
  8. package/dist/development/src/application/compression.cjs +99 -0
  9. package/dist/development/src/application/compression.cjs.map +1 -0
  10. package/dist/development/src/application/compression.js +82 -0
  11. package/dist/development/src/application/compression.js.map +1 -0
  12. package/dist/development/src/application/cors.cjs +52 -0
  13. package/dist/development/src/application/cors.cjs.map +1 -0
  14. package/dist/development/src/application/cors.js +52 -0
  15. package/dist/development/src/application/cors.js.map +1 -0
  16. package/dist/development/src/application/requestBody.cjs +242 -0
  17. package/dist/development/src/application/requestBody.cjs.map +1 -0
  18. package/dist/development/src/application/requestBody.js +242 -0
  19. package/dist/development/src/application/requestBody.js.map +1 -0
  20. package/dist/development/src/config/configSchema.cjs +8 -1
  21. package/dist/development/src/config/configSchema.cjs.map +1 -1
  22. package/dist/development/src/config/configSchema.js +8 -1
  23. package/dist/development/src/config/configSchema.js.map +1 -1
  24. package/dist/development/src/graphql/execution.cjs +3 -9
  25. package/dist/development/src/graphql/execution.cjs.map +1 -1
  26. package/dist/development/src/graphql/execution.js +3 -9
  27. package/dist/development/src/graphql/execution.js.map +1 -1
  28. package/dist/development/src/project/ProjectContainer.cjs +1 -1
  29. package/dist/development/src/project/ProjectContainer.js +1 -1
  30. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +1 -1
  31. package/dist/development/src/projectGroup/ProjectGroupContainer.js +1 -1
  32. package/dist/development/src/providers.cjs +2 -2
  33. package/dist/development/src/providers.cjs.map +1 -1
  34. package/dist/development/src/providers.js +2 -2
  35. package/dist/development/src/providers.js.map +1 -1
  36. package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
  37. package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
  38. package/dist/development/src/transfer/ImportExecutor.cjs +18 -3
  39. package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
  40. package/dist/development/src/transfer/ImportExecutor.js +18 -3
  41. package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
  42. package/dist/development/src/utils/sentry.cjs +31 -49
  43. package/dist/development/src/utils/sentry.cjs.map +1 -1
  44. package/dist/development/src/utils/sentry.js +32 -33
  45. package/dist/development/src/utils/sentry.js.map +1 -1
  46. package/dist/development/src/utils/serverStartup.cjs +5 -3
  47. package/dist/development/src/utils/serverStartup.cjs.map +1 -1
  48. package/dist/development/src/utils/serverStartup.js +5 -3
  49. package/dist/development/src/utils/serverStartup.js.map +1 -1
  50. package/dist/production/index.cjs +0 -1
  51. package/dist/production/index.cjs.map +1 -1
  52. package/dist/production/index.js +1 -2
  53. package/dist/production/src/application/application.cjs +8 -9
  54. package/dist/production/src/application/application.cjs.map +1 -1
  55. package/dist/production/src/application/application.js +8 -9
  56. package/dist/production/src/application/application.js.map +1 -1
  57. package/dist/production/src/application/compression.cjs +99 -0
  58. package/dist/production/src/application/compression.cjs.map +1 -0
  59. package/dist/production/src/application/compression.js +82 -0
  60. package/dist/production/src/application/compression.js.map +1 -0
  61. package/dist/production/src/application/cors.cjs +52 -0
  62. package/dist/production/src/application/cors.cjs.map +1 -0
  63. package/dist/production/src/application/cors.js +52 -0
  64. package/dist/production/src/application/cors.js.map +1 -0
  65. package/dist/production/src/application/requestBody.cjs +242 -0
  66. package/dist/production/src/application/requestBody.cjs.map +1 -0
  67. package/dist/production/src/application/requestBody.js +242 -0
  68. package/dist/production/src/application/requestBody.js.map +1 -0
  69. package/dist/production/src/config/configSchema.cjs +8 -1
  70. package/dist/production/src/config/configSchema.cjs.map +1 -1
  71. package/dist/production/src/config/configSchema.js +8 -1
  72. package/dist/production/src/config/configSchema.js.map +1 -1
  73. package/dist/production/src/graphql/execution.cjs +3 -9
  74. package/dist/production/src/graphql/execution.cjs.map +1 -1
  75. package/dist/production/src/graphql/execution.js +3 -9
  76. package/dist/production/src/graphql/execution.js.map +1 -1
  77. package/dist/production/src/project/ProjectContainer.cjs +1 -1
  78. package/dist/production/src/project/ProjectContainer.js +1 -1
  79. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +1 -1
  80. package/dist/production/src/projectGroup/ProjectGroupContainer.js +1 -1
  81. package/dist/production/src/providers.cjs +2 -2
  82. package/dist/production/src/providers.cjs.map +1 -1
  83. package/dist/production/src/providers.js +2 -2
  84. package/dist/production/src/providers.js.map +1 -1
  85. package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
  86. package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
  87. package/dist/production/src/transfer/ImportExecutor.cjs +18 -3
  88. package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
  89. package/dist/production/src/transfer/ImportExecutor.js +18 -3
  90. package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
  91. package/dist/production/src/utils/sentry.cjs +31 -49
  92. package/dist/production/src/utils/sentry.cjs.map +1 -1
  93. package/dist/production/src/utils/sentry.js +32 -33
  94. package/dist/production/src/utils/sentry.js.map +1 -1
  95. package/dist/production/src/utils/serverStartup.cjs +5 -3
  96. package/dist/production/src/utils/serverStartup.cjs.map +1 -1
  97. package/dist/production/src/utils/serverStartup.js +5 -3
  98. package/dist/production/src/utils/serverStartup.js.map +1 -1
  99. package/dist/tests/cases/unit/compression.test.d.ts +2 -0
  100. package/dist/tests/cases/unit/compression.test.d.ts.map +1 -0
  101. package/dist/tests/cases/unit/cors.test.d.ts +2 -0
  102. package/dist/tests/cases/unit/cors.test.d.ts.map +1 -0
  103. package/dist/tests/cases/unit/requestBody.test.d.ts +2 -0
  104. package/dist/tests/cases/unit/requestBody.test.d.ts.map +1 -0
  105. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  106. package/dist/types/MasterContainer.d.ts +1 -1
  107. package/dist/types/application/application.d.ts.map +1 -1
  108. package/dist/types/application/compression.d.ts +19 -0
  109. package/dist/types/application/compression.d.ts.map +1 -0
  110. package/dist/types/application/cors.d.ts +10 -0
  111. package/dist/types/application/cors.d.ts.map +1 -0
  112. package/dist/types/application/requestBody.d.ts +45 -0
  113. package/dist/types/application/requestBody.d.ts.map +1 -0
  114. package/dist/types/config/configSchema.d.ts +3 -3
  115. package/dist/types/config/configSchema.d.ts.map +1 -1
  116. package/dist/types/graphql/execution.d.ts.map +1 -1
  117. package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
  118. package/dist/types/tsconfig.tsbuildinfo +1 -1
  119. package/dist/types/utils/sentry.d.ts +13 -6
  120. package/dist/types/utils/sentry.d.ts.map +1 -1
  121. package/dist/types/utils/serverStartup.d.ts.map +1 -1
  122. package/package.json +18 -24
  123. package/src/application/application.ts +8 -9
  124. package/src/application/compression.ts +118 -0
  125. package/src/application/cors.ts +61 -0
  126. package/src/application/requestBody.ts +295 -0
  127. package/src/config/configSchema.ts +8 -1
  128. package/src/graphql/execution.ts +3 -9
  129. package/src/providers.ts +2 -2
  130. package/src/transfer/ImportExecutor.ts +21 -3
  131. package/src/tsconfig.json +3 -1
  132. package/src/utils/sentry.ts +42 -39
  133. package/src/utils/serverStartup.ts +7 -5
  134. package/tests/cases/unit/compression.test.ts +172 -0
  135. package/tests/cases/unit/cors.test.ts +106 -0
  136. package/tests/cases/unit/requestBody.test.ts +333 -0
  137. package/tests/cases/unit/sentryLoggerHandler.test.ts +74 -20
  138. package/tests/cases/unit/serverConfig.test.ts +19 -0
  139. package/dist/tests/cases/unit/sentryIntegrations.test.d.ts +0 -2
  140. package/dist/tests/cases/unit/sentryIntegrations.test.d.ts.map +0 -1
  141. package/tests/cases/unit/sentryIntegrations.test.ts +0 -15
@@ -0,0 +1,82 @@
1
+ import { Stream } from "node:stream";
2
+ import * as zlib from "node:zlib";
3
+ const compressors = {
4
+ zstd: () => zlib.createZstdCompress(),
5
+ gzip: () => zlib.createGzip(),
6
+ deflate: () => zlib.createDeflate()
7
+ };
8
+ const offeredEncodings = typeof zlib.createZstdCompress === "function" ? ["zstd", "gzip", "deflate"] : ["gzip", "deflate"];
9
+ const parseAcceptEncoding = (header) => header.split(",").flatMap((item) => {
10
+ const match = /^\s*([^\s;]+)\s*(?:;(.*))?$/.exec(item.trim());
11
+ if (!match) {
12
+ return [];
13
+ }
14
+ const qualityParameter = (match[2] ?? "").split(";").map((it) => it.trim().split("=")).find(([name]) => name === "q");
15
+ const quality = qualityParameter ? Number.parseFloat(qualityParameter[1]) : 1;
16
+ return [{ name: match[1].toLowerCase(), quality: Number.isNaN(quality) ? 0 : quality }];
17
+ });
18
+ const negotiateEncoding = (header) => {
19
+ if (header === "") {
20
+ return void 0;
21
+ }
22
+ if (header === "*") {
23
+ return "gzip";
24
+ }
25
+ const accepted = parseAcceptEncoding(header);
26
+ const quality = (name) => {
27
+ const exact = accepted.filter((it) => it.name === name);
28
+ const matching = exact.length > 0 ? exact : accepted.filter((it) => it.name === "*");
29
+ return matching.length > 0 ? Math.max(...matching.map((it) => it.quality)) : void 0;
30
+ };
31
+ const identityQuality = quality("identity") ?? Math.min(1, ...accepted.map((it) => it.quality || 1));
32
+ let best = { encoding: void 0, quality: identityQuality > 0 ? identityQuality : 0 };
33
+ for (const encoding of offeredEncodings) {
34
+ const encodingQuality = quality(encoding) ?? 0;
35
+ if (encodingQuality > 0 && (encodingQuality > best.quality || encodingQuality === best.quality && best.encoding === void 0)) {
36
+ best = { encoding, quality: encodingQuality };
37
+ }
38
+ }
39
+ return best.encoding;
40
+ };
41
+ const compressibleTypes = /* @__PURE__ */ new Set(["application/json", "application/javascript", "application/xml", "application/wasm"]);
42
+ const isCompressibleType = (type) => {
43
+ const normalized = type.toLowerCase();
44
+ return compressibleTypes.has(normalized) || /^text\/|\+(?:json|text|xml)$/.test(normalized);
45
+ };
46
+ const threshold = 1024;
47
+ const emptyBodyStatuses = /* @__PURE__ */ new Set([204, 205, 304]);
48
+ const noTransform = /(?:^|,)\s*?no-transform\s*?(?:,|$)/;
49
+ const shouldCompress = (ctx) => {
50
+ const response = ctx.response;
51
+ if (!ctx.body || ctx.res.headersSent || !ctx.writable || ctx.compress === false || ctx.method === "HEAD" || emptyBodyStatuses.has(response.status) || response.get("Content-Encoding") || !(ctx.compress === true || isCompressibleType(response.type)) || noTransform.test(response.get("Cache-Control"))) {
52
+ return false;
53
+ }
54
+ return response.length === void 0 || response.length >= threshold;
55
+ };
56
+ const createCompressionMiddleware = () => async (ctx, next) => {
57
+ ctx.vary("Accept-Encoding");
58
+ await next();
59
+ if (!shouldCompress(ctx)) {
60
+ return;
61
+ }
62
+ const encoding = negotiateEncoding(ctx.get("Accept-Encoding"));
63
+ if (encoding === void 0) {
64
+ return;
65
+ }
66
+ const body = ctx.body;
67
+ const compressed = compressors[encoding]();
68
+ ctx.set("Content-Encoding", encoding);
69
+ ctx.res.removeHeader("Content-Length");
70
+ ctx.body = compressed;
71
+ if (body instanceof Stream) {
72
+ body.pipe(compressed);
73
+ } else {
74
+ compressed.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body));
75
+ }
76
+ };
77
+ export {
78
+ createCompressionMiddleware,
79
+ isCompressibleType,
80
+ negotiateEncoding
81
+ };
82
+ //# sourceMappingURL=compression.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compression.js","sources":["../../../../../packages/engine-http/src/application/compression.ts"],"sourcesContent":["import { Stream, Transform } from 'node:stream'\nimport * as zlib from 'node:zlib'\nimport type * as Koa from 'koa'\n\ndeclare module 'koa' {\n\tinterface DefaultContext {\n\t\t/** `true` compresses a response whose type is not compressible by default, `false` never compresses it. */\n\t\tcompress?: boolean\n\t}\n}\n\ntype Encoding = 'zstd' | 'gzip' | 'deflate'\n\nconst compressors: Readonly<Record<Encoding, () => Transform>> = {\n\tzstd: () => zlib.createZstdCompress(),\n\tgzip: () => zlib.createGzip(),\n\tdeflate: () => zlib.createDeflate(),\n}\n\n// zstd needs Node 22.15 or 23.8; a tie in quality goes to the first listed. Brotli stays off, as it was.\nconst offeredEncodings: readonly Encoding[] = typeof zlib.createZstdCompress === 'function' ? ['zstd', 'gzip', 'deflate'] : ['gzip', 'deflate']\n\ntype AcceptedEncoding = { readonly name: string; readonly quality: number }\n\nconst parseAcceptEncoding = (header: string): AcceptedEncoding[] =>\n\theader.split(',').flatMap(item => {\n\t\tconst match = /^\\s*([^\\s;]+)\\s*(?:;(.*))?$/.exec(item.trim())\n\t\tif (!match) {\n\t\t\treturn []\n\t\t}\n\t\tconst qualityParameter = (match[2] ?? '').split(';').map(it => it.trim().split('=')).find(([name]) => name === 'q')\n\t\tconst quality = qualityParameter ? Number.parseFloat(qualityParameter[1]) : 1\n\t\treturn [{ name: match[1].toLowerCase(), quality: Number.isNaN(quality) ? 0 : quality }]\n\t})\n\n/**\n * The best encoding the client accepts (RFC 9110 §12.5.3), or `undefined` for identity. An exact entry outranks `*`,\n * and identity, unless listed, is acceptable at the lowest quality given. No header means identity, a bare `*` gzip.\n */\nexport const negotiateEncoding = (header: string): Encoding | undefined => {\n\tif (header === '') {\n\t\treturn undefined\n\t}\n\tif (header === '*') {\n\t\treturn 'gzip'\n\t}\n\tconst accepted = parseAcceptEncoding(header)\n\tconst quality = (name: string): number | undefined => {\n\t\tconst exact = accepted.filter(it => it.name === name)\n\t\tconst matching = exact.length > 0 ? exact : accepted.filter(it => it.name === '*')\n\t\treturn matching.length > 0 ? Math.max(...matching.map(it => it.quality)) : undefined\n\t}\n\tconst identityQuality = quality('identity') ?? Math.min(1, ...accepted.map(it => it.quality || 1))\n\tlet best: { encoding: Encoding | undefined; quality: number } = { encoding: undefined, quality: identityQuality > 0 ? identityQuality : 0 }\n\tfor (const encoding of offeredEncodings) {\n\t\tconst encodingQuality = quality(encoding) ?? 0\n\t\t// identity is the last preference, so an encoding wins a tie with it\n\t\tif (encodingQuality > 0 && (encodingQuality > best.quality || (encodingQuality === best.quality && best.encoding === undefined))) {\n\t\t\tbest = { encoding, quality: encodingQuality }\n\t\t}\n\t}\n\treturn best.encoding\n}\n\nconst compressibleTypes: ReadonlySet<string> = new Set(['application/json', 'application/javascript', 'application/xml', 'application/wasm'])\n\n/** The media types the engine serves as text: JSON, HTML, plain text, scripts, styles, SVG. */\nexport const isCompressibleType = (type: string): boolean => {\n\tconst normalized = type.toLowerCase()\n\treturn compressibleTypes.has(normalized) || /^text\\/|\\+(?:json|text|xml)$/.test(normalized)\n}\n\nconst threshold = 1024\nconst emptyBodyStatuses: ReadonlySet<number> = new Set([204, 205, 304])\nconst noTransform = /(?:^|,)\\s*?no-transform\\s*?(?:,|$)/\n\nconst shouldCompress = (ctx: Koa.Context): boolean => {\n\tconst response = ctx.response\n\tif (\n\t\t!ctx.body\n\t\t|| ctx.res.headersSent\n\t\t|| !ctx.writable\n\t\t|| ctx.compress === false\n\t\t|| ctx.method === 'HEAD'\n\t\t|| emptyBodyStatuses.has(response.status)\n\t\t|| response.get('Content-Encoding')\n\t\t|| !(ctx.compress === true || isCompressibleType(response.type))\n\t\t|| noTransform.test(response.get('Cache-Control'))\n\t) {\n\t\treturn false\n\t}\n\t// a stream has no known length and is always compressed\n\treturn response.length === undefined || response.length >= threshold\n}\n\n/** Compresses responses of 1 KiB and more, or of unknown length, with zstd, gzip or deflate, as the client accepts. */\nexport const createCompressionMiddleware = (): Koa.Middleware => async (ctx, next) => {\n\tctx.vary('Accept-Encoding')\n\tawait next()\n\n\tif (!shouldCompress(ctx)) {\n\t\treturn\n\t}\n\tconst encoding = negotiateEncoding(ctx.get('Accept-Encoding'))\n\tif (encoding === undefined) {\n\t\treturn\n\t}\n\tconst body: unknown = ctx.body\n\tconst compressed = compressors[encoding]()\n\tctx.set('Content-Encoding', encoding)\n\tctx.res.removeHeader('Content-Length')\n\tctx.body = compressed\n\tif (body instanceof Stream) {\n\t\tb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MAAI,KAAK,iBAAiB;AAC1B,QAAM,KAAA;AAEN,MAAI,CAAC,eAAe,GAAG,GAAG;AACzB;AAAA,EACD;AACA,QAAM,WAAW,kBAAkB,IAAI,IAAI,iBAAiB,CAAC;AAC7D,MAAI,aAAa,QAAW;AAC3B;AAAA,EACD;AACA,QAAM,OAAgB,IAAI;AAC1B,QAAM,aAAa,YAAY,QAAQ,EAAA;AACvC,MAAI,IAAI,oBAAoB,QAAQ;AACpC,MAAI,IAAI,aAAa,gBAAgB;AACrC,MAAI,OAAO;AACX,MAAI,gBAAgB,QAAQ;AAC3B,SAAK,KAAK,UAAU;AAAA,EACrB,OAAO;AACN,eAAW,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,IAAI,IAAI,OAAO,KAAK,UAAU,IAAI,CAAC;AAAA,EAC/F;AACD;"}
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const allowMethods = "GET,HEAD,PUT,POST,DELETE,PATCH";
4
+ const appendVary = (current, field) => {
5
+ const fields = current.split(",").map((it) => it.trim().toLowerCase());
6
+ if (fields.includes("*") || fields.includes(field.toLowerCase())) {
7
+ return current;
8
+ }
9
+ return current.trim() ? `${current}, ${field}` : field;
10
+ };
11
+ const createCorsMiddleware = ({ exposeHeaders }) => {
12
+ const exposeHeadersValue = exposeHeaders.join(",");
13
+ return async (ctx, next) => {
14
+ ctx.vary("Origin");
15
+ if (ctx.method === "OPTIONS") {
16
+ if (!ctx.get("Access-Control-Request-Method")) {
17
+ return await next();
18
+ }
19
+ ctx.set("Access-Control-Allow-Origin", "*");
20
+ ctx.set("Access-Control-Allow-Methods", allowMethods);
21
+ const requestHeaders = ctx.get("Access-Control-Request-Headers");
22
+ if (requestHeaders) {
23
+ ctx.set("Access-Control-Allow-Headers", requestHeaders);
24
+ }
25
+ ctx.status = 204;
26
+ return;
27
+ }
28
+ const corsHeaders = { "Access-Control-Allow-Origin": "*" };
29
+ if (exposeHeadersValue) {
30
+ corsHeaders["Access-Control-Expose-Headers"] = exposeHeadersValue;
31
+ }
32
+ ctx.set(corsHeaders);
33
+ try {
34
+ return await next();
35
+ } catch (error) {
36
+ if (typeof error === "object" && error !== null) {
37
+ const errorHeaders = Reflect.get(error, "headers");
38
+ const headers = typeof errorHeaders === "object" && errorHeaders !== null ? { ...errorHeaders } : {};
39
+ const vary = headers.vary ?? headers.Vary;
40
+ delete headers.Vary;
41
+ Reflect.set(error, "headers", {
42
+ ...headers,
43
+ ...corsHeaders,
44
+ vary: appendVary(typeof vary === "string" ? vary : "", "Origin")
45
+ });
46
+ }
47
+ throw error;
48
+ }
49
+ };
50
+ };
51
+ exports.createCorsMiddleware = createCorsMiddleware;
52
+ //# sourceMappingURL=cors.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.cjs","sources":["../../../../../packages/engine-http/src/application/cors.ts"],"sourcesContent":["import { KoaMiddleware } from './types.js'\n\nconst allowMethods = 'GET,HEAD,PUT,POST,DELETE,PATCH'\n\nconst appendVary = (current: string, field: string): string => {\n\tconst fields = current.split(',').map(it => it.trim().toLowerCase())\n\tif (fields.includes('*') || fields.includes(field.toLowerCase())) {\n\t\treturn current\n\t}\n\treturn current.trim() ? `${current}, ${field}` : field\n}\n\n/**\n * Permissive CORS for any origin without credentials. Preflights (OPTIONS with\n * Access-Control-Request-Method) are answered with 204 and echo the requested headers.\n * The CORS headers survive an error thrown by the downstream handler.\n */\nexport const createCorsMiddleware = ({ exposeHeaders }: { exposeHeaders: readonly string[] }): KoaMiddleware<unknown> => {\n\tconst exposeHeadersValue = exposeHeaders.join(',')\n\n\treturn async (ctx, next) => {\n\t\tctx.vary('Origin')\n\n\t\tif (ctx.method === 'OPTIONS') {\n\t\t\tif (!ctx.get('Access-Control-Request-Method')) {\n\t\t\t\treturn await next()\n\t\t\t}\n\t\t\tctx.set('Access-Control-Allow-Origin', '*')\n\t\t\tctx.set('Access-Control-Allow-Methods', allowMethods)\n\t\t\tconst requestHeaders = ctx.get('Access-Control-Request-Headers')\n\t\t\tif (requestHeaders) {\n\t\t\t\tctx.set('Access-Control-Allow-Headers', requestHeaders)\n\t\t\t}\n\t\t\tctx.status = 204\n\t\t\treturn\n\t\t}\n\n\t\tconst corsHeaders: Record<string, string> = { 'Access-Control-Allow-Origin': '*' }\n\t\tif (exposeHeadersValue) {\n\t\t\tcorsHeaders['Access-Control-Expose-Headers'] = exposeHeadersValue\n\t\t}\n\t\tctx.set(corsHeaders)\n\t\ttry {\n\t\t\treturn await next()\n\t\t} catch (error) {\n\t\t\t// Koa's error handler resets the response headers and applies `error.headers` instead.\n\t\t\tif (typeof error === 'object' && error !== null) {\n\t\t\t\tconst errorHeaders: unknown = Reflect.get(error, 'headers')\n\t\t\t\tconst headers: Record<string, unknown> = typeof errorHeaders === 'object' && errorHeaders !== null ? { ...errorHeaders } : {}\n\t\t\t\tconst vary = headers.vary ?? headers.Vary\n\t\t\t\tdelete headers.Vary\n\t\t\t\tReflect.set(error, 'headers', {\n\t\t\t\t\t...headers,\n\t\t\t\t\t...corsHeaders,\n\t\t\t\t\tvary: appendVary(typeof vary === 'string' ? vary : '', 'Origin'),\n\t\t\t\t})\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n}\n"],"names":[],"mappings":";;AAEA,MAAM,eAAe;AAErB,MAAM,aAAa,CAAC,SAAiB,UAA0B;AAC9D,QAAM,SAAS,QAAQ,MAAM,GAAG,EAAE,IAAI,CAAA,OAAM,GAAG,KAAA,EAAO,YAAA,CAAa;AACnE,MAAI,OAAO,SAAS,GAAG,KAAK,OAAO,SAAS,MAAM,YAAA,CAAa,GAAG;AACjE,WAAO;AAAA,EACR;AACA,SAAO,QAAQ,KAAA,IAAS,GAAG,OAAO,KAAK,KAAK,KAAK;AAClD;AAOO,MAAM,uBAAuB,CAAC,EAAE,oBAAkF;AACxH,QAAM,qBAAqB,cAAc,KAAK,GAAG;AAEjD,SAAO,OAAO,KAAK,SAAS;AAC3B,QAAI,KAAK,QAAQ;AAEjB,QAAI,IAAI,WAAW,WAAW;AAC7B,UAAI,CAAC,IAAI,IAAI,+BAA+B,GAAG;AAC9C,eAAO,MAAM,KAAA;AAAA,MACd;AACA,UAAI,IAAI,+BAA+B,GAAG;AAC1C,UAAI,IAAI,gCAAgC,YAAY;AACpD,YAAM,iBAAiB,IAAI,IAAI,gCAAgC;AAC/D,UAAI,gBAAgB;AACnB,YAAI,IAAI,gCAAgC,cAAc;AAAA,MACvD;AACA,UAAI,SAAS;AACb;AAAA,IACD;AAEA,UAAM,cAAsC,EAAE,+BAA+B,IAAA;AAC7E,QAAI,oBAAoB;AACvB,kBAAY,+BAA+B,IAAI;AAAA,IAChD;AACA,QAAI,IAAI,WAAW;AACnB,QAAI;AACH,aAAO,MAAM,KAAA;AAAA,IACd,SAAS,OAAO;AAEf,UAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAChD,cAAM,eAAwB,QAAQ,IAAI,OAAO,SAAS;AAC1D,cAAM,UAAmC,OAAO,iBAAiB,YAAY,iBAAiB,OAAO,EAAE,GAAG,aAAA,IAAiB,CAAA;AAC3H,cAAM,OAAO,QAAQ,QAAQ,QAAQ;AACrC,eAAO,QAAQ;AACf,gBAAQ,IAAI,OAAO,WAAW;AAAA,UAC7B,GAAG;AAAA,UACH,GAAG;AAAA,UACH,MAAM,WAAW,OAAO,SAAS,WAAW,OAAO,IAAI,QAAQ;AAAA,QAAA,CAC/D;AAAA,MACF;AACA,YAAM;AAAA,IACP;AAAA,EACD;AACD;;"}
@@ -0,0 +1,52 @@
1
+ const allowMethods = "GET,HEAD,PUT,POST,DELETE,PATCH";
2
+ const appendVary = (current, field) => {
3
+ const fields = current.split(",").map((it) => it.trim().toLowerCase());
4
+ if (fields.includes("*") || fields.includes(field.toLowerCase())) {
5
+ return current;
6
+ }
7
+ return current.trim() ? `${current}, ${field}` : field;
8
+ };
9
+ const createCorsMiddleware = ({ exposeHeaders }) => {
10
+ const exposeHeadersValue = exposeHeaders.join(",");
11
+ return async (ctx, next) => {
12
+ ctx.vary("Origin");
13
+ if (ctx.method === "OPTIONS") {
14
+ if (!ctx.get("Access-Control-Request-Method")) {
15
+ return await next();
16
+ }
17
+ ctx.set("Access-Control-Allow-Origin", "*");
18
+ ctx.set("Access-Control-Allow-Methods", allowMethods);
19
+ const requestHeaders = ctx.get("Access-Control-Request-Headers");
20
+ if (requestHeaders) {
21
+ ctx.set("Access-Control-Allow-Headers", requestHeaders);
22
+ }
23
+ ctx.status = 204;
24
+ return;
25
+ }
26
+ const corsHeaders = { "Access-Control-Allow-Origin": "*" };
27
+ if (exposeHeadersValue) {
28
+ corsHeaders["Access-Control-Expose-Headers"] = exposeHeadersValue;
29
+ }
30
+ ctx.set(corsHeaders);
31
+ try {
32
+ return await next();
33
+ } catch (error) {
34
+ if (typeof error === "object" && error !== null) {
35
+ const errorHeaders = Reflect.get(error, "headers");
36
+ const headers = typeof errorHeaders === "object" && errorHeaders !== null ? { ...errorHeaders } : {};
37
+ const vary = headers.vary ?? headers.Vary;
38
+ delete headers.Vary;
39
+ Reflect.set(error, "headers", {
40
+ ...headers,
41
+ ...corsHeaders,
42
+ vary: appendVary(typeof vary === "string" ? vary : "", "Origin")
43
+ });
44
+ }
45
+ throw error;
46
+ }
47
+ };
48
+ };
49
+ export {
50
+ createCorsMiddleware
51
+ };
52
+ //# sourceMappingURL=cors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.js","sources":["../../../../../packages/engine-http/src/application/cors.ts"],"sourcesContent":["import { KoaMiddleware } from './types.js'\n\nconst allowMethods = 'GET,HEAD,PUT,POST,DELETE,PATCH'\n\nconst appendVary = (current: string, field: string): string => {\n\tconst fields = current.split(',').map(it => it.trim().toLowerCase())\n\tif (fields.includes('*') || fields.includes(field.toLowerCase())) {\n\t\treturn current\n\t}\n\treturn current.trim() ? `${current}, ${field}` : field\n}\n\n/**\n * Permissive CORS for any origin without credentials. Preflights (OPTIONS with\n * Access-Control-Request-Method) are answered with 204 and echo the requested headers.\n * The CORS headers survive an error thrown by the downstream handler.\n */\nexport const createCorsMiddleware = ({ exposeHeaders }: { exposeHeaders: readonly string[] }): KoaMiddleware<unknown> => {\n\tconst exposeHeadersValue = exposeHeaders.join(',')\n\n\treturn async (ctx, next) => {\n\t\tctx.vary('Origin')\n\n\t\tif (ctx.method === 'OPTIONS') {\n\t\t\tif (!ctx.get('Access-Control-Request-Method')) {\n\t\t\t\treturn await next()\n\t\t\t}\n\t\t\tctx.set('Access-Control-Allow-Origin', '*')\n\t\t\tctx.set('Access-Control-Allow-Methods', allowMethods)\n\t\t\tconst requestHeaders = ctx.get('Access-Control-Request-Headers')\n\t\t\tif (requestHeaders) {\n\t\t\t\tctx.set('Access-Control-Allow-Headers', requestHeaders)\n\t\t\t}\n\t\t\tctx.status = 204\n\t\t\treturn\n\t\t}\n\n\t\tconst corsHeaders: Record<string, string> = { 'Access-Control-Allow-Origin': '*' }\n\t\tif (exposeHeadersValue) {\n\t\t\tcorsHeaders['Access-Control-Expose-Headers'] = exposeHeadersValue\n\t\t}\n\t\tctx.set(corsHeaders)\n\t\ttry {\n\t\t\treturn await next()\n\t\t} catch (error) {\n\t\t\t// Koa's error handler resets the response headers and applies `error.headers` instead.\n\t\t\tif (typeof error === 'object' && error !== null) {\n\t\t\t\tconst errorHeaders: unknown = Reflect.get(error, 'headers')\n\t\t\t\tconst headers: Record<string, unknown> = typeof errorHeaders === 'object' && errorHeaders !== null ? { ...errorHeaders } : {}\n\t\t\t\tconst vary = headers.vary ?? headers.Vary\n\t\t\t\tdelete headers.Vary\n\t\t\t\tReflect.set(error, 'headers', {\n\t\t\t\t\t...headers,\n\t\t\t\t\t...corsHeaders,\n\t\t\t\t\tvary: appendVary(typeof vary === 'string' ? vary : '', 'Origin'),\n\t\t\t\t})\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}\n}\n"],"names":[],"mappings":"AAEA,MAAM,eAAe;AAErB,MAAM,aAAa,CAAC,SAAiB,UAA0B;AA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AO,IAAI,QAAQ;AAAA,QAAA,CAC/D;AAAA,MACF;AACA,YAAM;AAAA,IACP;AAAA,EACD;AACD;"}
@@ -0,0 +1,242 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const zlib = require("node:zlib");
4
+ const byteUnits = {
5
+ b: 1,
6
+ kb: 1024,
7
+ mb: 1024 ** 2,
8
+ gb: 1024 ** 3,
9
+ tb: 1024 ** 4,
10
+ pb: 1024 ** 5
11
+ };
12
+ const parseByteSize = (value) => {
13
+ const match = /^(\d+(?:\.\d+)?) *(b|kb|mb|gb|tb|pb)?$/i.exec(value.trim());
14
+ if (!match) {
15
+ return void 0;
16
+ }
17
+ const bytes = Math.floor(Number(match[1]) * byteUnits[(match[2] ?? "b").toLowerCase()]);
18
+ return Number.isSafeInteger(bytes) ? bytes : void 0;
19
+ };
20
+ const jsonTypes = /* @__PURE__ */ new Set([
21
+ "application/json",
22
+ "application/json-patch+json",
23
+ "application/vnd.api+json",
24
+ "application/csp-report",
25
+ "application/scim+json"
26
+ ]);
27
+ const formType = "application/x-www-form-urlencoded";
28
+ const mediaTypePattern = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/;
29
+ const mediaTypeParameterPattern = /; *[!#$%&'*+\-.0-9A-Z^_`a-z|~]+ *= *(?:"(?:[ !\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+\-.0-9A-Z^_`a-z|~]+) */y;
30
+ const parseMediaType = (header) => {
31
+ const value = header.replace(/;$/, "");
32
+ const separator = value.indexOf(";");
33
+ const match = mediaTypePattern.exec(separator === -1 ? value : value.slice(0, separator));
34
+ if (!match) {
35
+ return void 0;
36
+ }
37
+ if (separator !== -1) {
38
+ mediaTypeParameterPattern.lastIndex = separator;
39
+ while (mediaTypeParameterPattern.lastIndex < value.length) {
40
+ if (!mediaTypeParameterPattern.test(value)) {
41
+ return void 0;
42
+ }
43
+ }
44
+ }
45
+ return `${match[1]}/${match[2]}`.toLowerCase();
46
+ };
47
+ class BodyReadError extends Error {
48
+ constructor(failure) {
49
+ super(failure.message ?? `HTTP ${failure.status}`);
50
+ this.failure = failure;
51
+ }
52
+ }
53
+ const tooLarge = { status: 413, message: "request entity too large" };
54
+ const aborted = { status: 400, message: "request aborted" };
55
+ const createDecompressor = (encoding) => {
56
+ switch (encoding) {
57
+ case "identity":
58
+ return void 0;
59
+ case "gzip":
60
+ case "deflate":
61
+ return zlib.createUnzip();
62
+ case "br":
63
+ return zlib.createBrotliDecompress();
64
+ default:
65
+ throw new BodyReadError({ status: 415 });
66
+ }
67
+ };
68
+ const compressedLimit = (limit) => limit + Math.ceil(limit / 1024) + 1024;
69
+ const readRequestText = (request, limit) => {
70
+ const encoding = request.headers["content-encoding"] ?? "identity";
71
+ const contentLength = request.headers["content-length"] !== void 0 ? Number(request.headers["content-length"]) : void 0;
72
+ const wireLimit = encoding === "identity" ? limit : compressedLimit(limit);
73
+ if (contentLength !== void 0 && contentLength > wireLimit) {
74
+ return Promise.reject(new BodyReadError(tooLarge));
75
+ }
76
+ const declaredLength = encoding === "identity" ? contentLength : void 0;
77
+ if (request.readableEnded) {
78
+ return Promise.reject(new BodyReadError({ status: 500, message: "request body was already read" }));
79
+ }
80
+ if (request.destroyed || request.readableAborted || !request.readable) {
81
+ return Promise.reject(new BodyReadError(aborted));
82
+ }
83
+ let decompressor;
84
+ try {
85
+ decompressor = createDecompressor(encoding);
86
+ } catch (error) {
87
+ return Promise.reject(error);
88
+ }
89
+ const source = decompressor ? request.pipe(decompressor) : request;
90
+ return new Promise((resolve, reject) => {
91
+ const chunks = [];
92
+ let received = 0;
93
+ let receivedCompressed = 0;
94
+ let settled = false;
95
+ const cleanup = () => {
96
+ source.off("data", onData);
97
+ source.off("end", onEnd);
98
+ source.off("error", onSourceError);
99
+ request.off("data", onCompressedData);
100
+ request.off("error", onAborted);
101
+ request.off("close", onClose);
102
+ };
103
+ const fail = (failure) => {
104
+ if (settled) {
105
+ return;
106
+ }
107
+ settled = true;
108
+ cleanup();
109
+ if (decompressor) {
110
+ request.unpipe(decompressor);
111
+ decompressor.destroy();
112
+ }
113
+ source.pause();
114
+ reject(new BodyReadError(failure));
115
+ };
116
+ const onData = (chunk) => {
117
+ received += chunk.length;
118
+ if (received > limit) {
119
+ fail(tooLarge);
120
+ } else {
121
+ chunks.push(chunk);
122
+ }
123
+ };
124
+ const onCompressedData = (chunk) => {
125
+ receivedCompressed += chunk.length;
126
+ if (receivedCompressed > wireLimit) {
127
+ fail(tooLarge);
128
+ }
129
+ };
130
+ const onEnd = () => {
131
+ if (declaredLength !== void 0 && received !== declaredLength) {
132
+ fail({ status: 400, message: "request size did not match content length" });
133
+ return;
134
+ }
135
+ settled = true;
136
+ cleanup();
137
+ resolve(new TextDecoder().decode(Buffer.concat(chunks)));
138
+ };
139
+ const onSourceError = () => fail(decompressor === void 0 ? aborted : { status: 400, message: "request body could not be decompressed" });
140
+ const onAborted = () => fail(aborted);
141
+ const onClose = () => {
142
+ if (!request.complete) {
143
+ fail(aborted);
144
+ }
145
+ };
146
+ source.on("data", onData);
147
+ source.on("end", onEnd);
148
+ source.on("error", onSourceError);
149
+ if (decompressor) {
150
+ request.on("data", onCompressedData);
151
+ }
152
+ request.on("error", onAborted);
153
+ request.on("close", onClose);
154
+ });
155
+ };
156
+ const strictJsonStart = /^[ \t\n\r]*[[{]/;
157
+ const suspectProtoKey = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
158
+ const hasOwnProtoKey = (root) => {
159
+ const pending = [root];
160
+ for (let node = pending.pop(); node !== void 0; node = pending.pop()) {
161
+ if (Object.hasOwn(node, "__proto__")) {
162
+ return true;
163
+ }
164
+ for (const value of Object.values(node)) {
165
+ if (typeof value === "object" && value !== null) {
166
+ pending.push(value);
167
+ }
168
+ }
169
+ }
170
+ return false;
171
+ };
172
+ const parseJsonBody = (text) => {
173
+ if (text === "") {
174
+ return { ok: true, value: {} };
175
+ }
176
+ if (!strictJsonStart.test(text)) {
177
+ return { ok: false };
178
+ }
179
+ let value;
180
+ try {
181
+ value = JSON.parse(text);
182
+ } catch {
183
+ return { ok: false };
184
+ }
185
+ if (typeof value === "object" && value !== null && suspectProtoKey.test(text) && hasOwnProtoKey(value)) {
186
+ return { ok: false };
187
+ }
188
+ return { ok: true, value };
189
+ };
190
+ const maxFormParameters = 1e3;
191
+ const parseFormBody = (text) => {
192
+ const result = {};
193
+ let count = 0;
194
+ for (const [key, value] of new URLSearchParams(text)) {
195
+ if (++count > maxFormParameters) {
196
+ break;
197
+ }
198
+ if (key === "" || Object.hasOwn(Object.prototype, key)) {
199
+ continue;
200
+ }
201
+ const existing = result[key];
202
+ result[key] = existing === void 0 ? value : [...Array.isArray(existing) ? existing : [existing], value];
203
+ }
204
+ return result;
205
+ };
206
+ const defaultJsonBodyLimit = 1024 ** 2;
207
+ const defaultFormBodyLimit = 56 * 1024;
208
+ const parseBody = async (ctx, limits) => {
209
+ const type = parseMediaType(ctx.get("Content-Type"));
210
+ if (type !== void 0 && jsonTypes.has(type)) {
211
+ const parsed = parseJsonBody(await readRequestText(ctx.req, limits.json));
212
+ return parsed.ok ? parsed.value : ctx.throw(400);
213
+ }
214
+ if (type === formType) {
215
+ return parseFormBody(await readRequestText(ctx.req, limits.form));
216
+ }
217
+ return {};
218
+ };
219
+ const createRequestBodyMiddleware = (limits) => async (ctx, next) => {
220
+ if (ctx.request.body !== void 0) {
221
+ return await next();
222
+ }
223
+ try {
224
+ ctx.request.body = await parseBody(ctx, limits);
225
+ } catch (error) {
226
+ if (error instanceof BodyReadError) {
227
+ const { status, message } = error.failure;
228
+ return message === void 0 ? ctx.throw(status) : ctx.throw(status, message);
229
+ }
230
+ throw error;
231
+ }
232
+ await next();
233
+ };
234
+ exports.createRequestBodyMiddleware = createRequestBodyMiddleware;
235
+ exports.defaultFormBodyLimit = defaultFormBodyLimit;
236
+ exports.defaultJsonBodyLimit = defaultJsonBodyLimit;
237
+ exports.parseByteSize = parseByteSize;
238
+ exports.parseFormBody = parseFormBody;
239
+ exports.parseJsonBody = parseJsonBody;
240
+ exports.parseMediaType = parseMediaType;
241
+ exports.readRequestText = readRequestText;
242
+ //# sourceMappingURL=requestBody.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestBody.cjs","sources":["../../../../../packages/engine-http/src/application/requestBody.ts"],"sourcesContent":["import { IncomingMessage } from 'node:http'\nimport { Readable, Transform } from 'node:stream'\nimport { createBrotliDecompress, createUnzip } from 'node:zlib'\nimport { KoaContext, KoaMiddleware } from './types.js'\n\ndeclare module 'koa' {\n\tinterface Request {\n\t\t/** The parsed JSON or form body; `{}` for any other content type. */\n\t\tbody?: unknown\n\t}\n}\n\nconst byteUnits: Readonly<Record<string, number>> = {\n\tb: 1,\n\tkb: 1024,\n\tmb: 1024 ** 2,\n\tgb: 1024 ** 3,\n\ttb: 1024 ** 4,\n\tpb: 1024 ** 5,\n}\n\n/** `1048576`, `512kb`, `1.5 MB`: binary units, as `requestBodySize` has always been read. `undefined` when invalid. */\nexport const parseByteSize = (value: string): number | undefined => {\n\tconst match = /^(\\d+(?:\\.\\d+)?) *(b|kb|mb|gb|tb|pb)?$/i.exec(value.trim())\n\tif (!match) {\n\t\treturn undefined\n\t}\n\tconst bytes = Math.floor(Number(match[1]) * byteUnits[(match[2] ?? 'b').toLowerCase()])\n\treturn Number.isSafeInteger(bytes) ? bytes : undefined\n}\n\nconst jsonTypes: ReadonlySet<string> = new Set([\n\t'application/json',\n\t'application/json-patch+json',\n\t'application/vnd.api+json',\n\t'application/csp-report',\n\t'application/scim+json',\n])\nconst formType = 'application/x-www-form-urlencoded'\n\nconst mediaTypePattern = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/\nconst mediaTypeParameterPattern =\n\t/; *[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+ *= *(?:\"(?:[ !\\x23-\\x5b\\x5d-\\x7e\\x80-\\xff]|\\\\[\\x20-\\x7e])*\"|[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+) */y\n\n/** The lower-cased `type/subtype` of a well-formed Content-Type header; a malformed one matches no parser. */\nexport const parseMediaType = (header: string): string | undefined => {\n\t// clients commonly send a trailing `;`, e.g. `application/json;`\n\tconst value = header.replace(/;$/, '')\n\tconst separator = value.indexOf(';')\n\tconst match = mediaTypePattern.exec(separator === -1 ? value : value.slice(0, separator))\n\tif (!match) {\n\t\treturn undefined\n\t}\n\tif (separator !== -1) {\n\t\tmediaTypeParameterPattern.lastIndex = separator\n\t\twhile (mediaTypeParameterPattern.lastIndex < value.length) {\n\t\t\tif (!mediaTypeParameterPattern.test(value)) {\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t}\n\treturn `${match[1]}/${match[2]}`.toLowerCase()\n}\n\ntype BodyReadFailure = { readonly status: 400 | 413 | 415 | 500; readonly message?: string }\n\nclass BodyReadError extends Error {\n\tconstructor(readonly failure: BodyReadFailure) {\n\t\tsuper(failure.message ?? `HTTP ${failure.status}`)\n\t}\n}\n\nconst tooLarge: BodyReadFailure = { status: 413, message: 'request entity too large' }\nconst aborted: BodyReadFailure = { status: 400, message: 'request aborted' }\n\nconst createDecompressor = (encoding: string): Transform | undefined => {\n\tswitch (encoding) {\n\t\tcase 'identity':\n\t\t\treturn undefined\n\t\tcase 'gzip':\n\t\tcase 'deflate':\n\t\t\treturn createUnzip()\n\t\tcase 'br':\n\t\t\treturn createBrotliDecompress()\n\t\tdefault:\n\t\t\tthrow new BodyReadError({ status: 415 })\n\t}\n}\n\n/** Compressed data can be a little larger than what it inflates to (stored blocks, headers), never by much. */\nconst compressedLimit = (limit: number): number => limit + Math.ceil(limit / 1024) + 1024\n\n/**\n * Reads the body as UTF-8 text. `limit` caps the decompressed size, so a compressed body cannot expand past it, and the\n * bytes received, so one cannot send endless input that inflates to nothing. On a failure the request is left paused\n * and unread, as before.\n */\nexport const readRequestText = (request: IncomingMessage, limit: number): Promise<string> => {\n\tconst encoding = request.headers['content-encoding'] ?? 'identity'\n\tconst contentLength = request.headers['content-length'] !== undefined ? Number(request.headers['content-length']) : undefined\n\tconst wireLimit = encoding === 'identity' ? limit : compressedLimit(limit)\n\tif (contentLength !== undefined && contentLength > wireLimit) {\n\t\treturn Promise.reject(new BodyReadError(tooLarge))\n\t}\n\tconst declaredLength = encoding === 'identity' ? contentLength : undefined\n\t// a consumed or closed request emits nothing more, so waiting for it would never settle\n\tif (request.readableEnded) {\n\t\treturn Promise.reject(new BodyReadError({ status: 500, message: 'request body was already read' }))\n\t}\n\tif (request.destroyed || request.readableAborted || !request.readable) {\n\t\treturn Promise.reject(new BodyReadError(aborted))\n\t}\n\tlet decompressor: Transform | undefined\n\ttry {\n\t\tdecompressor = createDecompressor(encoding)\n\t} catch (error) {\n\t\treturn Promise.reject(error)\n\t}\n\tconst source: Readable = decompressor ? request.pipe(decompressor) : request\n\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks: Buffer[] = []\n\t\tlet received = 0\n\t\tlet receivedCompressed = 0\n\t\tlet settled = false\n\n\t\tconst cleanup = () => {\n\t\t\tsource.off('data', onData)\n\t\t\tsource.off('end', onEnd)\n\t\t\tsource.off('error', onSourceError)\n\t\t\trequest.off('data', onCompressedData)\n\t\t\trequest.off('error', onAborted)\n\t\t\trequest.off('close', onClose)\n\t\t}\n\t\tconst fail = (failure: BodyReadFailure) => {\n\t\t\tif (settled) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsettled = true\n\t\t\tcleanup()\n\t\t\tif (decompressor) {\n\t\t\t\trequest.unpipe(decompressor)\n\t\t\t\tdecompressor.destroy()\n\t\t\t}\n\t\t\tsource.pause()\n\t\t\treject(new BodyReadError(failure))\n\t\t}\n\t\tconst onData = (chunk: Buffer) => {\n\t\t\treceived += chunk.length\n\t\t\tif (received > limit) {\n\t\t\t\tfail(tooLarge)\n\t\t\t} else {\n\t\t\t\tchunks.push(chunk)\n\t\t\t}\n\t\t}\n\t\tconst onCompressedData = (chunk: Buffer) => {\n\t\t\treceivedCompressed += chunk.length\n\t\t\tif (receivedCompressed > wireLimit) {\n\t\t\t\tfail(tooLarge)\n\t\t\t}\n\t\t}\n\t\tconst onEnd = () => {\n\t\t\tif (declaredLength !== undefined && received !== declaredLength) {\n\t\t\t\tfail({ status: 400, message: 'request size did not match content length' })\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsettled = true\n\t\t\tcleanup()\n\t\t\t// strips a UTF-8 BOM and replaces invalid sequences, as the previous parser did\n\t\t\tresolve(new TextDecoder().decode(Buffer.concat(chunks)))\n\t\t}\n\t\tconst onSourceError = () => fail(decompressor === undefined ? aborted : { status: 400, message: 'request body could not be decompressed' })\n\t\tconst onAborted = () => fail(aborted)\n\t\tconst onClose = () => {\n\t\t\tif (!request.complete) {\n\t\t\t\tfail(aborted)\n\t\t\t}\n\t\t}\n\n\t\tsource.on('data', onData)\n\t\tsource.on('end', onEnd)\n\t\tsource.on('error', onSourceError)\n\t\tif (decompressor) {\n\t\t\trequest.on('data', onCompressedData)\n\t\t}\n\t\trequest.on('error', onAborted)\n\t\trequest.on('close', onClose)\n\t})\n}\n\nconst strictJsonStart = /^[ \\t\\n\\r]*[[{]/\n// any spelling of a `\"__proto__\":` key, escapes included; only then is the parsed value scanned\nconst suspectProtoKey =\n\t/\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/\n\nconst hasOwnProtoKey = (root: object): boolean => {\n\tconst pending: object[] = [root]\n\tfor (let node = pending.pop(); node !== undefined; node = pending.pop()) {\n\t\tif (Object.hasOwn(node, '__proto__')) {\n\t\t\treturn true\n\t\t}\n\t\tfor (const value of Object.values(node)) {\n\t\t\tif (typeof value === 'object' && value !== null) {\n\t\t\t\tpending.push(value)\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\ntype JsonParseResult = { readonly ok: true; readonly value: unknown } | { readonly ok: false }\n\n/** Only an object or an array, and no `__proto__` key anywhere (prototype poisoning). An empty body is `{}`. */\nexport const parseJsonBody = (text: string): JsonParseResult => {\n\tif (text === '') {\n\t\treturn { ok: true, value: {} }\n\t}\n\tif (!strictJsonStart.test(text)) {\n\t\treturn { ok: false }\n\t}\n\tlet value: unknown\n\ttry {\n\t\tvalue = JSON.parse(text)\n\t} catch {\n\t\treturn { ok: false }\n\t}\n\tif (typeof value === 'object' && value !== null && suspectProtoKey.test(text) && hasOwnProtoKey(value)) {\n\t\treturn { ok: false }\n\t}\n\treturn { ok: true, value }\n}\n\nconst maxFormParameters = 1000\n\n/**\n * Flat `application/x-www-form-urlencoded`: a repeated key collects its values into an array. Only the first 1000\n * pairs are read, and keys naming an `Object.prototype` member (`__proto__`, `constructor`, …) are dropped.\n */\nexport const parseFormBody = (text: string): Record<string, string | string[]> => {\n\tconst result: Record<string, string | string[]> = {}\n\tlet count = 0\n\tfor (const [key, value] of new URLSearchParams(text)) {\n\t\tif (++count > maxFormParameters) {\n\t\t\tbreak\n\t\t}\n\t\tif (key === '' || Object.hasOwn(Object.prototype, key)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst existing = result[key]\n\t\tresult[key] = existing === undefined ? value : [...(Array.isArray(existing) ? existing : [existing]), value]\n\t}\n\treturn result\n}\n\nexport const defaultJsonBodyLimit = 1024 ** 2\nexport const defaultFormBodyLimit = 56 * 1024\n\n/** Bytes after decompression. */\nexport interface RequestBodyLimits {\n\treadonly json: number\n\treadonly form: number\n}\n\nconst parseBody = async (ctx: KoaContext<unknown>, limits: RequestBodyLimits): Promise<unknown> => {\n\tconst type = parseMediaType(ctx.get('Content-Type'))\n\tif (type !== undefined && jsonTypes.has(type)) {\n\t\tconst parsed = parseJsonBody(await readRequestText(ctx.req, limits.json))\n\t\treturn parsed.ok ? parsed.value : ctx.throw(400)\n\t}\n\tif (type === formType) {\n\t\treturn parseFormBody(await readRequestText(ctx.req, limits.form))\n\t}\n\treturn {}\n}\n\n/**\n * Parses JSON and form bodies into `ctx.request.body`, unless an earlier middleware set it. Other content types are not\n * read, so a handler can still stream the request (the import API reads `application/x-ndjson` itself).\n */\nexport const createRequestBodyMiddleware = (limits: RequestBodyLimits): KoaMiddleware<unknown> => async (ctx, next) => {\n\tif (ctx.request.body !== undefined) {\n\t\treturn await next()\n\t}\n\ttry {\n\t\tctx.request.body = await parseBody(ctx, limits)\n\t} catch (error) {\n\t\tif (error instanceof BodyReadError) {\n\t\t\tconst { status, message } = error.failure\n\t\t\t// without a message the response carries the status text, e.g. `Unsupported Media Type`\n\t\t\treturn message === undefined ? ctx.throw(status) : ctx.throw(status, message)\n\t\t}\n\t\tthrow error\n\t}\n\tawait next()\n}\n"],"names":["createUnzip","createBrotliDecompress"],"mappings":";;;AAYA,MAAM,YAA8C;AAAA,EACnD,GAAG;AAAA,EACH,IAAI;AAAA,EACJ,IAAI,QAAQ;AAAA,EACZ,IAAI,QAAQ;AAAA,EACZ,IAAI,QAAQ;AAAA,EACZ,IAAI,QAAQ;AACb;AAGO,MAAM,gBAAgB,CAAC,UAAsC;AACnE,QAAM,QAAQ,0CAA0C,KAAK,MAAM,MAAM;AACzE,MAAI,CAAC,OAAO;AACX,WAAO;AAAA,EACR;AACA,QAAM,QAAQ,KAAK,MAAM,OAAO,MAAM,CAAC,CAAC,IAAI,WAAW,MAAM,CAAC,KAAK,KAAK,YAAA,CAAa,CAAC;AACtF,SAAO,OAAO,cAAc,KAAK,IAAI,QAAQ;AAC9C;AAEA,MAAM,gCAAqC,IAAI;AAAA,EAC9C;AAAA,EACA;AAAA,EACA;A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