Skip to content

Commit

Permalink
style: add type information lint
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgecasar committed Jan 12, 2024
1 parent 50760f0 commit 46ed2e3
Show file tree
Hide file tree
Showing 12 changed files with 63 additions and 24 deletions.
13 changes: 12 additions & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
module.exports = {
extends: ['@os3/eslint-config', '@os3/eslint-config/jsdoc.cjs', '@os3/eslint-config/prettier.cjs'],
extends: [
'@os3/eslint-config',
'@os3/eslint-config/jsdoc.cjs',
'@os3/eslint-config/type-information.cjs',
'@os3/eslint-config/prettier.cjs',
],
env: {
mocha: true,
},
ignorePatterns: ['/coverage', './dist-types'],
overrides: [
{
extends: ['plugin:@typescript-eslint/disable-type-checked'],
files: ['./test/**/*', 'types/**/*', 'dist-types/**/*', './*.cjs'],
},
],
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"format:fix": "prettier --write .",
"prepare": "npx husky install",
"types": "tsc --build --pretty",
"types:check": "tsc --pretty -p tsconfig.checkOnly.json",
"prepublishOnly": "npm run types",
"release": "npx semantic-release",
"reset": "rm -rf .apimockrc && rm -rf .api-mock-runner",
Expand Down
6 changes: 4 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { MockRunnerError } from './services/utils.js';
try {
await main();
} catch (e) {
const err = new MockRunnerError(e.message, 500, 1, 'Entry point');
err.showError();
if (e instanceof Error) {
const err = new MockRunnerError(e.message, 500, 1, 'Entry point');
err.showError();
}
}
10 changes: 9 additions & 1 deletion src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import { RC_FILE_NAME } from './services/utils.js';
import Logger from './utils/logger.js';
import { messages } from './utils/messages.js';

/**
* @typedef {import('./types/types.d.js').Config} Config
* @typedef {import('./types/types.d.js').Options} Options
* @typedef {import('./types/types.d.js').ProgramOptions} ProgramOptions
*/

/**
* Main function to start the mock server.
* @async
Expand All @@ -22,6 +28,7 @@ export const main = async () => {

program.parse();

/** @type {ProgramOptions} */
const options = program.opts();
const configFileExists = fs.existsSync(`${process.cwd()}/${RC_FILE_NAME}`);
if (options.runConfig && !configFileExists) {
Expand All @@ -30,7 +37,8 @@ export const main = async () => {
return startMockServer.run(config.selectedSchemas);
}
if (options.runConfig) {
const config = JSON.parse(fs.readFileSync(`${process.cwd()}/${RC_FILE_NAME}`));
const config =
/** @type {Config} */ (JSON.parse(fs.readFileSync(`${process.cwd()}/${RC_FILE_NAME}`, 'utf-8'))) || {};
return startMockServer.run(config.selectedSchemas);
}
if (options?.origin) {
Expand Down
11 changes: 6 additions & 5 deletions src/services/find-oas-from-dir.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import Logger from '../utils/logger.js';
import { messages } from '../utils/messages.js';

/**
* @typedef {import('../types/types.js').Schema} Schema
* @typedef {import('../types/types.js').OasFile} OasFile
* @typedef {import('../types/types.d.js').OasFile} OasFile
*/

/**
* Get the first line of a file.
* @param {string} filePath - The path to the file.
Expand All @@ -17,6 +17,7 @@ import { messages } from '../utils/messages.js';
async function getFirstLine(filePath) {
const reader = readline.createInterface({ input: fs.createReadStream(filePath) });
const it = reader[Symbol.asyncIterator]();
/** @type {IteratorResult<string, string>} */
const line = await it.next();
return line.value;
}
Expand Down Expand Up @@ -48,6 +49,7 @@ export const findOasFromDir = async (startPath) => {
}

const files = fs.readdirSync(startPath);
/** @type {OasFile[]} */
const oasFiles = [];

for (const file of files) {
Expand All @@ -68,17 +70,16 @@ export const findOasFromDir = async (startPath) => {
* @async
* @function findOasFromDirRecursive
* @param {string} startPath - The path to the directory.
* @param {OasFile[]} [acc] - An array of OpenAPI specifications.
* @param {OasFile[]} [oasFiles] - An array of OpenAPI specifications.
* @returns {Promise<OasFile[]>} An array of OpenAPI specifications.
*/
export const findOasFromDirRecursive = async (startPath, acc) => {
export const findOasFromDirRecursive = async (startPath, oasFiles = []) => {
if (!fs.existsSync(startPath)) {
Logger.warn(messages.DIRECTORY_NOT_FOUND, startPath);
return [];
}

const files = fs.readdirSync(startPath);
const oasFiles = acc || [];

for (const file of files) {
if (file.startsWith('.')) continue;
Expand Down
4 changes: 2 additions & 2 deletions src/services/inquirer-validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import fs from 'fs';
import { verifyRemoteOrigin } from './utils.js';

/**
* @typedef {import('../types/schema.js').Schema} Schema
* @typedef {import('../types/types.d.js').Schema} Schema
*/

export const errorMessages = Object.freeze({
Expand Down Expand Up @@ -39,7 +39,7 @@ export function originValidator(value) {
export function portValidator(input, selectedSchemas) {
const numericInput = Number(input);
const isInteger = Number.isInteger(numericInput);
if (!isInteger || input < 0 || input > 65535) {
if (!isInteger || numericInput < 0 || numericInput > 65535) {
return errorMessages.port.INVALID;
}
const isPortAlreadySelected = selectedSchemas.some((schema) => schema.port === numericInput);
Expand Down
6 changes: 5 additions & 1 deletion src/services/start-mock-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import Logger from '../utils/logger.js';
import { messages } from '../utils/messages.js';

/**
* @typedef {import('../types/schema.js').Schema} Schema
* @typedef {import('../types/types.d.js').Schema} Schema
* @typedef {import('../types/types.d.js').OpenApiMockerOptions} OpenApiMockerOptions
*/

/**
Expand All @@ -19,13 +20,16 @@ import { messages } from '../utils/messages.js';
async function run(schemas) {
const validatedSchemas = await validateSchemas(schemas);
for (const schema of validatedSchemas) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment
const openApiMocker = new OpenApiMocker({
port: schema.port,
schema: schema.path,
watch: true,
});

// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
await openApiMocker.validate();
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
await openApiMocker.mock();
// Separate each server execution with an empty line
Logger.emptyLine();
Expand Down
23 changes: 14 additions & 9 deletions src/services/user-flow-steps.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import Logger from '../utils/logger.js';
import { messages } from '../utils/messages.js';

/**
* @typedef {import('../types/types.js').Config} Config
* @typedef {import('../types/types.js').Options} Options
* @typedef {import('../types/types.js').Schema} Schema
* @typedef {import('../types/types.d.js').Config} Config
* @typedef {import('../types/types.d.js').Options} Options
* @typedef {import('../types/types.d.js').Schema} Schema
* @typedef {import('../types/types.d.js').OasFile} OasFile
*/

/**
Expand All @@ -24,7 +25,9 @@ import { messages } from '../utils/messages.js';
* @returns {Promise<Config>} An object with the initial values from the user.
*/
async function initWithConfigFile() {
const existingConfig = JSON.parse(fs.readFileSync(`${process.cwd()}/${RC_FILE_NAME}`));
const configFilePath = `${process.cwd()}/${RC_FILE_NAME}`;
const fileContent = fs.readFileSync(configFilePath, 'utf-8');
const existingConfig = /** @type {Config} */ (JSON.parse(fileContent)) || {};
Logger.info(messages.CURRENT_CONFIG, existingConfig);
const useExistingConfig = await confirm({
message: 'Do you want to use the existing config?',
Expand All @@ -37,7 +40,7 @@ async function initWithConfigFile() {
* @async
* @function getSchemas
* @param {string} origin - The origin of the schemas (local or remote).
* @returns {Promise<Array>} An array of schemas.
* @returns {Promise<OasFile[]>} An array of schemas.
*/
async function getSchemas(origin) {
const isOriginRemote = verifyRemoteOrigin(origin);
Expand Down Expand Up @@ -70,11 +73,11 @@ async function getOrigin() {
* Start flow without config.
* @async
* @function init
* @param {Options} options - Cli options.
* @param {Options} [options] - Cli options.
* @returns {Promise<Config>} A object with the complete config.
* @throws {OpenApiSchemaNotFoundError} When no schemas are found in the given directory.
*/
async function init({ origin, schemaPaths, ports } = {}) {
async function init({ origin, schemaPaths, ports } = { schemaPaths: [], ports: [] }) {
const schemasOrigin = origin || (await getOrigin());
const schemas = await getSchemas(schemasOrigin);
if (!schemas.length) {
Expand All @@ -95,6 +98,7 @@ async function init({ origin, schemaPaths, ports } = {}) {
});

const selectedSchemas = ports?.length ? assignPorts(schemasToMock, ports) : await askForPorts(schemasToMock);
/** @type {Config} */
const config = { schemasOrigin, selectedSchemas };

fs.writeFileSync(`${process.cwd()}/${RC_FILE_NAME}`, JSON.stringify(config, null, '\t'));
Expand All @@ -111,7 +115,7 @@ async function init({ origin, schemaPaths, ports } = {}) {
* @param {Options} options - Cli options.
* @returns {Promise<Config>} A object with the complete config.
*/
async function initWithSchemaPaths({ schemaPaths, ports } = {}) {
async function initWithSchemaPaths({ schemaPaths, ports } = { schemaPaths: [], ports: [] }) {
const selectedSchemas = ports?.length ? assignPorts(schemaPaths, ports) : await askForPorts(schemaPaths);
const config = { selectedSchemas };

Expand All @@ -129,12 +133,13 @@ async function initWithSchemaPaths({ schemaPaths, ports } = {}) {
* @returns {Promise<Schema[]>} An array of selected Schemas.
*/
async function askForPorts(schemaPaths) {
/** @type {Schema[]} */
const selectedSchemas = [];
let suggestedPort = 1234;
for (const schemaPath of schemaPaths) {
const port = await input({
message: `Select a port for ${schemaPath}`,
default: suggestedPort,
default: suggestedPort.toString(),
validate: (input) => portValidator(input, selectedSchemas),
});
const portNumber = parseInt(port);
Expand Down
3 changes: 3 additions & 0 deletions src/types/desc.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
declare module '@os3/open-api-mocker';
declare module '@os3/prettier-config';
declare module '@os3/semantic-release-config';
6 changes: 6 additions & 0 deletions src/types/types.js → src/types/types.d.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,10 @@
* @property {string} filePath The path to the file.
*/

/**
* @typedef {object} OpenApiMockerOptions
* @property {number} port - The port to serve the schema.
* @property {string} schema - The path to the schema.
* @property {boolean} watch - Watch for changes in the schema.
*/
export {};
2 changes: 0 additions & 2 deletions src/utils/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ export default class Logger {
* @param {string} type - The type of message to log.
* @param {string} message - The message to log.
* @param {string|object} extra - Additional information to log.
* @private
*/
static #printMessage(type, message, extra) {
console.log(`${type} ${message} ${this.#getExtraFormatted(extra)}`);
Expand All @@ -74,7 +73,6 @@ export default class Logger {
* Private method for formatting the extra parameter.
* @param {string|object} extraParameter - The extra parameter to format.
* @returns {string} The formatted extra parameter.
* @private
*/
static #getExtraFormatted(extraParameter) {
if (!extraParameter || typeof extraParameter === 'object') {
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
"rootDir": "."
},
"include": ["src"],
"exclude": ["dist-types", "node_modules", "tests"]
"exclude": ["dist-types", "node_modules", "test"]
}

0 comments on commit 46ed2e3

Please sign in to comment.