vovk 3.0.0-draft.46 → 3.0.0-draft.461

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 (207) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +8 -96
  3. package/bin/index.mjs +8 -0
  4. package/cjs/JSONLinesResponse.d.ts +19 -0
  5. package/cjs/JSONLinesResponse.js +95 -0
  6. package/{VovkApp.d.ts → cjs/VovkApp.d.ts} +14 -8
  7. package/cjs/VovkApp.js +304 -0
  8. package/cjs/client/createRPC.d.ts +5 -0
  9. package/cjs/client/createRPC.js +116 -0
  10. package/cjs/client/defaultHandler.d.ts +6 -0
  11. package/{client → cjs/client}/defaultHandler.js +9 -2
  12. package/cjs/client/defaultStreamHandler.d.ts +9 -0
  13. package/{client → cjs/client}/defaultStreamHandler.js +49 -26
  14. package/cjs/client/fetcher.d.ts +18 -0
  15. package/cjs/client/fetcher.js +97 -0
  16. package/cjs/client/index.d.ts +4 -0
  17. package/cjs/client/index.js +10 -0
  18. package/cjs/client/progressive.d.ts +9 -0
  19. package/cjs/client/progressive.js +54 -0
  20. package/cjs/client/types.d.ts +120 -0
  21. package/{createVovkApp.d.ts → cjs/createVovkApp.d.ts} +19 -16
  22. package/cjs/createVovkApp.js +146 -0
  23. package/cjs/index.d.ts +69 -0
  24. package/cjs/index.js +42 -0
  25. package/cjs/openapi/error.d.ts +2 -0
  26. package/cjs/openapi/error.js +100 -0
  27. package/cjs/openapi/index.d.ts +8 -0
  28. package/cjs/openapi/index.js +21 -0
  29. package/cjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.d.ts +3 -0
  30. package/cjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.js +67 -0
  31. package/cjs/openapi/openAPIToVovkSchema/index.d.ts +4 -0
  32. package/cjs/openapi/openAPIToVovkSchema/index.js +141 -0
  33. package/cjs/openapi/openAPIToVovkSchema/inlineRefs.d.ts +10 -0
  34. package/cjs/openapi/openAPIToVovkSchema/inlineRefs.js +102 -0
  35. package/cjs/openapi/vovkSchemaToOpenAPI.d.ts +8 -0
  36. package/cjs/openapi/vovkSchemaToOpenAPI.js +238 -0
  37. package/cjs/types.d.ts +466 -0
  38. package/{types.js → cjs/types.js} +14 -2
  39. package/cjs/utils/camelCase.d.ts +6 -0
  40. package/cjs/utils/camelCase.js +37 -0
  41. package/cjs/utils/createCodeSamples.d.ts +20 -0
  42. package/cjs/utils/createCodeSamples.js +279 -0
  43. package/cjs/utils/createDecorator.d.ts +6 -0
  44. package/{createDecorator.js → cjs/utils/createDecorator.js} +24 -14
  45. package/cjs/utils/createLLMTools.d.ts +50 -0
  46. package/cjs/utils/createLLMTools.js +168 -0
  47. package/cjs/utils/createStandardValidation.d.ts +83 -0
  48. package/cjs/utils/createStandardValidation.js +35 -0
  49. package/cjs/utils/createValidateOnClient.d.ts +7 -0
  50. package/cjs/utils/createValidateOnClient.js +19 -0
  51. package/cjs/utils/deepExtend.d.ts +54 -0
  52. package/cjs/utils/deepExtend.js +134 -0
  53. package/{utils → cjs/utils}/generateStaticAPI.d.ts +2 -2
  54. package/cjs/utils/generateStaticAPI.js +30 -0
  55. package/cjs/utils/getJSONSchemaExample.d.ts +11 -0
  56. package/cjs/utils/getJSONSchemaExample.js +264 -0
  57. package/cjs/utils/getJSONSchemaSample.d.ts +2 -0
  58. package/cjs/utils/getJSONSchemaSample.js +167 -0
  59. package/cjs/utils/getSampleFromObject.d.ts +9 -0
  60. package/cjs/utils/getSampleFromObject.js +41 -0
  61. package/cjs/utils/getSchema.d.ts +21 -0
  62. package/cjs/utils/getSchema.js +38 -0
  63. package/cjs/utils/multitenant.d.ts +24 -0
  64. package/cjs/utils/multitenant.js +131 -0
  65. package/cjs/utils/parseQuery.d.ts +25 -0
  66. package/cjs/utils/parseQuery.js +156 -0
  67. package/cjs/utils/reqForm.d.ts +2 -0
  68. package/cjs/utils/reqForm.js +33 -0
  69. package/cjs/utils/reqMeta.d.ts +2 -0
  70. package/cjs/utils/reqQuery.d.ts +2 -0
  71. package/cjs/utils/reqQuery.js +10 -0
  72. package/cjs/utils/resolveGeneratorConfigValues.d.ts +18 -0
  73. package/cjs/utils/resolveGeneratorConfigValues.js +82 -0
  74. package/cjs/utils/serializeQuery.d.ts +13 -0
  75. package/cjs/utils/serializeQuery.js +65 -0
  76. package/cjs/utils/setHandlerSchema.d.ts +4 -0
  77. package/cjs/utils/setHandlerSchema.js +15 -0
  78. package/cjs/utils/upperFirst.d.ts +1 -0
  79. package/cjs/utils/upperFirst.js +6 -0
  80. package/cjs/utils/withValidationLibrary.d.ts +78 -0
  81. package/cjs/utils/withValidationLibrary.js +133 -0
  82. package/mjs/HttpException.d.ts +7 -0
  83. package/mjs/HttpException.js +15 -0
  84. package/mjs/JSONLinesResponse.d.ts +19 -0
  85. package/mjs/JSONLinesResponse.js +95 -0
  86. package/mjs/VovkApp.d.ts +34 -0
  87. package/mjs/VovkApp.js +304 -0
  88. package/mjs/client/createRPC.d.ts +5 -0
  89. package/mjs/client/createRPC.js +116 -0
  90. package/mjs/client/defaultHandler.d.ts +6 -0
  91. package/mjs/client/defaultHandler.js +29 -0
  92. package/mjs/client/defaultStreamHandler.d.ts +9 -0
  93. package/mjs/client/defaultStreamHandler.js +105 -0
  94. package/mjs/client/fetcher.d.ts +18 -0
  95. package/mjs/client/fetcher.js +97 -0
  96. package/mjs/client/index.d.ts +4 -0
  97. package/mjs/client/index.js +10 -0
  98. package/mjs/client/progressive.d.ts +9 -0
  99. package/mjs/client/progressive.js +54 -0
  100. package/mjs/client/types.d.ts +120 -0
  101. package/mjs/createVovkApp.d.ts +65 -0
  102. package/mjs/createVovkApp.js +146 -0
  103. package/mjs/index.d.ts +69 -0
  104. package/mjs/index.js +42 -0
  105. package/mjs/openapi/error.d.ts +2 -0
  106. package/mjs/openapi/error.js +100 -0
  107. package/mjs/openapi/index.d.ts +8 -0
  108. package/mjs/openapi/index.js +21 -0
  109. package/mjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.d.ts +3 -0
  110. package/mjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.js +67 -0
  111. package/mjs/openapi/openAPIToVovkSchema/index.d.ts +4 -0
  112. package/mjs/openapi/openAPIToVovkSchema/index.js +141 -0
  113. package/mjs/openapi/openAPIToVovkSchema/inlineRefs.d.ts +10 -0
  114. package/mjs/openapi/openAPIToVovkSchema/inlineRefs.js +102 -0
  115. package/mjs/openapi/vovkSchemaToOpenAPI.d.ts +8 -0
  116. package/mjs/openapi/vovkSchemaToOpenAPI.js +238 -0
  117. package/mjs/types.d.ts +466 -0
  118. package/mjs/types.js +77 -0
  119. package/mjs/utils/camelCase.d.ts +6 -0
  120. package/mjs/utils/camelCase.js +37 -0
  121. package/mjs/utils/createCodeSamples.d.ts +20 -0
  122. package/mjs/utils/createCodeSamples.js +279 -0
  123. package/mjs/utils/createDecorator.d.ts +6 -0
  124. package/mjs/utils/createDecorator.js +48 -0
  125. package/mjs/utils/createLLMTools.d.ts +50 -0
  126. package/mjs/utils/createLLMTools.js +168 -0
  127. package/mjs/utils/createStandardValidation.d.ts +83 -0
  128. package/mjs/utils/createStandardValidation.js +35 -0
  129. package/mjs/utils/createValidateOnClient.d.ts +7 -0
  130. package/mjs/utils/createValidateOnClient.js +19 -0
  131. package/mjs/utils/deepExtend.d.ts +54 -0
  132. package/mjs/utils/deepExtend.js +134 -0
  133. package/mjs/utils/generateStaticAPI.d.ts +4 -0
  134. package/mjs/utils/generateStaticAPI.js +30 -0
  135. package/mjs/utils/getJSONSchemaExample.d.ts +11 -0
  136. package/mjs/utils/getJSONSchemaExample.js +264 -0
  137. package/mjs/utils/getJSONSchemaSample.d.ts +2 -0
  138. package/mjs/utils/getJSONSchemaSample.js +167 -0
  139. package/mjs/utils/getSampleFromObject.d.ts +9 -0
  140. package/mjs/utils/getSampleFromObject.js +41 -0
  141. package/mjs/utils/getSchema.d.ts +21 -0
  142. package/mjs/utils/getSchema.js +38 -0
  143. package/mjs/utils/multitenant.d.ts +24 -0
  144. package/mjs/utils/multitenant.js +131 -0
  145. package/mjs/utils/parseQuery.d.ts +25 -0
  146. package/mjs/utils/parseQuery.js +156 -0
  147. package/mjs/utils/reqForm.d.ts +2 -0
  148. package/mjs/utils/reqForm.js +33 -0
  149. package/mjs/utils/reqMeta.d.ts +2 -0
  150. package/mjs/utils/reqMeta.js +13 -0
  151. package/mjs/utils/reqQuery.d.ts +2 -0
  152. package/mjs/utils/reqQuery.js +10 -0
  153. package/mjs/utils/resolveGeneratorConfigValues.d.ts +18 -0
  154. package/mjs/utils/resolveGeneratorConfigValues.js +82 -0
  155. package/mjs/utils/serializeQuery.d.ts +13 -0
  156. package/mjs/utils/serializeQuery.js +65 -0
  157. package/mjs/utils/setHandlerSchema.d.ts +4 -0
  158. package/mjs/utils/setHandlerSchema.js +15 -0
  159. package/mjs/utils/shim.d.ts +1 -0
  160. package/mjs/utils/shim.js +18 -0
  161. package/mjs/utils/upperFirst.d.ts +1 -0
  162. package/mjs/utils/upperFirst.js +6 -0
  163. package/mjs/utils/withValidationLibrary.d.ts +78 -0
  164. package/mjs/utils/withValidationLibrary.js +133 -0
  165. package/package.json +28 -6
  166. package/.npmignore +0 -2
  167. package/StreamJSONResponse.d.ts +0 -17
  168. package/StreamJSONResponse.js +0 -54
  169. package/VovkApp.js +0 -185
  170. package/client/clientizeController.d.ts +0 -4
  171. package/client/clientizeController.js +0 -93
  172. package/client/defaultFetcher.d.ts +0 -4
  173. package/client/defaultFetcher.js +0 -49
  174. package/client/defaultHandler.d.ts +0 -2
  175. package/client/defaultStreamHandler.d.ts +0 -4
  176. package/client/index.d.ts +0 -4
  177. package/client/index.js +0 -5
  178. package/client/types.d.ts +0 -100
  179. package/createDecorator.d.ts +0 -4
  180. package/createVovkApp.js +0 -118
  181. package/index.d.ts +0 -60
  182. package/index.js +0 -20
  183. package/types.d.ts +0 -157
  184. package/utils/generateStaticAPI.js +0 -18
  185. package/utils/getSchema.d.ts +0 -8
  186. package/utils/getSchema.js +0 -38
  187. package/utils/reqForm.d.ts +0 -3
  188. package/utils/reqForm.js +0 -13
  189. package/utils/reqMeta.d.ts +0 -3
  190. package/utils/reqQuery.d.ts +0 -3
  191. package/utils/reqQuery.js +0 -25
  192. package/utils/setClientValidatorsForHandler.d.ts +0 -5
  193. package/utils/setClientValidatorsForHandler.js +0 -25
  194. package/worker/index.d.ts +0 -3
  195. package/worker/index.js +0 -7
  196. package/worker/promisifyWorker.d.ts +0 -2
  197. package/worker/promisifyWorker.js +0 -141
  198. package/worker/types.d.ts +0 -31
  199. package/worker/worker.d.ts +0 -1
  200. package/worker/worker.js +0 -43
  201. /package/{HttpException.d.ts → cjs/HttpException.d.ts} +0 -0
  202. /package/{HttpException.js → cjs/HttpException.js} +0 -0
  203. /package/{client → cjs/client}/types.js +0 -0
  204. /package/{utils → cjs/utils}/reqMeta.js +0 -0
  205. /package/{utils → cjs/utils}/shim.d.ts +0 -0
  206. /package/{utils → cjs/utils}/shim.js +0 -0
  207. /package/{worker → mjs/client}/types.js +0 -0
