vovk 3.0.0-draft.7 → 3.0.0-draft.70

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 (101) hide show
  1. package/README.md +8 -95
  2. package/{HttpException.d.ts → dist/HttpException.d.ts} +2 -2
  3. package/{HttpException.js → dist/HttpException.js} +3 -3
  4. package/{StreamResponse.d.ts → dist/StreamJSONResponse.d.ts} +3 -3
  5. package/{StreamResponse.js → dist/StreamJSONResponse.js} +5 -5
  6. package/{Segment.d.ts → dist/VovkApp.d.ts} +11 -10
  7. package/{Segment.js → dist/VovkApp.js} +28 -24
  8. package/dist/client/createRPC.d.ts +4 -0
  9. package/{client/clientizeController.js → dist/client/createRPC.js} +22 -40
  10. package/dist/client/defaultFetcher.d.ts +4 -0
  11. package/{client → dist/client}/defaultFetcher.js +19 -8
  12. package/{client → dist/client}/defaultHandler.d.ts +1 -1
  13. package/dist/client/defaultHandler.js +22 -0
  14. package/dist/client/defaultStreamHandler.d.ts +4 -0
  15. package/{client → dist/client}/defaultStreamHandler.js +5 -5
  16. package/dist/client/index.d.ts +2 -0
  17. package/dist/client/index.js +8 -0
  18. package/dist/client/types.d.ts +103 -0
  19. package/dist/createDecorator.d.ts +4 -0
  20. package/{createDecorator.js → dist/createDecorator.js} +5 -4
  21. package/{createSegment.d.ts → dist/createVovkApp.d.ts} +10 -10
  22. package/{createSegment.js → dist/createVovkApp.js} +25 -25
  23. package/dist/index.d.ts +60 -0
  24. package/dist/index.js +24 -0
  25. package/dist/openapi/fromSchema.d.ts +3 -0
  26. package/dist/openapi/fromSchema.js +26 -0
  27. package/dist/openapi/index.d.ts +1 -0
  28. package/dist/openapi/index.js +5 -0
  29. package/dist/openapi/openapi.d.ts +10 -0
  30. package/dist/openapi/openapi.js +16 -0
  31. package/dist/types.d.ts +147 -0
  32. package/dist/types.js +65 -0
  33. package/dist/utils/generateStaticAPI.d.ts +4 -0
  34. package/{generateStaticAPI.js → dist/utils/generateStaticAPI.js} +3 -3
  35. package/{utils → dist/utils}/getSchema.d.ts +1 -2
  36. package/{utils → dist/utils}/getSchema.js +5 -16
  37. package/dist/utils/parseQuery.d.ts +25 -0
  38. package/dist/utils/parseQuery.js +156 -0
  39. package/dist/utils/reqForm.d.ts +2 -0
  40. package/dist/utils/reqForm.js +13 -0
  41. package/{utils → dist/utils}/reqMeta.d.ts +1 -2
  42. package/{utils → dist/utils}/reqQuery.d.ts +1 -2
  43. package/dist/utils/reqQuery.js +10 -0
  44. package/dist/utils/serializeQuery.d.ts +13 -0
  45. package/dist/utils/serializeQuery.js +65 -0
  46. package/dist/utils/setClientValidatorsForHandler.d.ts +5 -0
  47. package/{utils → dist/utils}/setClientValidatorsForHandler.js +4 -6
  48. package/package.json +8 -2
  49. package/src/HttpException.ts +16 -0
  50. package/src/StreamJSONResponse.ts +61 -0
  51. package/src/VovkApp.ts +240 -0
  52. package/src/client/createRPC.ts +120 -0
  53. package/src/client/defaultFetcher.ts +69 -0
  54. package/src/client/defaultHandler.ts +23 -0
  55. package/src/client/defaultStreamHandler.ts +88 -0
  56. package/src/client/index.ts +9 -0
  57. package/src/client/types.ts +120 -0
  58. package/src/createDecorator.ts +61 -0
  59. package/src/createVovkApp.ts +168 -0
  60. package/src/index.ts +71 -0
  61. package/src/openapi/fromSchema.ts +33 -0
  62. package/src/openapi/index.ts +1 -0
  63. package/src/openapi/openapi.ts +23 -0
  64. package/src/types.ts +200 -0
  65. package/src/utils/generateStaticAPI.ts +18 -0
  66. package/src/utils/getSchema.ts +35 -0
  67. package/src/utils/parseQuery.ts +160 -0
  68. package/src/utils/reqForm.ts +16 -0
  69. package/src/utils/reqMeta.ts +16 -0
  70. package/src/utils/reqQuery.ts +6 -0
  71. package/src/utils/serializeQuery.ts +69 -0
  72. package/src/utils/setClientValidatorsForHandler.ts +45 -0
  73. package/src/utils/shim.ts +17 -0
  74. package/.npmignore +0 -2
  75. package/client/clientizeController.d.ts +0 -4
  76. package/client/defaultFetcher.d.ts +0 -4
  77. package/client/defaultHandler.js +0 -21
  78. package/client/defaultStreamHandler.d.ts +0 -4
  79. package/client/index.d.ts +0 -4
  80. package/client/index.js +0 -5
  81. package/client/types.d.ts +0 -102
  82. package/createDecorator.d.ts +0 -4
  83. package/generateStaticAPI.d.ts +0 -4
  84. package/index.d.ts +0 -60
  85. package/index.js +0 -20
  86. package/types.d.ts +0 -191
  87. package/types.js +0 -65
  88. package/utils/reqQuery.js +0 -25
  89. package/utils/setClientValidatorsForHandler.d.ts +0 -5
  90. package/worker/index.d.ts +0 -3
  91. package/worker/index.js +0 -7
  92. package/worker/promisifyWorker.d.ts +0 -2
  93. package/worker/promisifyWorker.js +0 -143
  94. package/worker/types.d.ts +0 -31
  95. package/worker/types.js +0 -2
  96. package/worker/worker.d.ts +0 -1
  97. package/worker/worker.js +0 -44
  98. /package/{client → dist/client}/types.js +0 -0
  99. /package/{utils → dist/utils}/reqMeta.js +0 -0
  100. /package/{utils → dist/utils}/shim.d.ts +0 -0
  101. /package/{utils → dist/utils}/shim.js +0 -0
