Skip to content

Commit c01d3f1

Browse files
committed
Fix code style in whole codebase
1 parent a03003d commit c01d3f1

30 files changed

Lines changed: 204 additions & 182 deletions

impress.js

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ process.title = 'impress';
55
const fsp = require('node:fs').promises;
66
const { Worker } = require('node:worker_threads');
77
const path = require('node:path');
8+
89
const { Config } = require('metaconfiguration');
910
const metavm = require('metavm');
1011
const { Pool, isError } = require('metautil');
@@ -39,7 +40,7 @@ const exit = async (message, code) => {
3940
if (impress.finalization) return;
4041
impress.finalization = true;
4142
impress.console.info(message);
42-
if (impress.logger && impress.logger.active) await impress.logger.close();
43+
if (impress.logger?.active) await impress.logger.close();
4344
process.exit(code);
4445
};
4546

@@ -150,7 +151,8 @@ const validateConfig = async (config) => {
150151
const checkResult = schema.check(config[section]);
151152
if (!checkResult.valid) {
152153
for (const error of checkResult.errors) {
153-
impress.console.error(`${error} in application/config/${section}.js`);
154+
const loc = `application/config/${section}.js`;
155+
impress.console.error(`${error} in ${loc}`);
154156
}
155157
valid = false;
156158
}
@@ -162,7 +164,8 @@ const loadApplication = async (root, dir, master) => {
162164
impress.console.info(`Start: ${dir}`);
163165
const configPath = path.join(dir, 'config');
164166
const config = await new Config(configPath, CFG_OPTIONS).catch((error) => {
165-
exit(`Can not read configuration: ${configPath}\n${error.stack}`, 1);
167+
const { stack } = error;
168+
exit(`Can not read configuration: ${configPath}\n${stack}`, 1);
166169
});
167170
await validateConfig(config);
168171
if (master) {
@@ -190,11 +193,17 @@ const loadApplication = async (root, dir, master) => {
190193
impress.applications.set(dir, app);
191194
};
192195

196+
const parseApplicationsFile = async () => {
197+
try {
198+
const data = await fsp.readFile('.applications', 'utf8');
199+
return data.split(/[\r\n\s]+/).filter((s) => s.length !== 0);
200+
} catch {
201+
return [path.join(PATH, 'application')];
202+
}
203+
};
204+
193205
const loadApplications = async () => {
194-
const applications = await fsp
195-
.readFile('.applications', 'utf8')
196-
.then((data) => data.split(/[\r\n\s]+/).filter((s) => s.length !== 0))
197-
.catch(() => [path.join(PATH, 'application')]);
206+
const applications = await parseApplicationsFile();
198207
let master = true;
199208
for (const dir of applications) {
200209
const location = path.isAbsolute(dir) ? dir : path.join(PATH, dir);

lib/api.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@ class Api extends Place {
6363
const unit = proc.exports;
6464
const relPath = filePath.substring(this.path.length + 1);
6565
const [unitDir, methodFile] = relPath.split(node.path.sep);
66-
const unitName = unitDir.includes('.') ? unitDir : `${unitDir}.1`;
66+
const hasVersion = unitDir.includes('.');
67+
const unitName = hasVersion ? unitDir : `${unitDir}.1`;
6768
if (methodFile) {
6869
const name = node.path.basename(methodFile, '.js');
6970
return void this.changeUnit(unitName, name, proc);
@@ -72,8 +73,8 @@ class Api extends Place {
7273
return void this.loadPlugin(unitName, unit);
7374
}
7475
for (const name of Object.keys(unit)) {
75-
const proc = new Procedure(script, name, this.application);
76-
this.changeUnit(unitName, name, proc);
76+
const methodProc = new Procedure(script, name, this.application);
77+
this.changeUnit(unitName, name, methodProc);
7778
}
7879
}
7980

@@ -87,9 +88,9 @@ class Api extends Place {
8788
const options = { context };
8889
const { exports } = metarhia.metavm.createScript(name, pluginSrc, options);
8990
const plugin = exports(unit);
90-
for (const [name, script] of Object.entries(plugin)) {
91-
const proc = new Procedure(script, name, this.application);
92-
this.changeUnit(unitName, name, proc);
91+
for (const [methodName, script] of Object.entries(plugin)) {
92+
const proc = new Procedure(script, methodName, this.application);
93+
this.changeUnit(unitName, methodName, proc);
9394
}
9495
}
9596

lib/application.js

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,13 @@ const ERR_INIT = 'Can not initialize an Application';
2626
const ERR_TEST = 'Application tests failed';
2727
const TEST_DELAY = 100;
2828

29+
const placeFromPath = (filePath, appPath) => {
30+
const relPath = filePath.substring(appPath.length + 1);
31+
const sepIndex = relPath.indexOf(node.path.sep);
32+
const place = relPath.substring(0, sepIndex);
33+
return { relPath, place };
34+
};
35+
2936
class Application extends EventEmitter {
3037
constructor() {
3138
super();
@@ -98,35 +105,42 @@ class Application extends EventEmitter {
98105
async start() {
99106
const { sandbox, config, cert, mode } = this;
100107
const { kind, port } = workerData;
108+
if (sandbox.api.auth) {
109+
const provider = sandbox.api.auth.provider || auth(config.sessions);
110+
this.auth = provider;
111+
sandbox.api.auth.provider = provider;
112+
}
113+
const { concurrency, size, timeout } = config.server.queue;
114+
this.semaphore = new Semaphore({ concurrency, size, timeout });
101115
if (kind === 'balancer') {
102116
const options = { ...config.server, port };
103117
this.server = new Balancer(this, options);
104118
await this.server.listen();
105119
} else if (kind === 'server') {
106120
const options = { ...config.server, port };
107-
if (config.server.protocol === 'https') {
121+
const isHttps = config.server.protocol === 'https';
122+
if (isHttps) {
108123
options.SNICallback = (servername, callback) => {
109124
const domain = cert.get(servername);
110-
if (!domain) callback(new Error(`No certificate for ${servername}`));
111-
else callback(null, domain.creds);
125+
if (domain === undefined) {
126+
const err = new Error(`No certificate for ${servername}`);
127+
callback(err);
128+
} else {
129+
callback(null, domain.creds);
130+
}
112131
};
113132
}
114133
this.server = new Server(this, options);
115134
this.server.httpServer.on('request', (req, res) => {
116-
if (!req.url.startsWith('/api')) this.static.serve(req.url, req, res);
135+
const isApi = req.url.startsWith('/api');
136+
if (!isApi) this.static.serve(req.url, req, res);
117137
});
118138
await this.server.listen();
119139
}
120-
if (sandbox.api.auth) {
121-
const provider = sandbox.api.auth.provider || auth(config.sessions);
122-
this.auth = provider;
123-
sandbox.api.auth.provider = provider;
124-
}
125-
const { concurrency, size, timeout } = config.server.queue;
126-
this.semaphore = new Semaphore({ concurrency, size, timeout });
127140
this.initialization = false;
128141
sandbox.application.emit('started');
129-
if (mode === 'test' && threadId === 1) this.runTests();
142+
const shouldRunTests = mode === 'test' && threadId === 1;
143+
if (shouldRunTests) this.runTests();
130144
}
131145

132146
async runTests() {
@@ -201,9 +215,7 @@ class Application extends EventEmitter {
201215
this.watcher = new DirectoryWatcher({ timeout });
202216

203217
this.watcher.on('change', (filePath) => {
204-
const relPath = filePath.substring(this.path.length + 1);
205-
const sepIndex = relPath.indexOf(node.path.sep);
206-
const place = relPath.substring(0, sepIndex);
218+
const { relPath, place } = placeFromPath(filePath, this.path);
207219
const target = this[place];
208220
if (!target) return;
209221
node.fs.stat(filePath, (error, stat) => {
@@ -221,9 +233,7 @@ class Application extends EventEmitter {
221233
});
222234

223235
this.watcher.on('delete', async (filePath) => {
224-
const relPath = filePath.substring(this.path.length + 1);
225-
const sepIndex = relPath.indexOf(node.path.sep);
226-
const place = relPath.substring(0, sepIndex);
236+
const { relPath, place } = placeFromPath(filePath, this.path);
227237
const target = this[place];
228238
if (!target) return;
229239
target.delete(filePath);

lib/auth.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ module.exports = ({ characters, secret, length }) => ({
2020
},
2121

2222
async readSession(token) {
23-
return sessions.get(token) || null;
23+
return sessions.get(token) ?? null;
2424
},
2525

2626
async deleteSession(token) {

lib/balancer.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
'use strict';
22

33
const http = require('node:http');
4+
45
const { parseHost, sample } = require('metautil');
56
const { buildHeaders } = require('metacom');
67

78
const DEFAULT_LISTEN_RETRY = 3;
9+
const SAFE_REDIRECT_METHODS = ['GET', 'HEAD'];
810

911
class Balancer {
1012
#console = null;
@@ -35,7 +37,8 @@ class Balancer {
3537
const targetPath = req.url;
3638
const location = `${protocol}://${host}:${targetPort}${targetPath}`;
3739
if (res.headersSent) return;
38-
const code = ['GET', 'HEAD'].includes(req.method) ? 302 : 307;
40+
const isSafe = SAFE_REDIRECT_METHODS.includes(req.method);
41+
const code = isSafe ? 302 : 307;
3942
res.writeHead(code, { ...this.#headers, Location: location });
4043
res.end();
4144
}
@@ -57,7 +60,8 @@ class Balancer {
5760

5861
const onError = (error) => {
5962
count--;
60-
const fatal = error.code !== 'EADDRINUSE' || count === 0;
63+
const addressInUse = error.code === 'EADDRINUSE';
64+
const fatal = !addressInUse || count === 0;
6165
if (fatal) return void reject(error);
6266
this.#console.warn(`Address in use: ${host}:${port}, retry...`);
6367
setTimeout(listen, timeouts.bind);

lib/bus.js

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,27 +15,31 @@ const prepare = (unit, application) => {
1515
const { parameters, query, returns } = validation;
1616
if (parameters) {
1717
const { valid, errors } = parameters.check(args);
18-
const problems = errors.join('; ');
19-
if (!valid) return new Error(`Invalid parameters type: ${problems}`);
18+
if (!valid) {
19+
return new Error(`Invalid parameters type: ${errors.join('; ')}`);
20+
}
2021
}
2122
if (unit.query.params) {
2223
const { valid, errors } = query.check(args);
23-
const problems = errors.join('; ');
24-
if (!valid) return new Error(`Invalid query type: ${problems}`);
24+
if (!valid) {
25+
return new Error(`Invalid query type: ${errors.join('; ')}`);
26+
}
2527
}
2628
const service = method.parent['.service'];
2729
const verb = unit.method.get ? 'get' : 'post';
2830
const target = [service.url, unit.method[verb]];
2931
if (unit.method.path) {
30-
target.push(...unit.method.path.map((arg) => args[arg]));
32+
const pathParts = unit.method.path.map((arg) => args[arg]);
33+
target.push(...pathParts);
3134
}
3235
let url = target.join('/');
3336
if (unit.query) {
3437
const params = [];
3538
const { prefix = '', suffix = '' } = unit.query;
3639
for (const param of Object.keys(unit.query.params)) {
3740
if (!args[param]) continue;
38-
params.push([`${prefix}${param}${suffix}`, args[param]]);
41+
const key = `${prefix}${param}${suffix}`;
42+
params.push([key, args[param]]);
3943
}
4044
const parsedParams = Object.fromEntries(params);
4145
const stringParams = new URLSearchParams(parsedParams).toString();
@@ -46,8 +50,9 @@ const prepare = (unit, application) => {
4650
const result = await metarhia.metautil.httpApiCall(url, options);
4751
if (returns) {
4852
const { valid, errors } = returns.check(result);
49-
const problems = errors.join('; ');
50-
if (!valid) return new Error(`Invalid result type: ${problems}`);
53+
if (!valid) {
54+
return new Error(`Invalid result type: ${errors.join('; ')}`);
55+
}
5156
}
5257
return result;
5358
};

lib/cert.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,9 @@ class Cert extends Static {
6060
const creds = node.tls.createSecureContext(options);
6161
const context = { ...options, creds };
6262
for (const domain of domains) this.domains.set(domain, context);
63-
if (!this.application.server?.httpServer.setSecureContext) continue;
64-
this.application.server.httpServer.setSecureContext(options);
63+
const httpServer = this.application.server?.httpServer;
64+
if (!httpServer?.setSecureContext) continue;
65+
httpServer.setSecureContext(options);
6566
} catch (error) {
6667
for (const domain of domains) this.domains.delete(domain);
6768
this.application.console.error(error.stack);

lib/code.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ class Code extends Place {
3434
for (let depth = 0; depth <= last; depth++) {
3535
const name = names[depth];
3636
let next = level[name];
37-
if (depth === last) {
37+
const isLeaf = depth === last;
38+
if (isLeaf) {
3839
if (unit === null) {
3940
if (name === 'stop') this.stopModule(names[0], level);
4041
delete level[name];
@@ -48,8 +49,10 @@ class Code extends Place {
4849
let { start } = unit;
4950
if (start) start = start.bind(unit);
5051
if (depth === 1 && name === 'start') start = unit;
51-
if (start) {
52-
if (start.constructor.name === 'AsyncFunction') {
52+
const shouldRegister = start && (isLeaf || name === 'start');
53+
if (shouldRegister) {
54+
const isAsync = start.constructor.name === 'AsyncFunction';
55+
if (isAsync) {
5356
this.application.starts.push(start);
5457
} else {
5558
const msg = `${relPath}/start expected to be async function`;

lib/deps.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const CWD = process.cwd();
44

55
const wt = require('node:worker_threads');
66
const { createRequire, builtinModules } = require('node:module');
7+
78
const metautil = require('metautil');
89
const appRequire = createRequire(`file://${CWD}/server.js`);
910

@@ -46,7 +47,8 @@ const validSubmodules = (key) =>
4647

4748
const loadModule = (name) => {
4849
const lib = appRequire(name);
49-
const pkg = require(`${CWD}/node_modules/${name}/package.json`);
50+
const pkgPath = `${CWD}/node_modules/${name}/package.json`;
51+
const pkg = require(pkgPath);
5052
if (!pkg.exports) return lib;
5153
const subKeys = Object.keys(pkg.exports).map((key) => key.substring(2));
5254
const subNames = subKeys.filter(validSubmodules);
@@ -73,13 +75,15 @@ for (const name of dependencies) {
7375
let lib = null;
7476
try {
7577
if (internals.includes(name)) {
76-
const realName = name.startsWith('node:') ? name : `node:${name}`;
78+
const hasPrefix = name.startsWith('node:');
79+
const realName = hasPrefix ? name : `node:${name}`;
7780
lib = require(realName);
7881
} else {
7982
lib = loadModule(name);
8083
}
8184
} catch (error) {
82-
if (npmpkg.includes(name) || !optional.includes(name)) {
85+
const isRequired = npmpkg.includes(name) || !optional.includes(name);
86+
if (isRequired) {
8387
notLoaded.add(`- ${name}: ${error.stack}`);
8488
}
8589
continue;

lib/place.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Place {
2222
else await this.change(filePath);
2323
}
2424
} catch (error) {
25-
const console = this.application.console || global.console;
25+
const console = this.application.console ?? global.console;
2626
console.error(error.stack);
2727
}
2828
}

0 commit comments

Comments
 (0)