vovk 3.0.0-draft.33 → 3.0.0-draft.331

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 (196) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +8 -96
  3. package/bin/index.mjs +8 -0
  4. package/{HttpException.d.ts → cjs/HttpException.d.ts} +2 -2
  5. package/{HttpException.js → cjs/HttpException.js} +3 -3
  6. package/cjs/JSONLinesResponse.d.ts +19 -0
  7. package/cjs/JSONLinesResponse.js +93 -0
  8. package/{VovkApp.d.ts → cjs/VovkApp.d.ts} +10 -9
  9. package/cjs/VovkApp.js +202 -0
  10. package/cjs/client/createRPC.d.ts +3 -0
  11. package/cjs/client/createRPC.js +90 -0
  12. package/cjs/client/defaultHandler.d.ts +6 -0
  13. package/cjs/client/defaultHandler.js +29 -0
  14. package/cjs/client/defaultStreamHandler.d.ts +9 -0
  15. package/{client → cjs/client}/defaultStreamHandler.js +25 -13
  16. package/cjs/client/fetcher.d.ts +14 -0
  17. package/cjs/client/fetcher.js +93 -0
  18. package/cjs/client/index.d.ts +4 -0
  19. package/cjs/client/index.js +10 -0
  20. package/cjs/client/progressive.d.ts +9 -0
  21. package/cjs/client/progressive.js +45 -0
  22. package/cjs/client/types.d.ts +123 -0
  23. package/{createVovkApp.d.ts → cjs/createVovkApp.d.ts} +12 -11
  24. package/cjs/createVovkApp.js +133 -0
  25. package/cjs/index.d.ts +65 -0
  26. package/cjs/index.js +38 -0
  27. package/cjs/openapi/error.d.ts +2 -0
  28. package/cjs/openapi/error.js +100 -0
  29. package/cjs/openapi/generateFnName.d.ts +23 -0
  30. package/cjs/openapi/generateFnName.js +81 -0
  31. package/cjs/openapi/index.d.ts +12 -0
  32. package/cjs/openapi/index.js +21 -0
  33. package/cjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.d.ts +3 -0
  34. package/cjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.js +67 -0
  35. package/cjs/openapi/openAPIToVovkSchema/index.d.ts +4 -0
  36. package/cjs/openapi/openAPIToVovkSchema/index.js +192 -0
  37. package/cjs/openapi/openAPIToVovkSchema/inlineRefs.d.ts +10 -0
  38. package/cjs/openapi/openAPIToVovkSchema/inlineRefs.js +102 -0
  39. package/cjs/openapi/vovkSchemaToOpenAPI.d.ts +9 -0
  40. package/cjs/openapi/vovkSchemaToOpenAPI.js +233 -0
  41. package/cjs/types.d.ts +400 -0
  42. package/cjs/types.js +74 -0
  43. package/cjs/utils/camelCase.d.ts +6 -0
  44. package/cjs/utils/camelCase.js +37 -0
  45. package/cjs/utils/createCodeExamples.d.ts +19 -0
  46. package/cjs/utils/createCodeExamples.js +110 -0
  47. package/cjs/utils/createDecorator.d.ts +6 -0
  48. package/{createDecorator.js → cjs/utils/createDecorator.js} +26 -16
  49. package/cjs/utils/createLLMTools.d.ts +44 -0
  50. package/cjs/utils/createLLMTools.js +118 -0
  51. package/cjs/utils/createStandardValidation.d.ts +81 -0
  52. package/cjs/utils/createStandardValidation.js +33 -0
  53. package/cjs/utils/generateStaticAPI.d.ts +4 -0
  54. package/cjs/utils/generateStaticAPI.js +30 -0
  55. package/cjs/utils/getJSONSchemaExample.d.ts +8 -0
  56. package/cjs/utils/getJSONSchemaExample.js +234 -0
  57. package/cjs/utils/getJSONSchemaSample.d.ts +2 -0
  58. package/cjs/utils/getJSONSchemaSample.js +167 -0
  59. package/cjs/utils/getSchema.d.ts +21 -0
  60. package/cjs/utils/getSchema.js +38 -0
  61. package/cjs/utils/multitenant.d.ts +24 -0
  62. package/cjs/utils/multitenant.js +170 -0
  63. package/cjs/utils/parseQuery.d.ts +25 -0
  64. package/cjs/utils/parseQuery.js +156 -0
  65. package/{utils → cjs/utils}/reqForm.d.ts +1 -2
  66. package/cjs/utils/reqForm.js +33 -0
  67. package/{utils → cjs/utils}/reqMeta.d.ts +1 -2
  68. package/cjs/utils/reqQuery.d.ts +2 -0
  69. package/cjs/utils/reqQuery.js +10 -0
  70. package/cjs/utils/serializeQuery.d.ts +13 -0
  71. package/cjs/utils/serializeQuery.js +65 -0
  72. package/cjs/utils/setHandlerSchema.d.ts +4 -0
  73. package/cjs/utils/setHandlerSchema.js +15 -0
  74. package/cjs/utils/upperFirst.d.ts +1 -0
  75. package/cjs/utils/upperFirst.js +6 -0
  76. package/cjs/utils/withValidationLibrary.d.ts +76 -0
  77. package/cjs/utils/withValidationLibrary.js +123 -0
  78. package/mjs/HttpException.d.ts +7 -0
  79. package/mjs/HttpException.js +15 -0
  80. package/mjs/JSONLinesResponse.d.ts +19 -0
  81. package/mjs/JSONLinesResponse.js +93 -0
  82. package/mjs/VovkApp.d.ts +29 -0
  83. package/mjs/VovkApp.js +202 -0
  84. package/mjs/client/createRPC.d.ts +3 -0
  85. package/mjs/client/createRPC.js +90 -0
  86. package/mjs/client/defaultHandler.d.ts +6 -0
  87. package/mjs/client/defaultHandler.js +29 -0
  88. package/mjs/client/defaultStreamHandler.d.ts +9 -0
  89. package/mjs/client/defaultStreamHandler.js +94 -0
  90. package/mjs/client/fetcher.d.ts +14 -0
  91. package/mjs/client/fetcher.js +93 -0
  92. package/mjs/client/index.d.ts +4 -0
  93. package/mjs/client/index.js +10 -0
  94. package/mjs/client/progressive.d.ts +9 -0
  95. package/mjs/client/progressive.js +45 -0
  96. package/mjs/client/types.d.ts +123 -0
  97. package/mjs/createVovkApp.d.ts +63 -0
  98. package/mjs/createVovkApp.js +133 -0
  99. package/mjs/index.d.ts +65 -0
  100. package/mjs/index.js +38 -0
  101. package/mjs/openapi/error.d.ts +2 -0
  102. package/mjs/openapi/error.js +100 -0
  103. package/mjs/openapi/generateFnName.d.ts +23 -0
  104. package/mjs/openapi/generateFnName.js +81 -0
  105. package/mjs/openapi/index.d.ts +12 -0
  106. package/mjs/openapi/index.js +21 -0
  107. package/mjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.d.ts +3 -0
  108. package/mjs/openapi/openAPIToVovkSchema/applyComponentsSchemas.js +67 -0
  109. package/mjs/openapi/openAPIToVovkSchema/index.d.ts +4 -0
  110. package/mjs/openapi/openAPIToVovkSchema/index.js +192 -0
  111. package/mjs/openapi/openAPIToVovkSchema/inlineRefs.d.ts +10 -0
  112. package/mjs/openapi/openAPIToVovkSchema/inlineRefs.js +102 -0
  113. package/mjs/openapi/vovkSchemaToOpenAPI.d.ts +9 -0
  114. package/mjs/openapi/vovkSchemaToOpenAPI.js +233 -0
  115. package/mjs/types.d.ts +400 -0
  116. package/mjs/types.js +74 -0
  117. package/mjs/utils/camelCase.d.ts +6 -0
  118. package/mjs/utils/camelCase.js +37 -0
  119. package/mjs/utils/createCodeExamples.d.ts +19 -0
  120. package/mjs/utils/createCodeExamples.js +110 -0
  121. package/mjs/utils/createDecorator.d.ts +6 -0
  122. package/mjs/utils/createDecorator.js +48 -0
  123. package/mjs/utils/createLLMTools.d.ts +44 -0
  124. package/mjs/utils/createLLMTools.js +118 -0
  125. package/mjs/utils/createStandardValidation.d.ts +81 -0
  126. package/mjs/utils/createStandardValidation.js +33 -0
  127. package/mjs/utils/generateStaticAPI.d.ts +4 -0
  128. package/mjs/utils/generateStaticAPI.js +30 -0
  129. package/mjs/utils/getJSONSchemaExample.d.ts +8 -0
  130. package/mjs/utils/getJSONSchemaExample.js +234 -0
  131. package/mjs/utils/getJSONSchemaSample.d.ts +2 -0
  132. package/mjs/utils/getJSONSchemaSample.js +167 -0
  133. package/mjs/utils/getSchema.d.ts +21 -0
  134. package/mjs/utils/getSchema.js +38 -0
  135. package/mjs/utils/multitenant.d.ts +24 -0
  136. package/mjs/utils/multitenant.js +170 -0
  137. package/mjs/utils/parseQuery.d.ts +25 -0
  138. package/mjs/utils/parseQuery.js +156 -0
  139. package/mjs/utils/reqForm.d.ts +2 -0
  140. package/mjs/utils/reqForm.js +33 -0
  141. package/mjs/utils/reqMeta.d.ts +2 -0
  142. package/mjs/utils/reqMeta.js +13 -0
  143. package/mjs/utils/reqQuery.d.ts +2 -0
  144. package/mjs/utils/reqQuery.js +10 -0
  145. package/mjs/utils/serializeQuery.d.ts +13 -0
  146. package/mjs/utils/serializeQuery.js +65 -0
  147. package/mjs/utils/setHandlerSchema.d.ts +4 -0
  148. package/mjs/utils/setHandlerSchema.js +15 -0
  149. package/mjs/utils/shim.d.ts +1 -0
  150. package/mjs/utils/shim.js +18 -0
  151. package/mjs/utils/upperFirst.d.ts +1 -0
  152. package/mjs/utils/upperFirst.js +6 -0
  153. package/mjs/utils/withValidationLibrary.d.ts +76 -0
  154. package/mjs/utils/withValidationLibrary.js +123 -0
  155. package/package.json +29 -6
  156. package/.npmignore +0 -2
  157. package/StreamJSONResponse.d.ts +0 -17
  158. package/StreamJSONResponse.js +0 -54
  159. package/VovkApp.js +0 -185
  160. package/client/clientizeController.d.ts +0 -4
  161. package/client/clientizeController.js +0 -92
  162. package/client/defaultFetcher.d.ts +0 -4
  163. package/client/defaultFetcher.js +0 -49
  164. package/client/defaultHandler.d.ts +0 -2
  165. package/client/defaultHandler.js +0 -22
  166. package/client/defaultStreamHandler.d.ts +0 -4
  167. package/client/index.d.ts +0 -4
  168. package/client/index.js +0 -5
  169. package/client/types.d.ts +0 -100
  170. package/createDecorator.d.ts +0 -4
  171. package/createVovkApp.js +0 -118
  172. package/index.d.ts +0 -60
  173. package/index.js +0 -20
  174. package/types.d.ts +0 -157
  175. package/types.js +0 -65
  176. package/utils/generateStaticAPI.d.ts +0 -4
  177. package/utils/generateStaticAPI.js +0 -18
  178. package/utils/getSchema.d.ts +0 -8
  179. package/utils/getSchema.js +0 -38
  180. package/utils/reqForm.js +0 -13
  181. package/utils/reqQuery.d.ts +0 -3
  182. package/utils/reqQuery.js +0 -25
  183. package/utils/setClientValidatorsForHandler.d.ts +0 -5
  184. package/utils/setClientValidatorsForHandler.js +0 -25
  185. package/worker/index.d.ts +0 -3
  186. package/worker/index.js +0 -7
  187. package/worker/promisifyWorker.d.ts +0 -2
  188. package/worker/promisifyWorker.js +0 -141
  189. package/worker/types.d.ts +0 -31
  190. package/worker/worker.d.ts +0 -1
  191. package/worker/worker.js +0 -43
  192. /package/{client → cjs/client}/types.js +0 -0
  193. /package/{utils → cjs/utils}/reqMeta.js +0 -0
  194. /package/{utils → cjs/utils}/shim.d.ts +0 -0
  195. /package/{utils → cjs/utils}/shim.js +0 -0
  196. /package/{worker → mjs/client}/types.js +0 -0