@@ -0,0 +1,4 @@
1
+ import type { StaticClass } from '../types';
2
+ export declare function generateStaticAPI(c: Record<string, StaticClass>, slug?: string): {
3
+ [x: string]: string[];
4
+ }[];
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports._generateStaticAPI = _generateStaticAPI;
4
- function _generateStaticAPI(c, slug = 'vovk') {
3
+ exports.generateStaticAPI = generateStaticAPI;
4
+ function generateStaticAPI(c, slug = 'vovk') {
5
5
  const controllers = c;
6
6
  return [
7
- { [slug]: ['_vovk-ping_'] },
7
+ { [slug]: ['_schema_'] },
8
8
  ...Object.values(controllers)
9
9
  .map((controller) => {
10
10
  const handlers = controller._handlers;
@@ -1,8 +1,7 @@
1
- import { _VovkSchema as VovkSchema, _StaticClass as StaticClass } from '../types';
1
+ import type { VovkSchema, StaticClass } from '../types';
2
2
  export default function getSchema(options: {
3
3
  emitSchema?: boolean;
4
4
  segmentName?: string;
5
5
  controllers: Record<string, StaticClass>;
6
- workers?: Record<string, StaticClass>;
7
6
  exposeValidation?: boolean;
8
7
  }): VovkSchema;
@@ -8,31 +8,20 @@ function getSchema(options) {
8
8
  emitSchema,
9
9
  segmentName: options.segmentName ?? '',
10
10
  controllers: {},
11
- workers: {},
12
11
  };
13
12
  if (!emitSchema)
14
13
  return schema;
15
14
  for (const [controllerName, controller] of Object.entries(options.controllers)) {
16
15
  schema.controllers[controllerName] = {
17
- _controllerName: controllerName,
18
- _originalControllerName: controller.name,
19
- _prefix: controller._prefix ?? '',
20
- _handlers: {
16
+ controllerName: controllerName,
17
+ originalControllerName: controller.name,
18
+ prefix: controller._prefix ?? '',
19
+ handlers: {
21
20
  ...(exposeValidation
22
21
  ? controller._handlers
23
- : Object.fromEntries(Object.entries(controller._handlers).map(([key, value]) => [
24
- key,
25
- { ...value, clientValidators: undefined },
26
- ]))),
22
+ : Object.fromEntries(Object.entries(controller._handlers ?? {}).map(([key, value]) => [key, { ...value, validation: {} }]))),
27
23
  },
28
24
  };
29
25
  }
30
- for (const [workerName, worker] of Object.entries(options.workers ?? {})) {
31
- schema.workers[workerName] = {
32
- _workerName: workerName,
33
- _originalWorkerName: worker.name,
34
- _handlers: { ...worker._handlers },
35
- };
36
- }
37
26
  return schema;
38
27
  }
@@ -0,0 +1,25 @@
1
+ import type { KnownAny } from '../types';
2
+ /**
3
+ * Deserialize a bracket-based query string into an object.
4
+ *
5
+ * Supports:
6
+ * - Key/value pairs with nested brackets (e.g. "a[b][0]=value")
7
+ * - Arrays with empty bracket (e.g. "arr[]=1&arr[]=2")
8
+ * - Mixed arrays of objects, etc.
9
+ *
10
+ * @example
11
+ * parseQuery("x=xx&y[0]=yy&y[1]=uu&z[f]=x&z[u][0]=uu&z[u][1]=xx&z[d][x]=ee")
12
+ * => {
13
+ * x: "xx",
14
+ * y: ["yy", "uu"],
15
+ * z: {
16
+ * f: "x",
17
+ * u: ["uu", "xx"],
18
+ * d: { x: "ee" }
19
+ * }
20
+ * }
21
+ *
22
+ * @param queryString - The raw query string (e.g. location.search.slice(1))
23
+ * @returns - A nested object representing the query params
24
+ */
25
+ export default function parseQuery(queryString: string): Record<string, KnownAny>;
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = parseQuery;
4
+ /**
5
+ * Parse a bracket-based key (e.g. "z[d][0][x]" or "arr[]")
6
+ * into an array of path segments (strings or special push-markers).
7
+ *
8
+ * Example: "z[d][0][x]" => ["z", "d", "0", "x"]
9
+ * Example: "arr[]" => ["arr", "" ] // "" indicates "push" onto array
10
+ */
11
+ function parseKey(key) {
12
+ // The first segment is everything up to the first '[' (or the entire key if no '[')
13
+ const segments = [];
14
+ const topKeyMatch = key.match(/^([^[\]]+)/);
15
+ if (topKeyMatch) {
16
+ segments.push(topKeyMatch[1]);
17
+ }
18
+ else {
19
+ // If it starts with brackets, treat it as empty? (edge case)
20
+ segments.push('');
21
+ }
22
+ // Now capture all bracket parts: [something], [0], []
23
+ const bracketRegex = /\[([^[\]]*)\]/g;
24
+ let match;
25
+ while ((match = bracketRegex.exec(key)) !== null) {
26
+ // match[1] is the content inside the brackets
27
+ segments.push(match[1]);
28
+ }
29
+ return segments;
30
+ }
31
+ /**
32
+ * Recursively set a value in a nested object/array, given a path of segments.
33
+ * - If segment is numeric => treat as array index
34
+ * - If segment is empty "" => push to array
35
+ * - Else => object property
36
+ */
37
+ function setValue(obj, path, value) {
38
+ let current = obj;
39
+ for (let i = 0; i < path.length; i++) {
40
+ const segment = path[i];
41
+ // If we're at the last segment, set the value
42
+ if (i === path.length - 1) {
43
+ if (segment === '') {
44
+ // Empty bracket => push
45
+ if (!Array.isArray(current)) {
46
+ current = [];
47
+ }
48
+ current.push(value);
49
+ }
50
+ else if (!isNaN(Number(segment))) {
51
+ // Numeric segment => array index
52
+ const idx = Number(segment);
53
+ if (!Array.isArray(current)) {
54
+ current = [];
55
+ }
56
+ current[idx] = value;
57
+ }
58
+ else {
59
+ // Object property
60
+ current[segment] = value;
61
+ }
62
+ }
63
+ else {
64
+ // Not the last segment: descend into existing structure or create it
65
+ const nextSegment = path[i + 1];
66
+ if (segment === '') {
67
+ // Empty bracket => push
68
+ if (!Array.isArray(current)) {
69
+ // Convert the current node into an array, if not one
70
+ current = [];
71
+ }
72
+ // If we are not at the last path, we need a placeholder object or array
73
+ // for the next segment. We'll push something and move current to that.
74
+ if (current.length === 0) {
75
+ // nothing in array yet
76
+ current.push(typeof nextSegment === 'string' && !isNaN(Number(nextSegment)) ? [] : {});
77
+ }
78
+ else if (typeof nextSegment === 'string' && !isNaN(Number(nextSegment))) {
79
+ // next is numeric => we want an array
80
+ if (!Array.isArray(current[current.length - 1])) {
81
+ current[current.length - 1] = [];
82
+ }
83
+ }
84
+ else {
85
+ // next is not numeric => we want an object
86
+ if (typeof current[current.length - 1] !== 'object') {
87
+ current[current.length - 1] = {};
88
+ }
89
+ }
90
+ current = current[current.length - 1];
91
+ }
92
+ else if (!isNaN(Number(segment))) {
93
+ // segment is numeric => array index
94
+ const idx = Number(segment);
95
+ if (!Array.isArray(current)) {
96
+ current = [];
97
+ }
98
+ if (current[idx] === undefined) {
99
+ // Create placeholder for next segment
100
+ current[idx] = typeof nextSegment === 'string' && !isNaN(Number(nextSegment)) ? [] : {};
101
+ }
102
+ current = current[idx];
103
+ }
104
+ else {
105
+ // segment is an object key
106
+ if (current[segment] === undefined) {
107
+ // Create placeholder
108
+ current[segment] = typeof nextSegment === 'string' && !isNaN(Number(nextSegment)) ? [] : {};
109
+ }
110
+ current = current[segment];
111
+ }
112
+ }
113
+ }
114
+ }
115
+ /**
116
+ * Deserialize a bracket-based query string into an object.
117
+ *
118
+ * Supports:
119
+ * - Key/value pairs with nested brackets (e.g. "a[b][0]=value")
120
+ * - Arrays with empty bracket (e.g. "arr[]=1&arr[]=2")
121
+ * - Mixed arrays of objects, etc.
122
+ *
123
+ * @example
124
+ * parseQuery("x=xx&y[0]=yy&y[1]=uu&z[f]=x&z[u][0]=uu&z[u][1]=xx&z[d][x]=ee")
125
+ * => {
126
+ * x: "xx",
127
+ * y: ["yy", "uu"],
128
+ * z: {
129
+ * f: "x",
130
+ * u: ["uu", "xx"],
131
+ * d: { x: "ee" }
132
+ * }
133
+ * }
134
+ *
135
+ * @param queryString - The raw query string (e.g. location.search.slice(1))
136
+ * @returns - A nested object representing the query params
137
+ */
138
+ function parseQuery(queryString) {
139
+ const result = {};
140
+ if (!queryString)
141
+ return result;
142
+ // Split into key=value pairs
143
+ const pairs = queryString
144
+ .replace(/^\?/, '') // Remove leading "?" if present
145
+ .split('&');
146
+ for (const pair of pairs) {
147
+ const [rawKey, rawVal = ''] = pair.split('=');
148
+ const decodedKey = decodeURIComponent(rawKey || '');
149
+ const decodedVal = decodeURIComponent(rawVal);
150
+ // Parse bracket notation
151
+ const pathSegments = parseKey(decodedKey);
152
+ // Insert into the result object
153
+ setValue(result, pathSegments, decodedVal);
154
+ }
155
+ return result;
156
+ }
@@ -0,0 +1,2 @@
1
+ import type { KnownAny, VovkRequest } from '../types';
2
+ export default function reqForm<T = KnownAny>(req: VovkRequest<KnownAny, KnownAny>): Promise<T>;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = reqForm;
4
+ const formMap = new WeakMap();
5
+ async function reqForm(req) {
6
+ if (formMap.has(req)) {
7
+ return formMap.get(req);
8
+ }
9
+ const body = await req.formData();
10
+ const formData = Object.fromEntries(body.entries());
11
+ formMap.set(req, formData);
12
+ return formData;
13
+ }
@@ -1,3 +1,2 @@
1
- import { VovkRequest } from 'vovk';
2
- import { _KnownAny as KnownAny } from '../types';
1
+ import type { KnownAny, VovkRequest } from '../types';
3
2
  export default function reqMeta<T = Record<KnownAny, KnownAny>>(req: VovkRequest<KnownAny, KnownAny>, meta?: T | null): T;
@@ -1,3 +1,2 @@
1
- import { _KnownAny as KnownAny } from '../types';
2
- import { VovkRequest } from 'vovk';
1
+ import type { KnownAny, VovkRequest } from '../types';
3
2
  export default function reqQuery<T extends object | undefined>(req: VovkRequest<KnownAny, T>): T;
@@ -0,0 +1,10 @@
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.default = reqQuery;
7
+ const parseQuery_1 = __importDefault(require("./parseQuery"));
8
+ function reqQuery(req) {
9
+ return (0, parseQuery_1.default)(req.nextUrl.search);
10
+ }
@@ -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,5 @@
1
+ import type { KnownAny } from '../types';
2
+ export declare function setClientValidatorsForHandler(h: (...args: KnownAny[]) => KnownAny, validation: {
3
+ body: unknown;
4
+ query: unknown;
5
+ }): Promise<void>;
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = setClientValidatorsForHandler;
4
- function setClientValidatorsForHandler(h, validators) {
3
+ exports.setClientValidatorsForHandler = setClientValidatorsForHandler;
4
+ function setClientValidatorsForHandler(h, validation) {
5
5
  return new Promise((resolve) => {
6
+ // the setTimeout is necessary to ensure that the _controller is already defined
6
7
  setTimeout(() => {
7
8
  const controller = h._controller;
8
9
  if (!controller) {
@@ -16,10 +17,7 @@ function setClientValidatorsForHandler(h, validators) {
16
17
  ...controller._handlers,
17
18
  [handlerName]: {
18
19
  ...controller._handlers[handlerName],
19
- clientValidators: {
20
- body: validators.body,
21
- query: validators.query,
22
- },
20
+ validation,
23
21
  },
24
22
  };
25
23
  resolve();
package/package.json CHANGED
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "name": "vovk",
3
- "version": "3.0.0-draft.7",
3
+ "version": "3.0.0-draft.70",
4
+ "main": "dist/index.js",
4
5
  "description": "RESTful RPC for Next.js - Transforms Next.js into a powerful REST API platform with RPC capabilities.",
5
6
  "repository": {
6
7
  "type": "git",
7
8
  "url": "git+https://github.com/finom/vovk.git"
8
9
  },
9
10
  "scripts": {
10
- "build": "rm -rf dist && tsc && cp {package.json,LICENSE,.npmignore} dist && cp ../../README.md dist",
11
+ "build": "tsc",
12
+ "rm-dist": "shx rm -rf dist",
11
13
  "lint": "eslint . --fix",
14
+ "tsc": "tsc --noEmit",
12
15
  "npm-publish": "if [ -z \"$NPM_TAG\" ]; then echo 'Error: NPM_TAG is not set'; exit 1; fi; cd ./dist && npm publish --tag=$NPM_TAG && cd ..",
13
16
  "ncu": "npm-check-updates -u"
14
17
  },
@@ -24,5 +27,8 @@
24
27
  "homepage": "https://vovk.dev",
25
28
  "peerDependencies": {
26
29
  "next": "*"
30
+ },
31
+ "optionalDependencies": {
32
+ "openapi3-ts": "^4.4.0"
27
33
  }
28
34
  }
@@ -0,0 +1,16 @@
1
+ import type { HttpStatus } from './types';
2
+
3
+ export class HttpException extends Error {
4
+ statusCode: HttpStatus;
5
+
6
+ message: string;
7
+
8
+ cause?: unknown;
9
+
10
+ constructor(statusCode: HttpStatus, message: string, cause?: unknown) {
11
+ super(message);
12
+ this.statusCode = statusCode;
13
+ this.message = message;
14
+ this.cause = cause;
15
+ }
16
+ }
@@ -0,0 +1,61 @@
1
+ import type { KnownAny, StreamAbortMessage } from './types';
2
+ import './utils/shim';
3
+
4
+ export class StreamJSONResponse<T> extends Response {
5
+ public static defaultHeaders = {
6
+ 'content-type': 'text/plain; format=jsonlines',
7
+ };
8
+
9
+ public isClosed = false;
10
+
11
+ public controller?: ReadableStreamDefaultController;
12
+
13
+ public readonly encoder: TextEncoder;
14
+
15
+ public readonly readableStream: ReadableStream;
16
+
17
+ constructor(init?: ResponseInit) {
18
+ const encoder = new TextEncoder();
19
+ let readableController: ReadableStreamDefaultController;
20
+
21
+ const readableStream = new ReadableStream({
22
+ cancel: () => {
23
+ this.isClosed = true;
24
+ },
25
+ start: (controller) => {
26
+ readableController = controller;
27
+ },
28
+ });
29
+
30
+ super(readableStream, {
31
+ ...init,
32
+ headers: init?.headers ?? StreamJSONResponse.defaultHeaders,
33
+ });
34
+
35
+ this.readableStream = readableStream;
36
+ this.encoder = encoder;
37
+ this.controller = readableController!;
38
+ }
39
+
40
+ public send(data: T | StreamAbortMessage) {
41
+ const { controller, encoder } = this;
42
+ if (this.isClosed) return;
43
+ return controller?.enqueue(encoder.encode(JSON.stringify(data) + '\n'));
44
+ }
45
+
46
+ public close() {
47
+ const { controller } = this;
48
+ if (this.isClosed) return;
49
+ this.isClosed = true;
50
+ controller?.close();
51
+ }
52
+
53
+ public throw(e: KnownAny) {
54
+ this.send({ isError: true, reason: e instanceof Error ? e.message : (e as unknown) });
55
+ return this.close();
56
+ }
57
+
58
+ public [Symbol.dispose]() {
59
+ this.close();
60
+ }
61
+ }