You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

swagger-typescript-api

Package Overview
Dependencies
Maintainers
1
Versions
154
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

swagger-typescript-api - npm Package Compare versions

Comparing version

to
11.0.0--beta-4

CHANGELOG.md

26

cli/execute.js

@@ -16,2 +16,3 @@ const _ = require("lodash");

reject(new Error(error));
return;
}

@@ -95,5 +96,18 @@

if (i === 0) {
command = commands[arg] || commands[root_command];
allFlagKeys = command.options.reduce((acc, option) => [...acc, ...option.flags.keys], []);
command = commands[arg];
if (!command && !arg.startsWith("-")) {
const tip = didYouMean(arg, _.keys(commands));
error = `unknown command ${arg}${tip ? `\n(Did you mean ${tip} ?)` : ""}`;
} else if (!command) {
command = commands[root_command];
}
if (command) {
allFlagKeys = command.options.reduce((acc, option) => [...acc, ...option.flags.keys], []);
}
}
if (error) return;
if (arg.startsWith("-")) {

@@ -132,2 +146,10 @@ const option = command.options.find((option) => option.flags.keys.includes(arg));

if (error) {
return {
command: null,
usageOptions: [],
error,
};
}
return {

@@ -134,0 +156,0 @@ command,

@@ -11,3 +11,3 @@ const _ = require("lodash");

const addCommand = (command) => {
const addCommand = (command, { addVersion = false, addHelp = true } = {}) => {
commands[command.name] = {

@@ -19,2 +19,22 @@ name: command.name,

if (addVersion) {
commands[command.name].options.unshift(
processOption({
flags: "-v, --version",
description: "output the current version",
operation: () => displayVersion(instance),
}),
);
}
if (addHelp) {
commands[command.name].options.push(
processOption({
flags: "-h, --help",
description: "display help for command",
operation: () => displayHelp(commands, instance, commands[command.name]),
}),
);
}
return instance;

@@ -30,6 +50,12 @@ };

addCommand({
name: root_command,
options: [],
});
addCommand(
{
name: root_command,
options: [],
},
{
addVersion: false,
addHelp: false,
},
);

@@ -61,3 +87,3 @@ _.forEach(input.options, (option) => {

description: "display help for command",
operation: () => displayHelp(commands, instance),
operation: () => displayHelp(commands, instance, commands[root_command]),
}),

@@ -64,0 +90,0 @@ );

119

cli/operations/display-help.js
const _ = require("lodash");
const { root_command } = require("../constants");
const displayHelp = (commands, instance) => {
const generateOptionsOutput = (options) =>
options.reduce(
(acc, option) => {
const flags = `${option.flags.keys.join(", ")}${option.flags.value?.raw ? ` ${option.flags.value?.raw}` : ""}`;
const description = `${option.description || ""}${
option.default === undefined || (option.flags.isNoFlag && option.default === true)
? ""
: ` (default: ${typeof option.default === "string" ? `"${option.default}"` : option.default})`
}`;
const generateOptionsOutput = (options) =>
options.reduce(
(acc, option) => {
const flags = `${option.flags.keys.join(", ")}${option.flags.value?.raw ? ` ${option.flags.value?.raw}` : ""}`;
const description = `${option.description || ""}${
option.default === undefined || (option.flags.isNoFlag && option.default === true)
? ""
: ` (default: ${typeof option.default === "string" ? `"${option.default}"` : option.default})`
}`;
if (flags.length > acc.maxLength) {
acc.maxLength = flags.length;
}
if (flags.length > acc.maxLength) {
acc.maxLength = flags.length;
}
acc.options.push({
flags,
description,
});
return acc;
},
{
options: [],
maxLength: 0,
},
);
acc.options.push({
flags,
description,
});
return acc;
},
{
options: [],
maxLength: 0,
},
);
const generateOptionsTextOutput = (options, maxLength, spaces) =>
options
.map((option) => {
const spacesText = Array(spaces).fill(" ").join("");
const leftStr = `${spacesText}${option.flags.padEnd(maxLength, " ")} `;
const leftStrFiller = Array(leftStr.length).fill(" ").join("");
const descriptionLines = option.description.split("\n");
return (
leftStr +
descriptionLines
.map((line, i) => {
if (i === 0) {
return line;
}
return `\n${leftStrFiller}${line}`;
})
.join("")
);
})
.join("\n");
const displayAllHelp = (commands, instance) => {
const { options, maxLength: maxOptionLength } = generateOptionsOutput(commands[root_command].options);

@@ -60,25 +83,2 @@

const generateOptionsTextOutput = (options, maxLength, spaces) =>
options
.map((option) => {
const spacesText = Array(spaces).fill(" ").join("");
const leftStr = `${spacesText}${option.flags.padEnd(maxLength, " ")} `;
const leftStrFiller = Array(leftStr.length).fill(" ").join("");
const descriptionLines = option.description.split("\n");
return (
leftStr +
descriptionLines
.map((line, i) => {
if (i === 0) {
return line;
}
return `\n${leftStrFiller}${line}`;
})
.join("")
);
})
.join("\n");
const optionsOutput = generateOptionsTextOutput(options, maxOptionLength, 2);

@@ -132,4 +132,29 @@

const displayHelp = (commands, instance, command) => {
const rootCommand = commands[root_command];
if (command.name === root_command) return displayAllHelp(commands, instance);
const { options, maxLength: maxOptionLength } = generateOptionsOutput(command.options);
const optionsOutput = generateOptionsTextOutput(options, maxOptionLength, 2);
const outputTest = [
optionsOutput &&
`Options:
${optionsOutput}`,
]
.filter(Boolean)
.join("\n\n");
console.log(`Usage: ${instance.input.name} ${command.name}${optionsOutput ? " [options]" : ""}
${
command.description &&
`
${command.description}`
}
${outputTest}`);
};
module.exports = {
displayHelp,
};

@@ -0,1 +1,3 @@

type HttpClientType = "axios" | "fetch";
interface GenerateApiParamsBase {

@@ -37,3 +39,3 @@ /**

*/
httpClientType?: "axios" | "fetch";
httpClientType?: HttpClientType;
/**

@@ -503,1 +505,13 @@ * use "default" response status code as success response too.

export declare function generateApi(params: GenerateApiParams): Promise<GenerateApiOutput>;
export interface GenerateTemplatesParams {
cleanOutput?: boolean;
output?: string;
httpClientType?: HttpClientType;
modular?: boolean;
silent?: boolean;
}
export interface GenerateTemplatesOutput extends Pick<GenerateApiOutput, "files" | "createFile"> {}
export declare function generateTemplates(params: GenerateTemplatesParams): Promise<GenerateTemplatesOutput>;

@@ -12,6 +12,11 @@ #!/usr/bin/env node

const { cli } = require("./cli");
const { generateApi } = require("./src");
const { generateApi, generateTemplates } = require("./src");
const { HTTP_CLIENT } = require("./src/constants");
const { resolve } = require("path");
const { CodeGenConfig } = require("./src/configuration");
const { TemplatesGenConfig } = require("./src/commands/generate-templates/configuration");
const codeGenBaseConfig = new CodeGenConfig({});
const templateGenBaseConfig = new TemplatesGenConfig({});
const program = cli({

@@ -36,3 +41,3 @@ name: name,

description: "name of output typescript api file",
default: "Api.ts",
default: `${codeGenBaseConfig.apiClassName}.ts`,
},

@@ -48,3 +53,3 @@ {

'some swagger schemas use "default" response status code as success response type by default.',
default: false,
default: codeGenBaseConfig.defaultResponseAsSuccess,
},

@@ -54,3 +59,3 @@ {

description: "generate additional information about request responses\n" + "also add typings for bad responses",
default: false,
default: codeGenBaseConfig.generateResponses,
},

@@ -60,3 +65,3 @@ {

description: 'generate all "enum" types as union types (T1 | T2 | TN)',
default: false,
default: codeGenBaseConfig.generateUnionEnums,
},

@@ -66,3 +71,3 @@ {

description: "generate readonly properties",
default: false,
default: codeGenBaseConfig.addReadonly,
},

@@ -72,3 +77,3 @@ {

description: "generate type definitions for API routes",
default: false,
default: codeGenBaseConfig.generateRouteTypes,
},

@@ -78,3 +83,3 @@ {

description: "do not generate an API class",
default: true,
default: codeGenBaseConfig.generateClient,
},

@@ -84,3 +89,3 @@ {

description: "use values in 'x-enumNames' as enum values (not only as keys)",
default: false,
default: codeGenBaseConfig.enumNamesAsValues,
},

@@ -91,3 +96,3 @@ {

"extract request params to data contract (Also combine path params and query params into one object)",
default: false,
default: codeGenBaseConfig.extractRequestParams,
},

@@ -97,3 +102,3 @@ {

description: "extract request body type to data contract",
default: false,
default: codeGenBaseConfig.extractRequestBody,
},

@@ -103,3 +108,3 @@ {

description: "extract response body type to data contract",
default: false,
default: codeGenBaseConfig.extractResponseBody,
},

@@ -109,3 +114,3 @@ {

description: "extract response error type to data contract",
default: false,
default: codeGenBaseConfig.extractResponseError,
},

@@ -115,3 +120,3 @@ {

description: "generate separated files for http client, data contracts, and routes",
default: false,
default: codeGenBaseConfig.modular,
},

@@ -121,3 +126,3 @@ {

description: "generate js api module with declaration file",
default: false,
default: codeGenBaseConfig.toJS,
},

@@ -128,3 +133,3 @@ {

"determines which path index should be used for routes separation (example: GET:/fruites/getFruit -> index:0 -> moduleName -> fruites)",
default: 0,
default: codeGenBaseConfig.moduleNameIndex,
},

@@ -134,3 +139,3 @@ {

description: "splits routes based on the first tag",
default: false,
default: codeGenBaseConfig.moduleNameFirstTag,
},

@@ -140,3 +145,3 @@ {

description: "disabled strict SSL",
default: false,
default: codeGenBaseConfig.disableStrictSSL,
},

@@ -146,3 +151,3 @@ {

description: "disabled proxy",
default: false,
default: codeGenBaseConfig.disableProxy,
},

@@ -152,3 +157,3 @@ {

description: "generate axios http client",
default: false,
default: codeGenBaseConfig.httpClientType === "axios",
},

@@ -158,3 +163,3 @@ {

description: "unwrap the data item from the response",
default: false,
default: codeGenBaseConfig.unwrapResponseData,
},

@@ -164,3 +169,3 @@ {

description: "Do not throw an error when response.ok is not true",
default: false,
default: codeGenBaseConfig.disableThrowOnError,
},

@@ -170,3 +175,3 @@ {

description: "Ability to send HttpClient instance to Api constructor",
default: false,
default: codeGenBaseConfig.singleHttpClient,
},

@@ -176,3 +181,3 @@ {

description: "Output only errors to console",
default: false,
default: codeGenBaseConfig.silent,
},

@@ -182,3 +187,3 @@ {

description: "default type for empty response schema",
default: "void",
default: codeGenBaseConfig.defaultResponseType,
},

@@ -188,3 +193,3 @@ {

description: "data contract name prefix",
default: "",
default: codeGenBaseConfig.typePrefix,
},

@@ -194,3 +199,3 @@ {

description: "data contract name suffix",
default: "",
default: codeGenBaseConfig.typeSuffix,
},

@@ -200,3 +205,3 @@ {

description: "clean output folder before generate api. WARNING: May cause data loss",
default: false,
default: codeGenBaseConfig.cleanOutput,
},

@@ -210,3 +215,3 @@ {

description: "fix up small errors in the swagger source definition",
default: false,
default: codeGenBaseConfig.patch,
},

@@ -216,3 +221,3 @@ {

description: "additional information about processes inside this tool",
default: false,
default: codeGenBaseConfig.debug,
},

@@ -222,3 +227,3 @@ {

description: "generate array types as Array<Type> (by default Type[])",
default: false,
default: codeGenBaseConfig.anotherArrayType,
},

@@ -228,3 +233,3 @@ {

description: "sort fields and types",
default: false,
default: codeGenBaseConfig.sortTypes,
},

@@ -234,2 +239,36 @@ ],

program.addCommand({
name: "generate-templates",
description: `Generate ".ejs" templates needed for generate api`,
options: [
{
flags: "-o, --output <string>",
description: "output path of generated templates",
default: templateGenBaseConfig.output,
},
{
flags: "-m, --modular",
description: "generate templates needed to separate files for http client, data contracts, and routes",
default: templateGenBaseConfig.modular,
},
{
flags: "--http-client <string>",
description: `http client type (possible values: ${Object.values(HTTP_CLIENT)
.map((v) => `"${v}"`)
.join(", ")})`,
default: templateGenBaseConfig.httpClientType,
},
{
flags: "-c, --clean-output",
description: "clean output folder before generate template. WARNING: May cause data loss",
default: templateGenBaseConfig.cleanOutput,
},
{
flags: "--silent",
description: "Output only errors to console",
default: templateGenBaseConfig.silent,
},
],
});
const main = async () => {

@@ -282,3 +321,3 @@ const { command, options } = await program.execute({ args: process.argv });

case "generate-templates": {
console.info("todo");
await generateTemplates(options);
break;

@@ -285,0 +324,0 @@ }

{
"name": "swagger-typescript-api",
"version": "11.0.0--beta-3",
"version": "11.0.0--beta-4",
"description": "Generate typescript/javascript api from swagger schema",

@@ -5,0 +5,0 @@ "scripts": {

@@ -7,3 +7,3 @@ const _ = require("lodash");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -10,0 +10,0 @@ config;

@@ -9,3 +9,3 @@ const { SwaggerSchemaResolver } = require("./swagger-schema-resolver.js");

const { SchemaRoutes } = require("./schema-parser/schema-routes.js");
const { Configuration } = require("./configuration.js");
const { CodeGenConfig } = require("./configuration.js");
const { FileSystem } = require("./util/file-system");

@@ -21,3 +21,3 @@ const { Templates } = require("./templates");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -63,3 +63,3 @@ config;

constructor(config) {
this.config = new Configuration(config);
this.config = new CodeGenConfig(config);
this.logger = new Logger(this.config);

@@ -66,0 +66,0 @@ this.fileSystem = new FileSystem();

const { objectAssign } = require("./util/object-assign");
const _ = require("lodash");
const constantsBase = require("./constants.js");
const packageJson = require("../package.json");
const { NameResolver, ComponentTypeNameResolver } = require("./util/name-resolver");
const CONSTANTS = require("./constants");
const { ComponentTypeNameResolver } = require("./util/name-resolver");
const { cosmiconfigSync } = require("cosmiconfig");
const CONSTANTS = require("./constants");

@@ -37,4 +35,4 @@ const TsKeyword = {

*/
class Configuration {
version = packageJson.version;
class CodeGenConfig {
version = CONSTANTS.PROJECT_VERSION;
/** CLI flag */

@@ -319,3 +317,3 @@ templates = "../templates/default";

constants: {
...constantsBase,
...CONSTANTS,
...constants,

@@ -353,3 +351,3 @@ },

module.exports = {
Configuration,
CodeGenConfig,
};

@@ -0,1 +1,2 @@

const packageJson = require("../package.json");
const RESERVED_QUERY_ARG_NAMES = ["query", "queryParams", "queryArg"];

@@ -26,2 +27,4 @@ const RESERVED_BODY_ARG_NAMES = ["data", "body", "reqBody"];

const PROJECT_VERSION = packageJson.version;
const FILE_PREFIX = `/* eslint-disable */

@@ -43,2 +46,3 @@ /* tslint:disable */

DEFAULT_BODY_ARG_NAME: "data",
PROJECT_VERSION,
SCHEMA_TYPES,

@@ -45,0 +49,0 @@ HTTP_CLIENT,

@@ -12,2 +12,3 @@ #!/usr/bin/env node

const { CodeGenProcess } = require("./code-gen-process.js");
const { generateTemplates } = require("./commands/generate-templates");

@@ -24,3 +25,5 @@ module.exports = {

},
generateTemplates: (config) => {},
generateTemplates: async (config) => {
return await generateTemplates(config);
},
};

@@ -9,3 +9,3 @@ const _ = require("lodash");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -12,0 +12,0 @@ config;

@@ -6,3 +6,3 @@ const { SCHEMA_TYPES } = require("../constants");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -9,0 +9,0 @@ config;

@@ -8,3 +8,3 @@ const { SCHEMA_TYPES } = require("../constants.js");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -11,0 +11,0 @@ config;

@@ -23,3 +23,3 @@ const _ = require("lodash");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -26,0 +26,0 @@ config;

@@ -1,2 +0,1 @@

const { Configuration } = require("./configuration.js");
const _ = require("lodash");

@@ -10,3 +9,3 @@ const converter = require("swagger2openapi");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -13,0 +12,0 @@ config;

@@ -8,3 +8,3 @@ const { resolve } = require("path");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -11,0 +11,0 @@ config;

@@ -7,3 +7,3 @@ const _ = require("lodash");

/** @type {Configuration} */
/** @type {CodeGenConfig} */
config;

@@ -10,0 +10,0 @@

@@ -26,2 +26,6 @@ const fs = require("fs");

readDir = (path) => {
return fs.readdirSync(path);
};
pathIsDir = (path) => {

@@ -28,0 +32,0 @@ if (!path) return false;

@@ -7,3 +7,3 @@ const { emojify } = require("node-emoji");

/**
* @type {Configuration}
* @type {CodeGenConfig}
*/

@@ -10,0 +10,0 @@ config;

Sorry, the diff of this file is not supported yet