package/LICENSE CHANGED
@@ -16,7 +16,7 @@
16
16
  "nextjs",
17
17
  "router"
18
18
  ],
19
- "author": "Andrii Gubanov",
19
+ "author": "Andrey Gubanov",
20
20
  "license": "MIT",
21
21
  "bugs": {
22
22
  "url": "https://github.com/finom/vovk/issues"
package/README.md CHANGED
@@ -4,109 +4,21 @@
4
4
  <source width="300" media="(prefers-color-scheme: light)" srcset="https://vovk.dev/vovk-logo.svg">
5
5
  <img width="300" alt="vovk" src="https://vovk.dev/vovk-logo.svg">
6
6
  </picture><br>
7
- <strong>RESTful RPC for Next.js</strong>
8
-
7
+ <strong>RESTful + RPC = ♥️</strong>
9
8
  </p>
10
9
 
11
10
  <p align="center">
12
- Transforms <a href="https://nextjs.org/docs/app">Next.js</a> into a powerful REST API platform with RPC capabilities.
13
- <br><br>
14
- ℹ️ Improved syntax for Zod and DTO validation is coming soon. Stay tuned!
11
+ Back-end meta-framework for <a href="https://nextjs.org/docs/app">Next.js</a>
15
12
  </p>
16
13
 
17
- <p align="center">
18
- <a href="https://vovk.dev/">Documentation</a>&nbsp;&nbsp;&nbsp;&nbsp;
19
- <a href="https://discord.gg/qdT8WEHUuP">Discord</a>&nbsp;&nbsp;&nbsp;&nbsp;
20
- <a href="https://github.com/finom/vovk-examples">Code Examples</a>&nbsp;&nbsp;&nbsp;&nbsp;
21
- <a href="https://github.com/finom/vovk-zod">vovk-zod</a>&nbsp;&nbsp;&nbsp;&nbsp;
22
- <a href="https://github.com/finom/vovk-hello-world">vovk-hello-world</a>&nbsp;&nbsp;&nbsp;&nbsp;
23
- <a href="https://github.com/finom/vovk-react-native-example">vovk-react-native-example</a>
24
- </p>
25
- <p align="center">
26
- <a href="https://www.npmjs.com/package/vovk"><img src="https://badge.fury.io/js/vovk.svg" alt="npm version" /></a>&nbsp;
27
- <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg" alt="TypeScript" /></a>&nbsp;
28
- <a href="https://github.com/finom/vovk/actions/workflows/main.yml"><img src="https://github.com/finom/vovk/actions/workflows/main.yml/badge.svg" alt="Build status" /></a>
29
- </p>
14
+ ---
30
15
 
31
- <br />
16
+ ## vovk [![npm version](https://badge.fury.io/js/vovk.svg)](https://www.npmjs.com/package/vovk)
32
17
 
33
- Example back-end Controller Class:
18
+ The main library with [zero dependencies](https://bundlephobia.com/result?p=vovk) that's going to be used in production. It provides a wrapper for Next.js API routes, internal RPC API, utilities and types.
34
19
 
35
- ```ts
36
- // /src/modules/post/PostController.ts
37
- import { get, prefix, type VovkRequest } from 'vovk';
38
- import PostService from './PostService';
39
-
40
- @prefix('posts')
41
- export default class PostController {
42
- /**
43
- * Create a comment on a post
44
- * POST /api/posts/:postId/comments
45
- */
46
- @post(':postId/comments')
47
- static async createComment(
48
- // decorate NextRequest type with body and query types
49
- req: VovkRequest<{ content: string; userId: string }, { notificationType: 'push' | 'email' }>,
50
- { postId }: { postId: string } // params
51
- ) {
52
- // use standard Next.js API to get body and query
53
- const { content, userId } = await req.json();
54
- const notificationType = req.nextUrl.searchParams.get('notificationType');
55
-
56
- // perform the request to the database in a custom service
57
- return PostService.createComment({
58
- postId,
59
- content,
60
- userId,
61
- notificationType,
62
- });
63
- }
64
- }
20
+ ```sh
21
+ npm install vovk
65
22
  ```
66
23
 
67
- Example component that uses the auto-generated client library:
68
-
69
- ```tsx
70
- 'use client';
71
- import { useState } from 'react';
72
- import { PostController } from 'vovk-client';
73
- import type { VovkReturnType } from 'vovk';
74
-
75
- export default function Example() {
76
- const [response, setResponse] = useState<VovkReturnType<typeof PostController.createComment>>();
77
-
78
- return (
79
- <>
80
- <button
81
- onClick={async () =>
82
- setResponse(
83
- await PostController.createComment({
84
- body: {
85
- content: 'Hello, World!',
86
- userId: '1',
87
- },
88
- params: { postId: '69' },
89
- query: { notificationType: 'push' },
90
- })
91
- )
92
- }
93
- >
94
- Post a comment
95
- </button>
96
- <div>{JSON.stringify(response)}</div>
97
- </>
98
- );
99
- }
100
- ```
101
-
102
- Alternatively, the resource can be fetched wit the regular `fetch` function:
103
-
104
- ```ts
105
- fetch('/api/posts/69?notificationType=push', {
106
- method: 'POST',
107
- body: JSON.stringify({
108
- content: 'Hello, World!',
109
- userId: '1',
110
- }),
111
- });
112
- ```
24
+ For more information, please visit the [getting started guide](https://vovk.dev/getting-started) or check out the [Vovk.ts examples](https://vovk-examples.vercel.app/).
package/bin/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'child_process';
3
+
4
+ console.warn(`Vovk CLI requires vovk-cli package. Running "npx vovk-cli ${process.argv.slice(2).join(' ')}" instead.`);
5
+
6
+ spawn('npx', ['vovk-cli', ...process.argv.slice(2)], { stdio: 'inherit' }).on('exit', (code) => {
7
+ process.exit(code);
8
+ });
@@ -1,5 +1,5 @@
1
- import type { _HttpStatus as HttpStatus } from './types';
2
- export declare class _HttpException extends Error {
1
+ import type { HttpStatus } from './types';
2
+ export declare class HttpException extends Error {
3
3
  statusCode: HttpStatus;
4
4
  message: string;
5
5
  cause?: unknown;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._HttpException = void 0;
4
- class _HttpException extends Error {
3
+ exports.HttpException = void 0;
4
+ class HttpException extends Error {
5
5
  statusCode;
6
6
  message;
7
7
  cause;
@@ -12,4 +12,4 @@ class _HttpException extends Error {
12
12
  this.cause = cause;
13
13
  }
14
14
  }
15
- exports._HttpException = _HttpException;
15
+ exports.HttpException = HttpException;
@@ -0,0 +1,19 @@
1
+ import type { KnownAny, StreamAbortMessage } from './types.js';
2
+ import './utils/shim.js';
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,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JSONLinesResponse = void 0;
4
+ require("./utils/shim.js");
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
+ }
38
+ send = (data) => {
39
+ const { controller, encoder } = this;
40
+ if (this.isClosed)
41
+ return;
42
+ // Enqueue to the ReadableStream
43
+ controller?.enqueue(encoder?.encode(JSON.stringify(data) + '\n'));
44
+ // Handle async iterator consumers
45
+ if (this.iteratorResolvers.length > 0) {
46
+ // If there's a pending next() call, resolve it immediately
47
+ const resolve = this.iteratorResolvers.shift();
48
+ resolve({ value: data, done: false });
49
+ }
50
+ else {
51
+ // Otherwise, queue the value for later consumption
52
+ this.iteratorQueue.push(data);
53
+ }
54
+ };
55
+ close = () => {
56
+ const { controller } = this;
57
+ if (this.isClosed)
58
+ return;
59
+ this.isClosed = true;
60
+ controller?.close();
61
+ // Resolve all pending iterator next() calls with done: true
62
+ while (this.iteratorResolvers.length > 0) {
63
+ const resolve = this.iteratorResolvers.shift();
64
+ resolve({ done: true, value: undefined });
65
+ }
66
+ };
67
+ throw = (e) => {
68
+ this.send({ isError: true, reason: e instanceof Error ? e.message : e });
69
+ return this.close();
70
+ };
71
+ [Symbol.dispose] = () => this.close();
72
+ [Symbol.asyncDispose] = () => this.close();
73
+ [Symbol.asyncIterator] = () => {
74
+ return {
75
+ next: async () => {
76
+ // If we have queued values, return them immediately
77
+ if (this.iteratorQueue.length > 0) {
78
+ const value = this.iteratorQueue.shift();
79
+ return { value, done: false };
80
+ }
81
+ // If the stream is closed and no more values, we're done
82
+ if (this.isClosed) {
83
+ return { done: true, value: undefined };
84
+ }
85
+ // Otherwise, wait for the next value or close
86
+ return new Promise((resolve) => {
87
+ this.iteratorResolvers.push(resolve);
88
+ });
89
+ },
90
+ };
91
+ };
92
+ }
93
+ exports.JSONLinesResponse = JSONLinesResponse;
@@ -1,27 +1,28 @@
1
- import { _HttpMethod as HttpMethod, _HttpStatus as HttpStatus, type _RouteHandler as RouteHandler, type _VovkController as VovkController, type _DecoratorOptions as DecoratorOptions, type _VovkRequest as VovkRequest } from './types';
2
- export declare class _VovkApp {
1
+ import type { NextRequest } from 'next/server';
2
+ import { HttpMethod, HttpStatus, type RouteHandler, type VovkController, type DecoratorOptions } from './types';
3
+ export declare class VovkApp {
3
4
  #private;
4
5
  private static getHeadersFromOptions;
5
6
  routes: Record<HttpMethod, Map<VovkController, Record<string, RouteHandler>>>;
6
- GET: (req: VovkRequest, data: {
7
+ GET: (req: NextRequest, data: {
7
8
  params: Promise<Record<string, string[]>>;
8
9
  }) => Promise<Response>;
9
- POST: (req: VovkRequest, data: {
10
+ POST: (req: NextRequest, data: {
10
11
  params: Promise<Record<string, string[]>>;
11
12
  }) => Promise<Response>;
12
- PUT: (req: VovkRequest, data: {
13
+ PUT: (req: NextRequest, data: {
13
14
  params: Promise<Record<string, string[]>>;
14
15
  }) => Promise<Response>;
15
- PATCH: (req: VovkRequest, data: {
16
+ PATCH: (req: NextRequest, data: {
16
17
  params: Promise<Record<string, string[]>>;
17
18
  }) => Promise<Response>;
18
- DELETE: (req: VovkRequest, data: {
19
+ DELETE: (req: NextRequest, data: {
19
20
  params: Promise<Record<string, string[]>>;
20
21
  }) => Promise<Response>;
21
- HEAD: (req: VovkRequest, data: {
22
+ HEAD: (req: NextRequest, data: {
22
23
  params: Promise<Record<string, string[]>>;
23
24
  }) => Promise<Response>;
24
- OPTIONS: (req: VovkRequest, data: {
25
+ OPTIONS: (req: NextRequest, data: {
25
26
  params: Promise<Record<string, string[]>>;
26
27
  }) => Promise<Response>;
27
28
  respond: (status: HttpStatus, body: unknown, options?: DecoratorOptions) => Response;
package/cjs/VovkApp.js ADDED
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ var _a;
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.VovkApp = void 0;
8
+ const types_1 = require("./types");
9
+ const HttpException_1 = require("./HttpException");
10
+ const JSONLinesResponse_1 = require("./JSONLinesResponse");
11
+ const reqQuery_1 = __importDefault(require("./utils/reqQuery"));
12
+ const reqMeta_1 = __importDefault(require("./utils/reqMeta"));
13
+ const reqForm_1 = __importDefault(require("./utils/reqForm"));
14
+ const headers_1 = require("next/headers");
15
+ class VovkApp {
16
+ static getHeadersFromOptions(options) {
17
+ if (!options)
18
+ return {};
19
+ const corsHeaders = {
20
+ 'access-control-allow-origin': '*',
21
+ 'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
22
+ 'access-control-allow-headers': 'content-type, authorization',
23
+ };
24
+ const headers = {
25
+ ...(options.cors ? corsHeaders : {}),
26
+ ...(options.headers ?? {}),
27
+ };
28
+ return headers;
29
+ }
30
+ routes = {
31
+ GET: new Map(),
32
+ POST: new Map(),
33
+ PUT: new Map(),
34
+ PATCH: new Map(),
35
+ DELETE: new Map(),
36
+ HEAD: new Map(),
37
+ OPTIONS: new Map(),
38
+ };
39
+ GET = async (req, data) => this.#callMethod(types_1.HttpMethod.GET, req, await data.params);
40
+ POST = async (req, data) => this.#callMethod(types_1.HttpMethod.POST, req, await data.params);
41
+ PUT = async (req, data) => this.#callMethod(types_1.HttpMethod.PUT, req, await data.params);
42
+ PATCH = async (req, data) => this.#callMethod(types_1.HttpMethod.PATCH, req, await data.params);
43
+ DELETE = async (req, data) => this.#callMethod(types_1.HttpMethod.DELETE, req, await data.params);
44
+ HEAD = async (req, data) => this.#callMethod(types_1.HttpMethod.HEAD, req, await data.params);
45
+ OPTIONS = async (req, data) => this.#callMethod(types_1.HttpMethod.OPTIONS, req, await data.params);
46
+ respond = (status, body, options) => {
47
+ return new Response(JSON.stringify(body), {
48
+ status,
49
+ headers: {
50
+ 'content-type': 'application/json',
51
+ ..._a.getHeadersFromOptions(options),
52
+ },
53
+ });
54
+ };
55
+ #respondWithError = (statusCode, message, options, cause) => {
56
+ return this.respond(statusCode, {
57
+ cause,
58
+ statusCode,
59
+ message,
60
+ isError: true,
61
+ }, options);
62
+ };
63
+ #getHandler = ({ handlers, path, params, }) => {
64
+ let methodParams = {};
65
+ if (Object.keys(params).length === 0) {
66
+ return { handler: handlers[''], methodParams };
67
+ }
68
+ const allMethodKeys = Object.keys(handlers);
69
+ let methodKeys = [];
70
+ const pathStr = path.join('/');
71
+ methodKeys = allMethodKeys
72
+ // First, try to match literal routes exactly.
73
+ .filter((p) => {
74
+ if (p.includes('{'))
75
+ return false; // Skip parameterized paths
76
+ return p === pathStr;
77
+ });
78
+ if (!methodKeys.length) {
79
+ methodKeys = allMethodKeys.filter((p) => {
80
+ const routeSegments = p.split('/');
81
+ if (routeSegments.length !== path.length)
82
+ return false;
83
+ const params = {};
84
+ for (let i = 0; i < routeSegments.length; i++) {
85
+ const routeSegment = routeSegments[i];
86
+ const pathSegment = path[i];
87
+ if (routeSegment.includes('{')) {
88
+ // const parameter = routeSegment.slice(1);
89
+ const regexPattern = routeSegment
90
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // Escape special chars
91
+ .replace(/\\{(\w+)\\}/g, '(?<$1>[^/]+)'); // Replace {var} with named groups
92
+ const values = pathSegment.match(new RegExp(`^${regexPattern}$`))?.groups ?? {};
93
+ for (const parameter in values) {
94
+ if (!Object.prototype.hasOwnProperty.call(values, parameter))
95
+ continue;
96
+ if (parameter in params) {
97
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, `Duplicate parameter "${parameter}" at ${p}`);
98
+ }
99
+ // If it's a parameterized segment, capture the parameter value.
100
+ params[parameter] = values[parameter];
101
+ }
102
+ }
103
+ else if (routeSegment !== pathSegment) {
104
+ // If it's a literal segment and it does not match the corresponding path segment, return false.
105
+ return false;
106
+ }
107
+ }
108
+ methodParams = params;
109
+ return true;
110
+ });
111
+ }
112
+ if (methodKeys.length > 1) {
113
+ throw new HttpException_1.HttpException(types_1.HttpStatus.INTERNAL_SERVER_ERROR, `Conflicting routes found: ${methodKeys.join(', ')}`);
114
+ }
115
+ const [methodKey] = methodKeys;
116
+ if (methodKey) {
117
+ return { handler: handlers[methodKey], methodParams };
118
+ }
119
+ return { handler: null, methodParams };
120
+ };
121
+ #callMethod = async (httpMethod, nextReq, params) => {
122
+ const req = nextReq;
123
+ const controllers = this.routes[httpMethod];
124
+ const path = params[Object.keys(params)[0]];
125
+ const handlers = {};
126
+ const headersList = await (0, headers_1.headers)();
127
+ const xMeta = headersList.get('x-meta');
128
+ const meta = xMeta && JSON.parse(xMeta);
129
+ if (meta)
130
+ (0, reqMeta_1.default)(req, { clientMetaHeader: meta });
131
+ controllers.forEach((staticMethods, controller) => {
132
+ const prefix = controller._prefix ?? '';
133
+ Object.entries(staticMethods ?? {}).forEach(([path, staticMethod]) => {
134
+ const fullPath = [prefix, path].filter(Boolean).join('/');
135
+ handlers[fullPath] = { staticMethod, controller };
136
+ });
137
+ });
138
+ const { handler, methodParams } = this.#getHandler({ handlers, path, params });
139
+ if (!handler) {
140
+ return this.#respondWithError(types_1.HttpStatus.NOT_FOUND, `${Object.keys(handlers)} - Route ${path.join('/')} is not found`);
141
+ }
142
+ const { staticMethod, controller } = handler;
143
+ req.vovk = {
144
+ body: () => req.json(),
145
+ query: () => (0, reqQuery_1.default)(req),
146
+ meta: (meta) => (0, reqMeta_1.default)(req, meta),
147
+ form: () => (0, reqForm_1.default)(req),
148
+ params: () => methodParams,
149
+ };
150
+ try {
151
+ await staticMethod._options?.before?.call(controller, req);
152
+ const result = await staticMethod.call(controller, req, methodParams);
153
+ if (result instanceof Response) {
154
+ return result;
155
+ }
156
+ const isIterator = typeof result === 'object' &&
157
+ !!result &&
158
+ !(result instanceof Array) &&
159
+ ((Reflect.has(result, Symbol.iterator) &&
160
+ typeof result[Symbol.iterator] === 'function') ||
161
+ (Reflect.has(result, Symbol.asyncIterator) &&
162
+ typeof result[Symbol.asyncIterator] === 'function'));
163
+ if (isIterator) {
164
+ const streamResponse = new JSONLinesResponse_1.JSONLinesResponse(req, {
165
+ headers: {
166
+ ..._a.getHeadersFromOptions(staticMethod._options),
167
+ },
168
+ });
169
+ void (async () => {
170
+ try {
171
+ for await (const chunk of result) {
172
+ streamResponse.send(chunk);
173
+ }
174
+ }
175
+ catch (e) {
176
+ return streamResponse.throw(e);
177
+ }
178
+ return streamResponse.close();
179
+ })();
180
+ return streamResponse;
181
+ }
182
+ return this.respond(200, result ?? null, staticMethod._options);
183
+ }
184
+ catch (e) {
185
+ const err = e;
186
+ try {
187
+ await controller._onError?.(err, req);
188
+ }
189
+ catch (onErrorError) {
190
+ // eslint-disable-next-line no-console
191
+ console.error(onErrorError);
192
+ }
193
+ if (err.message !== 'NEXT_REDIRECT' && err.message !== 'NEXT_NOT_FOUND') {
194
+ const statusCode = err.statusCode || types_1.HttpStatus.INTERNAL_SERVER_ERROR;
195
+ return this.#respondWithError(statusCode, err.message, staticMethod._options, err.cause);
196
+ }
197
+ throw e; // if NEXT_REDIRECT or NEXT_NOT_FOUND, rethrow it
198
+ }
199
+ };
200
+ }
201
+ exports.VovkApp = VovkApp;
202
+ _a = VovkApp;
@@ -0,0 +1,3 @@
1
+ import type { KnownAny, VovkSchema } from '../types';
2
+ import type { VovkClient, VovkClientFetcher, VovkDefaultFetcherOptions } from './types';
3
+ export declare const createRPC: <T, OPTS extends Record<string, KnownAny> = Record<string, never>>(schema: VovkSchema, segmentName: string, rpcModuleName: string, fetcher?: VovkClientFetcher<OPTS>, options?: VovkDefaultFetcherOptions<OPTS>) => VovkClient<T, OPTS>;
@@ -0,0 +1,90 @@
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.createRPC = void 0;
7
+ const fetcher_1 = require("./fetcher");
8
+ const defaultHandler_1 = require("./defaultHandler");
9
+ const defaultStreamHandler_1 = require("./defaultStreamHandler");
10
+ const serializeQuery_1 = __importDefault(require("../utils/serializeQuery"));
11
+ const trimPath = (path) => path.trim().replace(/^\/|\/$/g, '');
12
+ const getHandlerPath = (endpoint, params, query) => {
13
+ let result = endpoint;
14
+ const queryStr = query ? (0, serializeQuery_1.default)(query) : null;
15
+ for (const [key, value] of Object.entries(params ?? {})) {
16
+ result = result.replace(`{${key}}`, value);
17
+ }
18
+ return `${result}${queryStr ? '?' : ''}${queryStr}`;
19
+ };
20
+ const createRPC = (schema, segmentName, rpcModuleName, fetcher = fetcher_1.fetcher, options) => {
21
+ const segmentNamePath = options?.segmentNameOverride ?? segmentName;
22
+ const segmentSchema = schema.segments[segmentName];
23
+ if (!segmentSchema)
24
+ throw new Error(`Unable to create RPC module. Segment schema is missing for segment "${segmentName}".`);
25
+ const controllerSchema = schema.segments[segmentName]?.controllers[rpcModuleName];
26
+ const client = {};
27
+ if (!controllerSchema) {
28
+ throw new Error(`Unable to create RPC module. Controller schema is missing for module "${rpcModuleName}" from segment "${segmentName}".`);
29
+ }
30
+ const controllerPrefix = trimPath(controllerSchema.prefix ?? '');
31
+ for (const [staticMethodName, handlerSchema] of Object.entries(controllerSchema.handlers ?? {})) {
32
+ const { path, httpMethod, validation } = handlerSchema;
33
+ const getEndpoint = ({ apiRoot, params, query, }) => {
34
+ const forceApiRoot = controllerSchema.forceApiRoot ?? segmentSchema.forceApiRoot;
35
+ apiRoot = apiRoot ?? forceApiRoot ?? options?.apiRoot ?? '/api';
36
+ const endpoint = [
37
+ apiRoot.startsWith('http://') || apiRoot.startsWith('https://') || apiRoot.startsWith('/') ? '' : '/',
38
+ apiRoot,
39
+ forceApiRoot ? '' : segmentNamePath,
40
+ getHandlerPath([controllerPrefix, path].filter(Boolean).join('/'), params, query),
41
+ ]
42
+ .filter(Boolean)
43
+ .join('/')
44
+ .replace(/([^:])\/+/g, '$1/'); // replace // by / but not for protocols (http://, https://)
45
+ return endpoint;
46
+ };
47
+ const handler = async (input = {}) => {
48
+ const validate = async ({ body, query, params, endpoint, }) => {
49
+ const validateOnClient = input.validateOnClient ?? options?.validateOnClient;
50
+ if (validateOnClient && validation) {
51
+ if (typeof validateOnClient !== 'function') {
52
+ throw new Error('validateOnClient must be a function');
53
+ }
54
+ await validateOnClient({ body, query, params, endpoint }, validation, schema);
55
+ }
56
+ };
57
+ const internalOptions = {
58
+ name: staticMethodName,
59
+ httpMethod: httpMethod,
60
+ getEndpoint,
61
+ validate,
62
+ defaultHandler: defaultHandler_1.defaultHandler,
63
+ defaultStreamHandler: defaultStreamHandler_1.defaultStreamHandler,
64
+ schema: handlerSchema,
65
+ };
66
+ const internalInput = {
67
+ ...options,
68
+ ...input,
69
+ body: input.body ?? null,
70
+ query: input.query ?? {},
71
+ params: input.params ?? {},
72
+ meta: input.meta,
73
+ };
74
+ if (!fetcher)
75
+ throw new Error('Fetcher is not provided');
76
+ const [respData, resp] = await fetcher(internalOptions, internalInput);
77
+ return input.transform ? input.transform(respData, resp) : respData;
78
+ };
79
+ handler.schema = handlerSchema;
80
+ handler.controllerSchema = controllerSchema;
81
+ handler.segmentSchema = segmentSchema;
82
+ handler.fullSchema = schema;
83
+ handler.isRPC = true;
84
+ handler.path = [segmentNamePath, controllerPrefix, path].filter(Boolean).join('/');
85
+ // @ts-expect-error TODO
86
+ client[staticMethodName] = handler;
87
+ }
88
+ return client;
89
+ };
90
+ exports.createRPC = createRPC;
@@ -0,0 +1,6 @@
1
+ import { VovkHandlerSchema } from '../types';
2
+ export declare const DEFAULT_ERROR_MESSAGE = "Unknown error at defaultHandler";
3
+ export declare const defaultHandler: ({ response, schema }: {
4
+ response: Response;
5
+ schema: VovkHandlerSchema;
6
+ }) => Promise<unknown>;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultHandler = exports.DEFAULT_ERROR_MESSAGE = void 0;
4
+ const HttpException_1 = require("../HttpException");
5
+ exports.DEFAULT_ERROR_MESSAGE = 'Unknown error at defaultHandler';
6
+ // Helper function to get a value from an object using dot notation path
7
+ const getNestedValue = (obj, path) => {
8
+ return path.split('.').reduce((o, key) => (o && typeof o === 'object' ? o[key] : undefined), obj);
9
+ };
10
+ const defaultHandler = async ({ response, schema }) => {
11
+ let result;
12
+ try {
13
+ result = await response.json();
14
+ }
15
+ catch (e) {
16
+ // handle parsing errors
17
+ throw new HttpException_1.HttpException(response.status, e?.message ?? exports.DEFAULT_ERROR_MESSAGE);
18
+ }
19
+ if (!response.ok) {
20
+ const errorKey = schema.openapi && 'x-errorMessageKey' in schema.openapi
21
+ ? schema.openapi['x-errorMessageKey']
22
+ : 'message';
23
+ // handle server errors
24
+ const errorResponse = result;
25
+ throw new HttpException_1.HttpException(response.status, getNestedValue(errorResponse, errorKey) ?? exports.DEFAULT_ERROR_MESSAGE, errorResponse?.cause ?? JSON.stringify(result));
26
+ }
27
+ return result;
28
+ };
29
+ exports.defaultHandler = defaultHandler;
@@ -0,0 +1,9 @@
1
+ import { VovkHandlerSchema } from '../types';
2
+ import type { VovkStreamAsyncIterable } from './types';
3
+ import '../utils/shim';
4
+ export declare const DEFAULT_ERROR_MESSAGE = "Unknown error at defaultStreamHandler";
5
+ export declare const defaultStreamHandler: ({ response, controller, }: {
6
+ response: Response;
7
+ controller: AbortController;
8
+ schema: VovkHandlerSchema;
9
+ }) => Promise<VovkStreamAsyncIterable<unknown>>;