vovk 0.2.3-beta.12 → 0.2.3-beta.121
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.
- package/Segment.d.ts +1 -0
- package/Segment.js +29 -4
- package/StreamResponse.js +1 -2
- package/cli/.eslintrc.js +10 -2
- package/cli/generateClient.mjs +122 -0
- package/cli/getVars.mjs +45 -0
- package/cli/index.mjs +67 -0
- package/cli/lib/getAvailablePort.mjs +30 -0
- package/cli/lib/getReturnPath.mjs +26 -0
- package/cli/lib/isEqual.mjs +26 -0
- package/cli/lib/parallel.mjs +48 -0
- package/cli/lib/parseCommandLineArgs.mjs +39 -0
- package/cli/postinstall.mjs +29 -0
- package/cli/server.mjs +118 -0
- package/client/clientizeController.d.ts +19 -1
- package/client/clientizeController.js +7 -10
- package/client/defaultFetcher.d.ts +4 -2
- package/client/defaultFetcher.js +6 -12
- package/client/defaultHandler.d.ts +2 -0
- package/client/defaultHandler.js +21 -0
- package/client/defaultStreamHandler.d.ts +3 -0
- package/client/{defaultStreamFetcher.js → defaultStreamHandler.js} +30 -41
- package/client/types.d.ts +12 -2
- package/createSegment.d.ts +16 -20
- package/createSegment.js +28 -51
- package/index.d.ts +21 -23
- package/index.js +5 -2
- package/package.json +17 -17
- package/tsconfig.tsbuildinfo +1 -1
- package/types.d.ts +42 -1
- package/worker/promisifyWorker.d.ts +1 -1
- package/worker/promisifyWorker.js +24 -8
- package/worker/types.d.ts +8 -2
- package/cli/generateClient.js +0 -54
- package/cli/getVovkrc.js +0 -28
- package/cli/index.js +0 -77
- package/cli/server.js +0 -76
- package/cli/watchMetadata.js +0 -34
- package/client/defaultStreamFetcher.d.ts +0 -5
package/Segment.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { NextRequest } from 'next/server';
|
|
|
2
2
|
import { _HttpMethod as HttpMethod, type _RouteHandler as RouteHandler } from './types';
|
|
3
3
|
export declare class _Segment {
|
|
4
4
|
#private;
|
|
5
|
+
private static getHeadersFromOptions;
|
|
5
6
|
_routes: Record<HttpMethod, Map<{
|
|
6
7
|
name?: string;
|
|
7
8
|
_prefix?: string;
|
package/Segment.js
CHANGED
|
@@ -1,10 +1,23 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var _a;
|
|
2
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
4
|
exports._Segment = void 0;
|
|
4
5
|
const types_1 = require("./types");
|
|
5
6
|
const HttpException_1 = require("./HttpException");
|
|
6
7
|
const StreamResponse_1 = require("./StreamResponse");
|
|
7
8
|
class _Segment {
|
|
9
|
+
static getHeadersFromOptions(options) {
|
|
10
|
+
const corsHeaders = {
|
|
11
|
+
'Access-Control-Allow-Origin': '*',
|
|
12
|
+
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
|
|
13
|
+
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
14
|
+
};
|
|
15
|
+
const headers = {
|
|
16
|
+
...(options?.cors ? corsHeaders : {}),
|
|
17
|
+
...(options?.headers ?? {}),
|
|
18
|
+
};
|
|
19
|
+
return headers;
|
|
20
|
+
}
|
|
8
21
|
_routes = {
|
|
9
22
|
GET: new Map(),
|
|
10
23
|
POST: new Map(),
|
|
@@ -14,18 +27,21 @@ class _Segment {
|
|
|
14
27
|
HEAD: new Map(),
|
|
15
28
|
OPTIONS: new Map(),
|
|
16
29
|
};
|
|
17
|
-
GET = (req, data) =>
|
|
30
|
+
GET = (req, data) => {
|
|
31
|
+
return this.#callMethod(types_1._HttpMethod.GET, req, data.params);
|
|
32
|
+
};
|
|
18
33
|
POST = (req, data) => this.#callMethod(types_1._HttpMethod.POST, req, data.params);
|
|
19
34
|
PUT = (req, data) => this.#callMethod(types_1._HttpMethod.PUT, req, data.params);
|
|
20
35
|
PATCH = (req, data) => this.#callMethod(types_1._HttpMethod.PATCH, req, data.params);
|
|
21
36
|
DELETE = (req, data) => this.#callMethod(types_1._HttpMethod.DELETE, req, data.params);
|
|
22
37
|
HEAD = (req, data) => this.#callMethod(types_1._HttpMethod.HEAD, req, data.params);
|
|
23
38
|
OPTIONS = (req, data) => this.#callMethod(types_1._HttpMethod.OPTIONS, req, data.params);
|
|
24
|
-
#respond = (status, body) => {
|
|
39
|
+
#respond = (status, body, options) => {
|
|
25
40
|
return new Response(JSON.stringify(body), {
|
|
26
41
|
status,
|
|
27
42
|
headers: {
|
|
28
43
|
'Content-Type': 'application/json',
|
|
44
|
+
..._a.getHeadersFromOptions(options),
|
|
29
45
|
},
|
|
30
46
|
});
|
|
31
47
|
};
|
|
@@ -39,6 +55,9 @@ class _Segment {
|
|
|
39
55
|
#callMethod = async (httpMethod, req, params) => {
|
|
40
56
|
const controllers = this._routes[httpMethod];
|
|
41
57
|
const methodParams = {};
|
|
58
|
+
if (params[Object.keys(params)[0]]?.[0] === '__ping') {
|
|
59
|
+
return this.#respond(200, { message: 'pong' });
|
|
60
|
+
}
|
|
42
61
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
43
62
|
const handlers = Object.fromEntries([...controllers.entries()]
|
|
44
63
|
.map(([controller, staticMethods]) => {
|
|
@@ -113,7 +132,12 @@ class _Segment {
|
|
|
113
132
|
(Reflect.has(result, Symbol.asyncIterator) &&
|
|
114
133
|
typeof result[Symbol.asyncIterator] === 'function'));
|
|
115
134
|
if (isIterator && !(result instanceof Array)) {
|
|
116
|
-
const streamResponse = new StreamResponse_1._StreamResponse(
|
|
135
|
+
const streamResponse = new StreamResponse_1._StreamResponse({
|
|
136
|
+
headers: {
|
|
137
|
+
...StreamResponse_1._StreamResponse.defaultHeaders,
|
|
138
|
+
..._a.getHeadersFromOptions(staticMethod._options),
|
|
139
|
+
},
|
|
140
|
+
});
|
|
117
141
|
void (async () => {
|
|
118
142
|
try {
|
|
119
143
|
for await (const chunk of result) {
|
|
@@ -130,7 +154,7 @@ class _Segment {
|
|
|
130
154
|
if (result instanceof Response) {
|
|
131
155
|
return result;
|
|
132
156
|
}
|
|
133
|
-
return this.#respond(200, result ?? null);
|
|
157
|
+
return this.#respond(200, result ?? null, staticMethod._options);
|
|
134
158
|
}
|
|
135
159
|
catch (e) {
|
|
136
160
|
const err = e;
|
|
@@ -150,3 +174,4 @@ class _Segment {
|
|
|
150
174
|
};
|
|
151
175
|
}
|
|
152
176
|
exports._Segment = _Segment;
|
|
177
|
+
_a = _Segment;
|
package/StreamResponse.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports._StreamResponse = void 0;
|
|
4
4
|
class _StreamResponse extends Response {
|
|
5
|
-
static JSON_DIVIDER = '__##DIV123##__'; // protects collisions
|
|
5
|
+
static JSON_DIVIDER = '__##DIV123##__'; // protects collisions of JSON data
|
|
6
6
|
static defaultHeaders = {
|
|
7
7
|
'Content-Type': 'text/event-stream',
|
|
8
8
|
Connection: 'keep-alive',
|
|
@@ -32,7 +32,6 @@ class _StreamResponse extends Response {
|
|
|
32
32
|
}
|
|
33
33
|
async throw(e) {
|
|
34
34
|
const { writer } = this;
|
|
35
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
36
35
|
await this.send({ isError: true, reason: e instanceof Error ? e.message : e });
|
|
37
36
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
38
37
|
return writer.abort(e);
|
package/cli/.eslintrc.js
CHANGED
|
@@ -7,6 +7,14 @@ module.exports = {
|
|
|
7
7
|
'@typescript-eslint/no-unsafe-call': 'off',
|
|
8
8
|
'@typescript-eslint/no-unsafe-member-access': 'off',
|
|
9
9
|
'@typescript-eslint/no-unsafe-return': 'off',
|
|
10
|
-
'no-console': ['error', { allow: ['info', 'error'] }]
|
|
11
|
-
}
|
|
10
|
+
'no-console': ['error', { allow: ['info', 'error', 'warn'] }]
|
|
11
|
+
},
|
|
12
|
+
parserOptions: {
|
|
13
|
+
ecmaVersion: 2022,
|
|
14
|
+
sourceType: 'module',
|
|
15
|
+
project: '../tsconfig.cli.json',
|
|
16
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
17
|
+
tsconfigRootDir: __dirname,
|
|
18
|
+
createDefaultProgram: true,
|
|
19
|
+
},
|
|
12
20
|
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import fs from 'fs/promises';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import getReturnPath from './lib/getReturnPath.mjs';
|
|
5
|
+
|
|
6
|
+
/** @type {(moduleName: string) => Promise<boolean>} */
|
|
7
|
+
async function fileExists(filePath) {
|
|
8
|
+
try {
|
|
9
|
+
await fs.stat(filePath);
|
|
10
|
+
return true; // The file exists
|
|
11
|
+
} catch (e) {
|
|
12
|
+
return false; // The file does not exist
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Generates client code with string concatenation so it should be much faster than using AST
|
|
18
|
+
* TODO: Check fetcher for existence
|
|
19
|
+
* @type {(rcPath: import('../src').VovkEnv) => Promise<{ written: boolean; path: string }>}
|
|
20
|
+
*/
|
|
21
|
+
export default async function generateClient({ ...env }) {
|
|
22
|
+
const outDir = env.VOVK_CLIENT_OUT;
|
|
23
|
+
const returnDir = getReturnPath(outDir, process.cwd());
|
|
24
|
+
const jsonPath = path.join(returnDir, '.vovk.json');
|
|
25
|
+
const localJsonPath = path.join(process.cwd(), '.vovk.json');
|
|
26
|
+
const fetcherPath = env.VOVK_FETCHER.startsWith('.') ? path.join(returnDir, env.VOVK_FETCHER) : env.VOVK_FETCHER;
|
|
27
|
+
|
|
28
|
+
if (!env.VOVK_VALIDATE_ON_CLIENT) {
|
|
29
|
+
env.VOVK_VALIDATE_ON_CLIENT = (await fileExists('vovk-zod/zodValidateOnClient'))
|
|
30
|
+
? 'vovk-zod/zodValidateOnClient'
|
|
31
|
+
: '';
|
|
32
|
+
}
|
|
33
|
+
const validatePath = env.VOVK_VALIDATE_ON_CLIENT.startsWith('.')
|
|
34
|
+
? path.join(returnDir, env.VOVK_VALIDATE_ON_CLIENT)
|
|
35
|
+
: env.VOVK_VALIDATE_ON_CLIENT;
|
|
36
|
+
const localValidatePath = env.VOVK_VALIDATE_ON_CLIENT.startsWith('.') ? path.join('..', validatePath) : validatePath;
|
|
37
|
+
|
|
38
|
+
if (env.VOVK_VALIDATE_ON_CLIENT && !(await fileExists(localValidatePath))) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`Unble to generate Vovk Client: cannot find "validateOnClient" module '${env.VOVK_VALIDATE_ON_CLIENT}'. Check your vovk.config.js file`
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (!(await fileExists(localJsonPath))) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`Unble to generate Vovk Client: cannot find ".vovk.json" file '${localJsonPath}' (original value '${jsonPath}').`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const controllersPath = path.join(returnDir, env.VOVK_ROUTE).replace(/\.ts$/, '');
|
|
51
|
+
let dts = `// auto-generated
|
|
52
|
+
/* eslint-disable */
|
|
53
|
+
import type { Controllers, Workers } from "${controllersPath}";
|
|
54
|
+
import type { clientizeController } from 'vovk/client';
|
|
55
|
+
import type { promisifyWorker } from 'vovk/worker';
|
|
56
|
+
import type { VovkClientFetcher } from 'vovk/client';
|
|
57
|
+
import type fetcher from '${fetcherPath}';
|
|
58
|
+
|
|
59
|
+
type Options = typeof fetcher extends VovkClientFetcher<infer U> ? U : never;
|
|
60
|
+
`;
|
|
61
|
+
let js = `// auto-generated
|
|
62
|
+
/* eslint-disable */
|
|
63
|
+
const { clientizeController } = require('vovk/client');
|
|
64
|
+
const { promisifyWorker } = require('vovk/worker');
|
|
65
|
+
const metadata = require('${jsonPath}');
|
|
66
|
+
const { default: fetcher } = require('${fetcherPath}');
|
|
67
|
+
const prefix = '${env.VOVK_PREFIX ?? '/api'}';
|
|
68
|
+
const { default: validateOnClient = null } = ${validatePath ? `require('${validatePath}')` : '{}'};
|
|
69
|
+
|
|
70
|
+
`;
|
|
71
|
+
let ts = `// auto-generated
|
|
72
|
+
/* eslint-disable */
|
|
73
|
+
import type { Controllers, Workers } from "${controllersPath}";
|
|
74
|
+
import { clientizeController } from 'vovk/client';
|
|
75
|
+
import { promisifyWorker } from 'vovk/worker';
|
|
76
|
+
import type { VovkClientFetcher } from 'vovk/client';
|
|
77
|
+
import fetcher from '${fetcherPath}';
|
|
78
|
+
import metadata from '${jsonPath}';
|
|
79
|
+
${validatePath ? `import validateOnClient from '${validatePath}';\n` : '\nconst validateOnClient = undefined;'}
|
|
80
|
+
const prefix = '${env.VOVK_PREFIX ?? '/api'}';
|
|
81
|
+
type Options = typeof fetcher extends VovkClientFetcher<infer U> ? U : never;
|
|
82
|
+
`;
|
|
83
|
+
const metadataJson = await fs.readFile(localJsonPath, 'utf-8').catch(() => null);
|
|
84
|
+
|
|
85
|
+
if (!metadataJson) console.warn(` 🐺 No .vovk.json file found in ${localJsonPath}`);
|
|
86
|
+
|
|
87
|
+
const metadata = JSON.parse(metadataJson || '{}');
|
|
88
|
+
|
|
89
|
+
for (const key of Object.keys(metadata)) {
|
|
90
|
+
if (key !== 'workers') {
|
|
91
|
+
dts += `export const ${key}: ReturnType<typeof clientizeController<Controllers["${key}"], Options>>;\n`;
|
|
92
|
+
js += `exports.${key} = clientizeController(metadata.${key}, { fetcher, validateOnClient, defaultOptions: { prefix } });\n`;
|
|
93
|
+
ts += `export const ${key} = clientizeController<Controllers["${key}"], Options>(metadata.${key}, { fetcher, validateOnClient, defaultOptions: { prefix } });\n`;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
for (const key of Object.keys(metadata.workers ?? {})) {
|
|
98
|
+
dts += `export const ${key}: ReturnType<typeof promisifyWorker<Workers["${key}"]>>;\n`;
|
|
99
|
+
js += `exports.${key} = promisifyWorker(null, metadata.workers.${key});\n`;
|
|
100
|
+
ts += `export const ${key} = promisifyWorker<Workers["${key}"]>(null, metadata.workers.${key});\n`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/* js += `
|
|
104
|
+
if(typeof window !== 'undefined') fetch(prefix + '/__ping', { method: 'POST' });
|
|
105
|
+
`; */
|
|
106
|
+
|
|
107
|
+
const localJsPath = path.join(outDir, 'client.js');
|
|
108
|
+
const localDtsPath = path.join(outDir, 'client.d.ts');
|
|
109
|
+
const localTsPath = path.join(outDir, 'index.ts');
|
|
110
|
+
const existingJs = await fs.readFile(localJsPath, 'utf-8').catch(() => '');
|
|
111
|
+
const existingDts = await fs.readFile(localDtsPath, 'utf-8').catch(() => '');
|
|
112
|
+
const existingTs = await fs.readFile(localTsPath, 'utf-8').catch(() => '');
|
|
113
|
+
|
|
114
|
+
if (existingJs === js && existingDts === dts && existingTs === ts) return { written: false, path: outDir };
|
|
115
|
+
|
|
116
|
+
await fs.mkdir(outDir, { recursive: true });
|
|
117
|
+
await fs.writeFile(localJsPath, js);
|
|
118
|
+
await fs.writeFile(localDtsPath, dts);
|
|
119
|
+
await fs.writeFile(localTsPath, ts);
|
|
120
|
+
|
|
121
|
+
return { written: true, path: outDir };
|
|
122
|
+
}
|
package/cli/getVars.mjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import path from 'path';
|
|
4
|
+
|
|
5
|
+
/** @type {import('../src').VovkEnv} */
|
|
6
|
+
let vars;
|
|
7
|
+
/** @type {(rcPath: string, options?: { VOVK_CLIENT_OUT?: string; PORT?: string; }) => Promise<import('../src').VovkEnv>} */
|
|
8
|
+
export default async function getVars(configPath, options = {}) {
|
|
9
|
+
if (vars) return vars;
|
|
10
|
+
/** @type {Required<import('../src').VovkConfig>} */
|
|
11
|
+
const vovkConfig = {
|
|
12
|
+
out: './node_modules/.vovk',
|
|
13
|
+
route: './src/app/api/[[...vovk]]/route.ts',
|
|
14
|
+
fetcher: 'vovk/client/defaultFetcher',
|
|
15
|
+
prefix: '/api',
|
|
16
|
+
validateOnClient: '',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
// make PORT available to the config file
|
|
21
|
+
process.env.PORT = options.PORT || process.env.PORT || '3000';
|
|
22
|
+
Object.assign(vovkConfig, await import(configPath));
|
|
23
|
+
} catch {
|
|
24
|
+
// noop
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
vars = {
|
|
28
|
+
PORT: options.PORT || process.env.PORT || '3000',
|
|
29
|
+
VOVK_CLIENT_OUT:
|
|
30
|
+
process.env.VOVK_CLIENT_OUT ||
|
|
31
|
+
(options.VOVK_CLIENT_OUT?.startsWith('/')
|
|
32
|
+
? options.VOVK_CLIENT_OUT
|
|
33
|
+
: options.VOVK_CLIENT_OUT
|
|
34
|
+
? path.join(process.cwd(), options.VOVK_CLIENT_OUT)
|
|
35
|
+
: null) ||
|
|
36
|
+
vovkConfig.out,
|
|
37
|
+
VOVK_PORT: process.env.VOVK_PORT || '3690',
|
|
38
|
+
VOVK_ROUTE: process.env.VOVK_ROUTE || vovkConfig.route,
|
|
39
|
+
VOVK_FETCHER: process.env.VOVK_FETCHER || vovkConfig.fetcher,
|
|
40
|
+
VOVK_PREFIX: process.env.VOVK_PREFIX || vovkConfig.prefix,
|
|
41
|
+
VOVK_VALIDATE_ON_CLIENT: process.env.VOVK_VALIDATE_ON_CLIENT || vovkConfig.validateOnClient,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
return vars;
|
|
45
|
+
}
|
package/cli/index.mjs
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import generateClient from './generateClient.mjs';
|
|
5
|
+
import parallel from './lib/parallel.mjs';
|
|
6
|
+
import getAvailablePort from './lib/getAvailablePort.mjs';
|
|
7
|
+
import getVars from './getVars.mjs';
|
|
8
|
+
import parseCommandLineArgs from './lib/parseCommandLineArgs.mjs';
|
|
9
|
+
import { fileURLToPath } from 'url';
|
|
10
|
+
|
|
11
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
12
|
+
// @ts-ignore Ignore meta-property error
|
|
13
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
|
|
15
|
+
const { command, flags, restArgs } = parseCommandLineArgs();
|
|
16
|
+
const {
|
|
17
|
+
config = path.join(process.cwd(), 'vovk.config.js'), // Path to vovk.config.js
|
|
18
|
+
// TODO not documented
|
|
19
|
+
project = process.cwd(), // Path to Next.js project
|
|
20
|
+
clientOut = path.join(process.cwd(), './node_modules/.vovk'), // Path to output directory
|
|
21
|
+
} = flags;
|
|
22
|
+
|
|
23
|
+
if (command === 'dev') {
|
|
24
|
+
void (async () => {
|
|
25
|
+
let PORT =
|
|
26
|
+
process.env.PORT ||
|
|
27
|
+
(await getAvailablePort(3000, 30).catch(() => {
|
|
28
|
+
throw new Error(' 🐺 Failed to find available Next port');
|
|
29
|
+
}));
|
|
30
|
+
|
|
31
|
+
const env = await getVars(config, { VOVK_CLIENT_OUT: clientOut, PORT });
|
|
32
|
+
|
|
33
|
+
let VOVK_PORT = parseInt(env.VOVK_PORT);
|
|
34
|
+
|
|
35
|
+
env.VOVK_PORT = await getAvailablePort(VOVK_PORT, 30).catch(() => {
|
|
36
|
+
throw new Error(' 🐺 Failed to find available Vovk port');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
await parallel(
|
|
40
|
+
[
|
|
41
|
+
{
|
|
42
|
+
command: `node ${__dirname}/server.mjs`,
|
|
43
|
+
name: 'Vovk',
|
|
44
|
+
},
|
|
45
|
+
{ command: `cd ${project} && npx next dev ${restArgs}`, name: 'Next' },
|
|
46
|
+
],
|
|
47
|
+
env
|
|
48
|
+
).catch((e) => console.error(e));
|
|
49
|
+
console.info(' 🐺 All processes have ended');
|
|
50
|
+
})();
|
|
51
|
+
} else if (command === 'generate') {
|
|
52
|
+
void (async () => {
|
|
53
|
+
const env = await getVars(config, { VOVK_CLIENT_OUT: clientOut });
|
|
54
|
+
|
|
55
|
+
void generateClient(env).then(({ path }) => {
|
|
56
|
+
console.info(` 🐺 Client generated in ${path}`);
|
|
57
|
+
});
|
|
58
|
+
})();
|
|
59
|
+
} else if (command === 'help') {
|
|
60
|
+
console.info(` 🐺 Vovk CLI
|
|
61
|
+
dev - Start development server
|
|
62
|
+
generate - Generate client
|
|
63
|
+
help - Show this help message`);
|
|
64
|
+
} else {
|
|
65
|
+
console.error(' 🐺 ❌ Invalid command');
|
|
66
|
+
process.exit(1);
|
|
67
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import net from 'net';
|
|
2
|
+
|
|
3
|
+
function checkPort(port, callback) {
|
|
4
|
+
const server = net.createServer();
|
|
5
|
+
|
|
6
|
+
server.listen(port, () => {
|
|
7
|
+
server.close(() => {
|
|
8
|
+
callback(true); // Port is available
|
|
9
|
+
});
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
server.on('error', () => {
|
|
13
|
+
callback(false);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** @type {(startPort: number, maxAttempts: number, attempt?: number) => Promise<string>} */
|
|
18
|
+
export default function getAvailablePort(startPort, maxAttempts, attempt = 1) {
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
checkPort(startPort, (isAvailable) => {
|
|
21
|
+
if (isAvailable) {
|
|
22
|
+
resolve(startPort.toString()); // Found an available port
|
|
23
|
+
} else if (attempt < maxAttempts) {
|
|
24
|
+
getAvailablePort(startPort + 1, maxAttempts, attempt + 1).then(resolve, reject);
|
|
25
|
+
} else {
|
|
26
|
+
reject(null);
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/** @type {(fromPath: string, toPath: string) => string} */
|
|
3
|
+
export default function getReturnPath(fromPath, toPath) {
|
|
4
|
+
// Split the paths into components
|
|
5
|
+
const fromParts = fromPath.replace(/^\.?\/|\/$/g, '').split('/');
|
|
6
|
+
const toParts = toPath.replace(/^\.?\/|\/$/g, '').split('/');
|
|
7
|
+
|
|
8
|
+
// Find the common base path length
|
|
9
|
+
const length = Math.min(fromParts.length, toParts.length);
|
|
10
|
+
let commonBaseLength = 0;
|
|
11
|
+
for (let i = 0; i < length; i++) {
|
|
12
|
+
if (fromParts[i] !== toParts[i]) break;
|
|
13
|
+
commonBaseLength++;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Calculate steps up to the common base
|
|
17
|
+
const stepsUp = '../'.repeat(fromParts.length - commonBaseLength);
|
|
18
|
+
|
|
19
|
+
// Calculate steps down to the target path
|
|
20
|
+
const stepsDown = toParts.slice(commonBaseLength).join('/');
|
|
21
|
+
|
|
22
|
+
// Combine steps up and steps down
|
|
23
|
+
const result = stepsUp + stepsDown;
|
|
24
|
+
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/** @type {(obj1: any, obj2: any) => boolean} */
|
|
3
|
+
export default function isEqual(obj1, obj2) {
|
|
4
|
+
if (obj1 === obj2) {
|
|
5
|
+
return true;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 == null || obj2 == null) {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const keys1 = Object.keys(obj1);
|
|
13
|
+
const keys2 = Object.keys(obj2);
|
|
14
|
+
|
|
15
|
+
if (keys1.length !== keys2.length) {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
for (const key of keys1) {
|
|
20
|
+
if (!keys2.includes(key) || !isEqual(obj1[key], obj2[key])) {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { spawn } from 'child_process';
|
|
3
|
+
|
|
4
|
+
/** @type {(commands: { command: string; name: string; }[], env: import('../../src').VovkEnv) => Promise<void>} */
|
|
5
|
+
export default function parallel(commands, env) {
|
|
6
|
+
return new Promise((resolve, reject) => {
|
|
7
|
+
/** @type {{ name: string; process: import('child_process').ChildProcess; }[]} */
|
|
8
|
+
let processes = [];
|
|
9
|
+
|
|
10
|
+
commands.forEach((cmd) => {
|
|
11
|
+
const processObj = {
|
|
12
|
+
name: cmd.name,
|
|
13
|
+
process: runCommand(
|
|
14
|
+
cmd.command,
|
|
15
|
+
cmd.name,
|
|
16
|
+
/** @type {(code: number) => void} */
|
|
17
|
+
(code) => handleProcessExit(code, cmd.name)
|
|
18
|
+
),
|
|
19
|
+
};
|
|
20
|
+
processes.push(processObj);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** @type {(command: string, name: string, onExit: (code: number) => void) => import('child_process').ChildProcess} */
|
|
24
|
+
function runCommand(command, name, onExit) {
|
|
25
|
+
const proc = spawn(command, { shell: true, env: { ...env, ...process.env }, stdio: 'inherit' });
|
|
26
|
+
|
|
27
|
+
proc.on('exit', onExit);
|
|
28
|
+
|
|
29
|
+
return proc;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @type {(code: number, name: string) => void} */
|
|
33
|
+
function handleProcessExit(code, name) {
|
|
34
|
+
processes = processes.filter((p) => p.name !== name);
|
|
35
|
+
|
|
36
|
+
if (code !== 0) {
|
|
37
|
+
processes.forEach((p) => p.name !== name && p.process.kill('SIGINT'));
|
|
38
|
+
processes = [];
|
|
39
|
+
process.stdout.write('\n');
|
|
40
|
+
return reject(new Error(`Process ${name} exited with code ${code}`));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (!processes.length) {
|
|
44
|
+
resolve();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/** @type {(str: string) => string} */
|
|
4
|
+
function toCamelCase(str) {
|
|
5
|
+
return str.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** @typedef {{ config?: string; project?: string; clientOut?: string }} Flags */
|
|
9
|
+
/** @typedef {'dev' | 'build' | 'generate' | 'help'} Command */
|
|
10
|
+
export default function parseCommandLineArgs() {
|
|
11
|
+
const args = process.argv.slice(2); // Slice off node and script path
|
|
12
|
+
let command = /** @type {Command} */ null;
|
|
13
|
+
/** @type {Flags} */
|
|
14
|
+
const flags = {};
|
|
15
|
+
/** @type {string[]} */
|
|
16
|
+
const unparsedArgs = [];
|
|
17
|
+
|
|
18
|
+
let isUnparsed = false;
|
|
19
|
+
for (const arg of args) {
|
|
20
|
+
if (arg === '--') {
|
|
21
|
+
isUnparsed = true;
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (isUnparsed) {
|
|
26
|
+
unparsedArgs.push(arg);
|
|
27
|
+
} else if (arg.startsWith('--')) {
|
|
28
|
+
const [key, value = true] = arg.slice(2).split('=');
|
|
29
|
+
const camelKey = /** @type {keyof Flags} */ (toCamelCase(key));
|
|
30
|
+
flags[camelKey] = /** @type {string} */ (value);
|
|
31
|
+
} else if (!command) {
|
|
32
|
+
command = /** @type {Command} */ (arg);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const restArgs = unparsedArgs.join(' ');
|
|
37
|
+
|
|
38
|
+
return { command, flags, restArgs };
|
|
39
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import fs from 'fs/promises';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { fileURLToPath } from 'url';
|
|
5
|
+
|
|
6
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
7
|
+
// @ts-ignore Ignore meta-property error
|
|
8
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
10
|
+
/** @type {(path: string) => Promise<boolean>} */
|
|
11
|
+
const fileExists = async (path) => !!(await fs.stat(path).catch(() => false));
|
|
12
|
+
|
|
13
|
+
async function postinstall() {
|
|
14
|
+
const vovk = path.join(__dirname, '../../.vovk');
|
|
15
|
+
const js = path.join(vovk, 'client.js');
|
|
16
|
+
const ts = path.join(vovk, 'client.d.ts');
|
|
17
|
+
const index = path.join(vovk, 'index.ts');
|
|
18
|
+
|
|
19
|
+
if ((await fileExists(js)) || (await fileExists(ts)) || (await fileExists(index))) {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
await fs.mkdir(vovk, { recursive: true });
|
|
24
|
+
await fs.writeFile(js, '/* postinstall */');
|
|
25
|
+
await fs.writeFile(ts, '/* postinstall */');
|
|
26
|
+
await fs.writeFile(index, '/* postinstall */');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
void postinstall();
|