@@ -0,0 +1,18 @@
1
+ import type { PackageJson } from 'type-fest';
2
+ import type { VovkGeneratorConfig, VovkReadmeConfig, VovkSamplesConfig, VovkSchema } from '../types';
3
+ import type { OpenAPIObject } from 'openapi3-ts/oas31';
4
+ export declare function resolveGeneratorConfigValues({ schema, configs, segmentName, isBundle, projectPackageJson, }: {
5
+ schema: VovkSchema;
6
+ configs?: VovkGeneratorConfig[];
7
+ segmentName: string | null;
8
+ isBundle?: boolean;
9
+ projectPackageJson?: PackageJson;
10
+ }): {
11
+ readme: VovkReadmeConfig;
12
+ openAPIObject: OpenAPIObject;
13
+ samples: VovkSamplesConfig;
14
+ origin: string;
15
+ package: PackageJson;
16
+ imports: VovkGeneratorConfig['imports'];
17
+ reExports: VovkGeneratorConfig['reExports'];
18
+ };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolveGeneratorConfigValues = resolveGeneratorConfigValues;
7
+ const deepExtend_1 = __importDefault(require("./deepExtend"));
8
+ function resolveGeneratorConfigValues({ schema, configs, segmentName, isBundle, projectPackageJson, }) {
9
+ const packageJson = (0, deepExtend_1.default)({}, {
10
+ main: './index.cjs',
11
+ module: './index.mjs',
12
+ types: './index.d.mts',
13
+ exports: {
14
+ '.': {
15
+ import: './index.mjs',
16
+ require: './index.cjs',
17
+ types: './index.d.mts',
18
+ },
19
+ './schema': {
20
+ import: './schema.cjs',
21
+ require: './schema.cjs',
22
+ types: './schema.d.cts',
23
+ },
24
+ './openapi': {
25
+ import: './openapi.cjs',
26
+ require: './openapi.cjs',
27
+ types: './openapi.d.cts',
28
+ },
29
+ },
30
+ }, projectPackageJson, schema.meta?.config?.generatorConfig?.package, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.package : undefined, typeof segmentName === 'string' ? schema.segments?.[segmentName]?.meta?.package : undefined, typeof segmentName === 'string'
31
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.package
32
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.package), {}));
33
+ return {
34
+ package: Object.fromEntries(Object.entries(packageJson).filter(([key]) => ['name', 'version', 'description', 'license', 'authors', 'repository', 'homepage', 'bugs', 'keywords'].includes(key))),
35
+ openAPIObject: (0, deepExtend_1.default)({}, {
36
+ openapi: '3.1.0',
37
+ info: {
38
+ title: packageJson.name,
39
+ version: packageJson.version,
40
+ description: packageJson.description,
41
+ },
42
+ }, schema.meta?.config?.generatorConfig?.openAPIObject, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.openAPIObject : undefined, typeof segmentName === 'string' ? schema?.segments?.[segmentName]?.meta?.openAPIObject : undefined, typeof segmentName === 'string'
43
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.openAPIObject
44
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.openAPIObject), {})),
45
+ samples: (0, deepExtend_1.default)({}, schema.meta?.config?.generatorConfig?.samples, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.samples : undefined, typeof segmentName === 'string'
46
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.samples
47
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.samples), {})),
48
+ readme: (0, deepExtend_1.default)({}, schema.meta?.config?.generatorConfig?.readme, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.readme : undefined, typeof segmentName === 'string'
49
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.readme
50
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.readme), {})),
51
+ origin: [
52
+ isBundle ? schema.meta?.config?.bundle?.generatorConfig?.origin : undefined,
53
+ typeof segmentName === 'string'
54
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.origin
55
+ : undefined,
56
+ schema.meta?.config?.generatorConfig?.origin,
57
+ ...(configs?.map((config) => config.origin) ?? []),
58
+ ]
59
+ .filter(Boolean)
60
+ .at(-1)
61
+ // remove trailing slash if any
62
+ ?.replace(/\/$/, '') ?? '',
63
+ imports: (0, deepExtend_1.default)({
64
+ fetcher: ['vovk'],
65
+ validateOnClient: null,
66
+ createRPC: ['vovk'],
67
+ }, schema.meta?.config?.generatorConfig?.imports, isBundle ? schema.meta?.config?.bundle?.generatorConfig?.imports : undefined, typeof segmentName === 'string'
68
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.imports
69
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.imports), {})),
70
+ reExports: (0, deepExtend_1.default)(
71
+ // segmentName can be an empty string (for the root segment) and null (for composed clients)
72
+ // therefore, !segmentName indicates that this either a composed client or a root segment of a segmented client
73
+ {}, !segmentName && schema.meta?.config?.generatorConfig?.reExports, !segmentName && isBundle ? schema.meta?.config?.bundle?.generatorConfig?.reExports : undefined,
74
+ // for segmented client, apply all reExports from all segments
75
+ typeof segmentName !== 'string' &&
76
+ Object.values(schema.meta?.config?.generatorConfig?.segments ?? {}).reduce((acc, segmentConfig) => (0, deepExtend_1.default)(acc, segmentConfig.reExports ?? {}), {}),
77
+ // for a specific segment, apply reExports from that segment
78
+ typeof segmentName === 'string'
79
+ ? schema.meta?.config?.generatorConfig?.segments?.[segmentName]?.reExports
80
+ : undefined, configs?.reduce((acc, config) => (0, deepExtend_1.default)(acc, config.reExports), {})),
81
+ };
82
+ }
@@ -0,0 +1,13 @@
1
+ import type { KnownAny } from '../types';
2
+ /**
3
+ * Serialize a nested object (including arrays, arrays of objects, etc.)
4
+ * into a bracket-based query string.
5
+ *
6
+ * @example
7
+ * serializeQuery({ x: 'xx', y: [1, 2], z: { f: 'x' } })
8
+ * => "x=xx&y[0]=1&y[1]=2&z[f]=x"
9
+ *
10
+ * @param obj - The input object to be serialized
11
+ * @returns - A bracket-based query string (without leading "?")
12
+ */
13
+ export default function serializeQuery(obj: Record<string, KnownAny>): string;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = serializeQuery;
4
+ /**
5
+ * Recursively build query parameters from an object.
6
+ *
7
+ * @param key - The query key so far (e.g. 'user', 'user[0]', 'user[0][name]')
8
+ * @param value - The current value to serialize
9
+ * @returns - An array of `key=value` strings
10
+ */
11
+ function buildParams(key, value) {
12
+ if (value === null || value === undefined) {
13
+ return []; // skip null/undefined values entirely
14
+ }
15
+ // If value is an object or array, we need to recurse
16
+ if (typeof value === 'object') {
17
+ // Array case
18
+ if (Array.isArray(value)) {
19
+ /**
20
+ * We use index-based bracket notation here:
21
+ * e.g. for value = ['aa', 'bb'] and key = 'foo'
22
+ * => "foo[0]=aa&foo[1]=bb"
23
+ *
24
+ * If you prefer "foo[]=aa&foo[]=bb" style, replace:
25
+ * `${key}[${i}]`
26
+ * with:
27
+ * `${key}[]`
28
+ */
29
+ return value.flatMap((v, i) => {
30
+ const newKey = `${key}[${i}]`;
31
+ return buildParams(newKey, v);
32
+ });
33
+ }
34
+ // Plain object case
35
+ return Object.keys(value).flatMap((k) => {
36
+ const newKey = `${key}[${k}]`;
37
+ return buildParams(newKey, value[k]);
38
+ });
39
+ }
40
+ return [`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`];
41
+ }
42
+ /**
43
+ * Serialize a nested object (including arrays, arrays of objects, etc.)
44
+ * into a bracket-based query string.
45
+ *
46
+ * @example
47
+ * serializeQuery({ x: 'xx', y: [1, 2], z: { f: 'x' } })
48
+ * => "x=xx&y[0]=1&y[1]=2&z[f]=x"
49
+ *
50
+ * @param obj - The input object to be serialized
51
+ * @returns - A bracket-based query string (without leading "?")
52
+ */
53
+ function serializeQuery(obj) {
54
+ if (!obj || typeof obj !== 'object')
55
+ return '';
56
+ // Collect query segments
57
+ const segments = [];
58
+ for (const key in obj) {
59
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
60
+ const value = obj[key];
61
+ segments.push(...buildParams(key, value));
62
+ }
63
+ }
64
+ return segments.join('&');
65
+ }
@@ -0,0 +1,4 @@
1
+ import type { KnownAny, VovkController, VovkHandlerSchema } from '../types';
2
+ export declare function setHandlerSchema(h: ((...args: KnownAny[]) => KnownAny) & {
3
+ _getSchema?: (controller: VovkController) => Omit<VovkHandlerSchema, 'httpMethod' | 'path'>;
4
+ }, schema: Omit<VovkHandlerSchema, 'httpMethod' | 'path'>): Promise<void>;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setHandlerSchema = setHandlerSchema;
4
+ async function setHandlerSchema(h, schema) {
5
+ h._getSchema = (controller) => {
6
+ if (!controller) {
7
+ throw new Error('Error setting client validators. Controller not found. Did you forget to use an HTTP decorator?');
8
+ }
9
+ const handlerName = Object.getOwnPropertyNames(controller).find((key) => controller[key]._sourceMethod === h);
10
+ if (!handlerName) {
11
+ throw new Error('Error setting client validators. Handler not found.');
12
+ }
13
+ return schema;
14
+ };
15
+ }
@@ -0,0 +1 @@
1
+ export declare function upperFirst(str: string): string;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.upperFirst = upperFirst;
4
+ function upperFirst(str) {
5
+ return str.charAt(0).toUpperCase() + str.slice(1);
6
+ }
@@ -0,0 +1,78 @@
1
+ import { VovkHandlerSchema, VovkTypedMethod, VovkValidationType, type KnownAny, type VovkRequest, type VovkOperationObject } from '../types';
2
+ type VovkRequestAny = VovkRequest<KnownAny, KnownAny, KnownAny>;
3
+ type Meta = {
4
+ __disableClientValidation?: boolean;
5
+ [key: string]: KnownAny;
6
+ };
7
+ export declare function withValidationLibrary<T extends VovkTypedMethod<(req: KnownAny, params: KnownAny) => KnownAny, KnownAny, KnownAny, KnownAny, KnownAny, KnownAny, boolean>, TBody_MODEL, TQuery_MODEL, TParams_MODEL, OUTPUT_MODEL, ITERATION_MODEL, IS_FORM extends boolean = false>({ isForm, disableServerSideValidation, skipSchemaEmission, validateEachIteration, body, query, params, output, iteration, handle, toJSONSchema, validate, preferTransformed, operationObject, }: {
8
+ isForm: IS_FORM | undefined;
9
+ disableServerSideValidation: boolean | VovkValidationType[] | undefined;
10
+ skipSchemaEmission: boolean | VovkValidationType[] | undefined;
11
+ validateEachIteration: boolean | undefined;
12
+ body: TBody_MODEL | undefined;
13
+ query: TQuery_MODEL | undefined;
14
+ params: TParams_MODEL | undefined;
15
+ output: OUTPUT_MODEL | undefined;
16
+ iteration: ITERATION_MODEL | undefined;
17
+ handle: T;
18
+ toJSONSchema: ((model: KnownAny, // performance concern
19
+ meta: {
20
+ type: VovkValidationType;
21
+ }) => KnownAny) | undefined;
22
+ validate: (data: KnownAny, model: NonNullable<TBody_MODEL | TQuery_MODEL | TParams_MODEL | OUTPUT_MODEL | ITERATION_MODEL>, meta: {
23
+ type: VovkValidationType | 'form';
24
+ req: VovkRequestAny;
25
+ status?: number;
26
+ i?: number;
27
+ }) => KnownAny;
28
+ preferTransformed: boolean | undefined;
29
+ operationObject: VovkOperationObject | undefined;
30
+ }): T & {
31
+ schema: Omit<VovkHandlerSchema, "httpMethod" | "path"> & Partial<VovkHandlerSchema>;
32
+ wrapper?: (req: VovkRequestAny, params: Parameters<T>[1]) => ReturnType<T>;
33
+ } & {
34
+ fn: {
35
+ <RETURN_TYPE = ReturnType<T>>(input?: (undefined extends TBody_MODEL | undefined ? undefined extends TQuery_MODEL | undefined ? undefined extends TParams_MODEL | undefined ? true : false : false : false) extends true ? {
36
+ disableClientValidation?: boolean;
37
+ } & (undefined extends TBody_MODEL | undefined ? {
38
+ body?: T["__types"]["body"];
39
+ } : {
40
+ body: T["__types"]["body"];
41
+ }) & (undefined extends TQuery_MODEL | undefined ? {
42
+ query?: T["__types"]["query"];
43
+ } : {
44
+ query: T["__types"]["query"];
45
+ }) & (undefined extends TParams_MODEL | undefined ? {
46
+ params?: T["__types"]["params"];
47
+ } : {
48
+ params: T["__types"]["params"];
49
+ }) & {
50
+ meta?: Meta;
51
+ } : never): (undefined extends TBody_MODEL | undefined ? undefined extends TQuery_MODEL | undefined ? undefined extends TParams_MODEL | undefined ? true : false : false : false) extends true ? RETURN_TYPE : never;
52
+ <RETURN_TYPE = ReturnType<T>>(input: {
53
+ disableClientValidation?: boolean;
54
+ } & (undefined extends TBody_MODEL | undefined ? {
55
+ body?: T["__types"]["body"];
56
+ } : {
57
+ body: T["__types"]["body"];
58
+ }) & (undefined extends TQuery_MODEL | undefined ? {
59
+ query?: T["__types"]["query"];
60
+ } : {
61
+ query: T["__types"]["query"];
62
+ }) & (undefined extends TParams_MODEL | undefined ? {
63
+ params?: T["__types"]["params"];
64
+ } : {
65
+ params: T["__types"]["params"];
66
+ }) & {
67
+ meta?: Meta;
68
+ }): RETURN_TYPE;
69
+ };
70
+ models: {
71
+ iteration?: (ITERATION_MODEL & ({} | null)) | undefined;
72
+ output?: (OUTPUT_MODEL & ({} | null)) | undefined;
73
+ params?: (TParams_MODEL & ({} | null)) | undefined;
74
+ query?: (TQuery_MODEL & ({} | null)) | undefined;
75
+ body?: (TBody_MODEL & ({} | null)) | undefined;
76
+ };
77
+ };
78
+ export {};
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.withValidationLibrary = withValidationLibrary;
7
+ const HttpException_1 = require("../HttpException");
8
+ const types_1 = require("../types");
9
+ const reqMeta_1 = __importDefault(require("./reqMeta"));
10
+ const setHandlerSchema_1 = require("./setHandlerSchema");
11
+ const validationTypes = ['body', 'query', 'params', 'output', 'iteration'];
12
+ function withValidationLibrary({ isForm, disableServerSideValidation, skipSchemaEmission, validateEachIteration, body, query, params, output, iteration, handle, toJSONSchema, validate, preferTransformed, operationObject, }) {
13
+ preferTransformed = preferTransformed ?? true;
14
+ const disableServerSideValidationKeys = disableServerSideValidation === false
15
+ ? []
16
+ : disableServerSideValidation === true
17
+ ? validationTypes
18
+ : (disableServerSideValidation ?? []);
19
+ const skipSchemaEmissionKeys = skipSchemaEmission === false ? [] : skipSchemaEmission === true ? validationTypes : (skipSchemaEmission ?? []);
20
+ const outputHandler = async (req, handlerParams) => {
21
+ const { __disableClientValidation } = req.vovk.meta();
22
+ const data = await handle(req, handlerParams);
23
+ if (__disableClientValidation) {
24
+ return data;
25
+ }
26
+ if (output && iteration) {
27
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, "Output and iteration are mutually exclusive. You can't use them together.");
28
+ }
29
+ if (output && !disableServerSideValidationKeys.includes('output')) {
30
+ if (!data) {
31
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, 'Output is required. You probably forgot to return something from your handler.');
32
+ }
33
+ const parsed = (await validate(data, output, { type: 'output', req })) ?? data;
34
+ return preferTransformed ? parsed : data;
35
+ }
36
+ if (iteration && !disableServerSideValidationKeys.includes('iteration')) {
37
+ // We assume `data` is an async iterable here; you might want to check that:
38
+ if (!data || typeof data[Symbol.asyncIterator] !== 'function') {
39
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, 'Data is not an async iterable but iteration validation is defined.');
40
+ }
41
+ // Return a brand-new async generator that yields validated items
42
+ return (async function* () {
43
+ let i = 0;
44
+ for await (const item of data) {
45
+ let parsed;
46
+ if (validateEachIteration || i === 0) {
47
+ parsed = (await validate(item, iteration, { type: 'iteration', req, status: 200, i })) ?? item;
48
+ }
49
+ else {
50
+ parsed = item;
51
+ }
52
+ i++;
53
+ yield preferTransformed ? parsed : item;
54
+ }
55
+ })();
56
+ }
57
+ else if (validateEachIteration) {
58
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, 'validateEachIteration is set but iteration is not defined.');
59
+ }
60
+ return data;
61
+ };
62
+ const resultHandler = (async (req, handlerParams) => {
63
+ const { __disableClientValidation } = req.vovk.meta();
64
+ if (!__disableClientValidation) {
65
+ if (body && !disableServerSideValidationKeys.includes('body')) {
66
+ const data = await req.vovk[isForm ? 'form' : 'body']();
67
+ const parsed = (await validate(data, body, { type: isForm ? 'form' : 'body', req })) ?? data;
68
+ const instance = preferTransformed ? parsed : data;
69
+ // redeclare to add ability to call req.json() and req.vovk.body() again
70
+ req.json = () => Promise.resolve(data);
71
+ req.vovk[isForm ? 'form' : 'body'] = () => Promise.resolve(instance);
72
+ }
73
+ if (query && !disableServerSideValidationKeys.includes('query')) {
74
+ const data = req.vovk.query();
75
+ const parsed = (await validate(data, query, { type: 'query', req })) ?? data;
76
+ const instance = preferTransformed ? parsed : data;
77
+ req.vovk.query = () => instance;
78
+ }
79
+ if (params && !disableServerSideValidationKeys.includes('params')) {
80
+ const data = req.vovk.params();
81
+ const parsed = (await validate(data, params, { type: 'params', req })) ?? data;
82
+ const instance = preferTransformed ? parsed : data;
83
+ req.vovk.params = () => instance;
84
+ }
85
+ }
86
+ return outputHandler(req, handlerParams);
87
+ });
88
+ function fn(input) {
89
+ const fakeReq = {
90
+ vovk: {
91
+ body: () => Promise.resolve((input?.body ?? {})),
92
+ query: () => (input?.query ?? {}),
93
+ params: () => (input?.params ?? {}),
94
+ meta: (meta) => (0, reqMeta_1.default)(fakeReq, meta),
95
+ form: () => {
96
+ throw new Error('Form data is not supported in this context.');
97
+ },
98
+ },
99
+ };
100
+ fakeReq.vovk.meta({ __disableClientValidation: input?.disableClientValidation, ...input?.meta });
101
+ return (resultHandler.wrapper ?? resultHandler)(fakeReq, (input?.params ?? {}));
102
+ }
103
+ const models = {
104
+ ...(body !== undefined ? { body } : {}),
105
+ ...(query !== undefined ? { query } : {}),
106
+ ...(params !== undefined ? { params } : {}),
107
+ ...(output !== undefined ? { output } : {}),
108
+ ...(iteration !== undefined ? { iteration } : {}),
109
+ };
110
+ const resultHandlerEnhanced = Object.assign(resultHandler, { fn, models });
111
+ if (toJSONSchema) {
112
+ const getJSONSchema = (model, type) => Object.assign(toJSONSchema(model, { type }), type === 'body' && isForm ? { 'x-isForm': isForm } : {});
113
+ const validation = {};
114
+ if (body && !skipSchemaEmissionKeys.includes('body')) {
115
+ validation.body = getJSONSchema(body, 'body');
116
+ }
117
+ if (query && !skipSchemaEmissionKeys.includes('query')) {
118
+ validation.query = getJSONSchema(query, 'query');
119
+ }
120
+ if (params && !skipSchemaEmissionKeys.includes('params')) {
121
+ validation.params = getJSONSchema(params, 'params');
122
+ }
123
+ if (output && !skipSchemaEmissionKeys.includes('output')) {
124
+ validation.output = getJSONSchema(output, 'output');
125
+ }
126
+ if (iteration && !skipSchemaEmissionKeys.includes('iteration')) {
127
+ validation.iteration = getJSONSchema(iteration, 'iteration');
128
+ }
129
+ resultHandlerEnhanced.schema = { validation, operationObject };
130
+ (0, setHandlerSchema_1.setHandlerSchema)(resultHandlerEnhanced, { validation, operationObject });
131
+ }
132
+ return resultHandlerEnhanced;
133
+ }
@@ -0,0 +1,7 @@
1
+ import type { HttpStatus } from './types';
2
+ export declare class HttpException extends Error {
3
+ statusCode: HttpStatus;
4
+ message: string;
5
+ cause?: unknown;
6
+ constructor(statusCode: HttpStatus, message: string, cause?: unknown);
7
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpException = void 0;
4
+ class HttpException extends Error {
5
+ statusCode;
6
+ message;
7
+ cause;
8
+ constructor(statusCode, message, cause) {
9
+ super(message);
10
+ this.statusCode = statusCode;
11
+ this.message = message;
12
+ this.cause = cause;
13
+ }
14
+ }
15
+ exports.HttpException = HttpException;
@@ -0,0 +1,19 @@
1
+ import type { KnownAny, StreamAbortMessage } from './types';
2
+ import './utils/shim';
3
+ export declare class JSONLinesResponse<T> extends Response {
4
+ isClosed: boolean;
5
+ controller?: ReadableStreamDefaultController | null;
6
+ readonly encoder: TextEncoder | null;
7
+ readonly readableStream: ReadableStream | null;
8
+ private iteratorQueue;
9
+ private iteratorResolvers;
10
+ constructor(request?: Request, init?: ResponseInit);
11
+ send: (data: T | StreamAbortMessage) => void;
12
+ close: () => void;
13
+ throw: (e: KnownAny) => void;
14
+ [Symbol.dispose]: () => void;
15
+ [Symbol.asyncDispose]: () => void;
16
+ [Symbol.asyncIterator]: () => {
17
+ next: () => Promise<IteratorResult<T | StreamAbortMessage>>;
18
+ };
19
+ }
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JSONLinesResponse = void 0;
4
+ require("./utils/shim");
5
+ class JSONLinesResponse extends Response {
6
+ isClosed = false;
7
+ controller;
8
+ encoder;
9
+ readableStream;
10
+ iteratorQueue = [];
11
+ iteratorResolvers = [];
12
+ constructor(request, init) {
13
+ const encoder = new TextEncoder();
14
+ let readableController;
15
+ const readableStream = new ReadableStream({
16
+ cancel: () => {
17
+ this.isClosed = true;
18
+ },
19
+ start: (controller) => {
20
+ readableController = controller;
21
+ },
22
+ });
23
+ const accept = request?.headers?.get('accept');
24
+ super(readableStream, {
25
+ ...init,
26
+ headers: {
27
+ 'content-type': !request || accept?.includes('application/jsonl')
28
+ ? 'application/jsonl; charset=utf-8'
29
+ : 'text/plain; charset=utf-8',
30
+ ...init?.headers,
31
+ },
32
+ });
33
+ this.readableStream = request ? readableStream : null;
34
+ this.encoder = request ? encoder : null;
35
+ this.controller = request ? readableController : null;
36
+ request?.signal?.addEventListener('abort', this.close, { once: true });
37
+ // this will make promise on the client-side to resolve immediately
38
+ this.controller?.enqueue(encoder?.encode(''));
39
+ }
40
+ send = (data) => {
41
+ const { controller, encoder } = this;
42
+ if (this.isClosed)
43
+ return;
44
+ // Enqueue to the ReadableStream
45
+ controller?.enqueue(encoder?.encode(JSON.stringify(data) + '\n'));
46
+ // Handle async iterator consumers
47
+ if (this.iteratorResolvers.length > 0) {
48
+ // If there's a pending next() call, resolve it immediately
49
+ const resolve = this.iteratorResolvers.shift();
50
+ resolve({ value: data, done: false });
51
+ }
52
+ else {
53
+ // Otherwise, queue the value for later consumption
54
+ this.iteratorQueue.push(data);
55
+ }
56
+ };
57
+ close = () => {
58
+ const { controller } = this;
59
+ if (this.isClosed)
60
+ return;
61
+ this.isClosed = true;
62
+ controller?.close();
63
+ // Resolve all pending iterator next() calls with done: true
64
+ while (this.iteratorResolvers.length > 0) {
65
+ const resolve = this.iteratorResolvers.shift();
66
+ resolve({ done: true, value: undefined });
67
+ }
68
+ };
69
+ throw = (e) => {
70
+ this.send({ isError: true, reason: e instanceof Error ? e.message : e });
71
+ return this.close();
72
+ };
73
+ [Symbol.dispose] = () => this.close();
74
+ [Symbol.asyncDispose] = () => this.close();
75
+ [Symbol.asyncIterator] = () => {
76
+ return {
77
+ next: async () => {
78
+ // If we have queued values, return them immediately
79
+ if (this.iteratorQueue.length > 0) {
80
+ const value = this.iteratorQueue.shift();
81
+ return { value, done: false };
82
+ }
83
+ // If the stream is closed and no more values, we're done
84
+ if (this.isClosed) {
85
+ return { done: true, value: undefined };
86
+ }
87
+ // Otherwise, wait for the next value or close
88
+ return new Promise((resolve) => {
89
+ this.iteratorResolvers.push(resolve);
90
+ });
91
+ },
92
+ };
93
+ };
94
+ }
95
+ exports.JSONLinesResponse = JSONLinesResponse;
@@ -0,0 +1,34 @@
1
+ import type { NextRequest } from 'next/server';
2
+ import { HttpMethod, HttpStatus, type RouteHandler, type VovkController, type DecoratorOptions, type VovkRequest } from './types';
3
+ export declare class VovkApp {
4
+ #private;
5
+ private static getHeadersFromOptions;
6
+ routes: Record<HttpMethod, Map<VovkController, Record<string, RouteHandler>>>;
7
+ GET: (req: NextRequest, data: {
8
+ params: Promise<Record<string, string[]>>;
9
+ }) => Promise<Response>;
10
+ POST: (req: NextRequest, data: {
11
+ params: Promise<Record<string, string[]>>;
12
+ }) => Promise<Response>;
13
+ PUT: (req: NextRequest, data: {
14
+ params: Promise<Record<string, string[]>>;
15
+ }) => Promise<Response>;
16
+ PATCH: (req: NextRequest, data: {
17
+ params: Promise<Record<string, string[]>>;
18
+ }) => Promise<Response>;
19
+ DELETE: (req: NextRequest, data: {
20
+ params: Promise<Record<string, string[]>>;
21
+ }) => Promise<Response>;
22
+ HEAD: (req: NextRequest, data: {
23
+ params: Promise<Record<string, string[]>>;
24
+ }) => Promise<Response>;
25
+ OPTIONS: (req: NextRequest, data: {
26
+ params: Promise<Record<string, string[]>>;
27
+ }) => Promise<Response>;
28
+ respond: ({ statusCode, responseBody, options, }: {
29
+ req: VovkRequest;
30
+ statusCode: HttpStatus;
31
+ responseBody: unknown;
32
+ options?: DecoratorOptions;
33
+ }) => Promise<Response>;
34
+ }