diff --git a/.ncurc.json b/.ncurc.json index da7ff7a5..868ca9ec 100644 --- a/.ncurc.json +++ b/.ncurc.json @@ -1,7 +1,4 @@ { "upgrade": true, - "reject": [ - "nanoid", - "eta" - ] -} \ No newline at end of file + "reject": ["nanoid", "eta"] +} diff --git a/biome.json b/biome.json index 394d1ad5..f28f45b8 100644 --- a/biome.json +++ b/biome.json @@ -1,5 +1,15 @@ { "$schema": "node_modules/@biomejs/biome/configuration_schema.json", + "files": { + "ignore": [ + "package.json", + "tests/**/*.json", + "tests/**/expected.ts", + "tests/**/expected/**", + "tests/**/generated/**", + "tests/**/schema.ts" + ] + }, "formatter": { "enabled": true, "indentStyle": "space" diff --git a/cli/constants.js b/cli/constants.js index ed50bc9f..02b90d01 100644 --- a/cli/constants.js +++ b/cli/constants.js @@ -1,7 +1,7 @@ -const root_command = Symbol('root'); -const skip_command = Symbol('skip'); +const root_command = Symbol("root"); +const skip_command = Symbol("skip"); -const reservedOptions = ['version', 'help']; +const reservedOptions = ["version", "help"]; module.exports = { root_command, diff --git a/cli/execute.js b/cli/execute.js index 263ffd85..ee403844 100644 --- a/cli/execute.js +++ b/cli/execute.js @@ -1,7 +1,7 @@ -const _ = require('lodash'); -const { root_command, skip_command } = require('./constants'); -const { parseArgs } = require('./parse-args'); -const didYouMean = require('didyoumean'); +const _ = require("lodash"); +const { root_command, skip_command } = require("./constants"); +const { parseArgs } = require("./parse-args"); +const didYouMean = require("didyoumean"); didYouMean.threshold = 0.5; @@ -19,7 +19,7 @@ const execute = (params, commands, instance) => { if (!usageOptions.length && command.name === root_command) { usageOptions.push( - command.options.find((option) => option.flags.name === 'help'), + command.options.find((option) => option.flags.name === "help"), ); } @@ -32,7 +32,7 @@ const execute = (params, commands, instance) => { }); return; } else { - let error = ''; + let error = ""; const processUserOptionData = (userOption, option) => { if (userOption) { @@ -43,7 +43,7 @@ const execute = (params, commands, instance) => { if (option.flags.value) { if (option.flags.value.variadic) { return data.reduce((acc, d) => { - acc.push(...d.split(',').map(option.flags.value.formatter)); + acc.push(...d.split(",").map(option.flags.value.formatter)); return acc; }, []); } else { @@ -94,7 +94,7 @@ const processArgs = (commands, args) => { let command = null; let usageOptions = []; let walkingOption = null; - let error = ''; + let error = ""; let allFlagKeys = []; @@ -104,10 +104,10 @@ const processArgs = (commands, args) => { if (i === 0) { command = commands[arg]; - if (!command && !arg.startsWith('-')) { + if (!command && !arg.startsWith("-")) { const tip = didYouMean(arg, _.keys(commands)); error = `unknown command ${arg}${ - tip ? `\n(Did you mean ${tip} ?)` : '' + tip ? `\n(Did you mean ${tip} ?)` : "" }`; } else if (!command) { command = commands[root_command]; @@ -123,7 +123,7 @@ const processArgs = (commands, args) => { if (error) return; - if (arg.startsWith('-')) { + if (arg.startsWith("-")) { const option = command.options.find((option) => option.flags.keys.includes(arg), ); @@ -131,7 +131,7 @@ const processArgs = (commands, args) => { if (!option) { const tip = didYouMean(arg, allFlagKeys); error = `unknown option ${arg}${ - tip ? `\n(Did you mean ${tip} ?)` : '' + tip ? `\n(Did you mean ${tip} ?)` : "" }`; } diff --git a/cli/index.js b/cli/index.js index 9d867f4f..13e85d19 100644 --- a/cli/index.js +++ b/cli/index.js @@ -1,9 +1,9 @@ -const _ = require('lodash'); -const { reservedOptions, root_command } = require('./constants'); -const { processOption } = require('./process-option'); -const { execute } = require('./execute'); -const { displayHelp } = require('./operations/display-help'); -const { displayVersion } = require('./operations/display-version'); +const _ = require("lodash"); +const { reservedOptions, root_command } = require("./constants"); +const { processOption } = require("./process-option"); +const { execute } = require("./execute"); +const { displayHelp } = require("./operations/display-help"); +const { displayVersion } = require("./operations/display-version"); const cli = (input) => { const commands = {}; @@ -11,15 +11,15 @@ const cli = (input) => { const addCommand = (command, { addVersion = false, addHelp = true } = {}) => { commands[command.name] = { name: command.name, - description: `${command.description || ''}`, + description: `${command.description || ""}`, options: _.compact(_.map(command.options, processOption)), }; if (addVersion) { commands[command.name].options.unshift( processOption({ - flags: '-v, --version', - description: 'output the current version', + flags: "-v, --version", + description: "output the current version", operation: () => displayVersion(instance), }), ); @@ -28,8 +28,8 @@ const cli = (input) => { if (addHelp) { commands[command.name].options.push( processOption({ - flags: '-h, --help', - description: 'display help for command', + flags: "-h, --help", + description: "display help for command", operation: () => displayHelp(commands, instance, commands[command.name]), }), @@ -63,7 +63,7 @@ const cli = (input) => { if (!processed) return; if (reservedOptions.includes(processed.name)) { - console.warn('reserved option', processed.name); + console.warn("reserved option", processed.name); return; } @@ -72,16 +72,16 @@ const cli = (input) => { commands[root_command].options.unshift( processOption({ - flags: '-v, --version', - description: 'output the current version', + flags: "-v, --version", + description: "output the current version", operation: () => displayVersion(instance), }), ); commands[root_command].options.push( processOption({ - flags: '-h, --help', - description: 'display help for command', + flags: "-h, --help", + description: "display help for command", operation: () => displayHelp(commands, instance, commands[root_command]), }), ); diff --git a/cli/operations/display-help.js b/cli/operations/display-help.js index c1267908..149209ea 100644 --- a/cli/operations/display-help.js +++ b/cli/operations/display-help.js @@ -1,18 +1,18 @@ -const _ = require('lodash'); -const { root_command } = require('../constants'); +const _ = require("lodash"); +const { root_command } = require("../constants"); const generateOptionsOutput = (options) => options.reduce( (acc, option) => { - const flags = `${option.flags.keys.join(', ')}${ - option.flags.value?.raw ? ` ${option.flags.value?.raw}` : '' + const flags = `${option.flags.keys.join(", ")}${ + option.flags.value?.raw ? ` ${option.flags.value?.raw}` : "" }`; - const description = `${option.description || ''}${ + const description = `${option.description || ""}${ option.default === undefined || (option.flags.isNoFlag && option.default === true) - ? '' + ? "" : ` (default: ${ - typeof option.default === 'string' + typeof option.default === "string" ? `"${option.default}"` : option.default })` @@ -37,10 +37,10 @@ const generateOptionsOutput = (options) => 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'); + 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 + @@ -52,10 +52,10 @@ const generateOptionsTextOutput = (options, maxLength, spaces) => return `\n${leftStrFiller}${line}`; }) - .join('') + .join("") ); }) - .join('\n'); + .join("\n"); const displayAllHelp = (commands, instance) => { const { options, maxLength: maxOptionLength } = generateOptionsOutput( @@ -68,7 +68,7 @@ const displayAllHelp = (commands, instance) => { ).reduce( (acc, command) => { const options = generateOptionsOutput(command.options); - const name = `${command.name}${options.length ? ' [options]' : ''}`; + const name = `${command.name}${options.length ? " [options]" : ""}`; const description = command.description; const maxLength = Math.max(name.length, options.maxLength); @@ -95,10 +95,10 @@ const displayAllHelp = (commands, instance) => { .map((commandLabel) => { const leftStr = ` ${commandLabel.name.padEnd( maxCommandLength, - ' ', + " ", )} `; - const leftStrFiller = Array(leftStr.length).fill(' ').join(''); - const descriptionLines = commandLabel.description.split('\n'); + const leftStrFiller = Array(leftStr.length).fill(" ").join(""); + const descriptionLines = commandLabel.description.split("\n"); const optionsTextOutput = generateOptionsTextOutput( commandLabel.options.options, maxCommandLength, @@ -115,11 +115,11 @@ const displayAllHelp = (commands, instance) => { return `\n${leftStrFiller}${line}`; }) - .join('') + - (optionsTextOutput.length ? `\n${optionsTextOutput}` : '') + .join("") + + (optionsTextOutput.length ? `\n${optionsTextOutput}` : "") ); }) - .join('\n'); + .join("\n"); const outputTest = [ optionsOutput && @@ -130,12 +130,12 @@ ${optionsOutput}`, ${commandsOutput}`, ] .filter(Boolean) - .join('\n\n'); + .join("\n\n"); console.log(`Usage: ${[instance.input.name, instance.input.alias] .filter(Boolean) - .join('|')}${optionsOutput ? ' [options]' : ''}${ - commandsOutput ? ' [command]' : '' + .join("|")}${optionsOutput ? " [options]" : ""}${ + commandsOutput ? " [command]" : "" } ${ instance.input.description && @@ -160,10 +160,10 @@ const displayHelp = (commands, instance, command) => { ${optionsOutput}`, ] .filter(Boolean) - .join('\n\n'); + .join("\n\n"); console.log(`Usage: ${instance.input.name} ${command.name}${ - optionsOutput ? ' [options]' : '' + optionsOutput ? " [options]" : "" } ${ command.description && diff --git a/cli/parse-args.js b/cli/parse-args.js index 4f961d6f..b99f14fc 100644 --- a/cli/parse-args.js +++ b/cli/parse-args.js @@ -1,18 +1,18 @@ const parseArgs = (args, type) => { if (args == null || !Array.isArray(args)) { - throw 'args should be array'; + throw "args should be array"; } const argsCopy = args.slice(); switch (type) { - case 'electron': { + case "electron": { if (process.defaultApp) { return argsCopy.slice(2); } return argsCopy.slice(1); } - case 'user': { + case "user": { return argsCopy; } default: { diff --git a/cli/process-option.js b/cli/process-option.js index 7a96d5f7..750ee67f 100644 --- a/cli/process-option.js +++ b/cli/process-option.js @@ -1,4 +1,4 @@ -const _ = require('lodash'); +const _ = require("lodash"); const optionFormatters = { number: (str) => +str, @@ -13,16 +13,16 @@ const processFlags = (flags) => { let name = null; const keys = []; let value = null; - const isNoFlag = flags.includes('--no-'); + const isNoFlag = flags.includes("--no-"); - _.compact(_.split(flags, ' ').map((str) => str.replace(/,/g, ''))).forEach( + _.compact(_.split(flags, " ").map((str) => str.replace(/,/g, ""))).forEach( (str) => { - if (str.startsWith('-')) { + if (str.startsWith("-")) { keys.push(str); } else if (value === null) { - if (str.startsWith('{') || str.startsWith('[') || str.startsWith('<')) { - const rawValue = str.replace(/[{[<>}\].]/g, ''); - const variadic = str.includes('...'); + if (str.startsWith("{") || str.startsWith("[") || str.startsWith("<")) { + const rawValue = str.replace(/[{[<>}\].]/g, ""); + const variadic = str.includes("..."); value = { raw: str, variadic, @@ -38,9 +38,9 @@ const processFlags = (flags) => { if (!_.isEmpty(longestKey)) { name = _.camelCase( - (isNoFlag ? longestKey.replace('--no-', '') : longestKey).replace( + (isNoFlag ? longestKey.replace("--no-", "") : longestKey).replace( /(--?)/, - '', + "", ), ); } @@ -58,13 +58,13 @@ const processOption = (option) => { const processedFlags = processFlags(option.flags); if (!processedFlags.name) { - console.warn('invalid option', option); + console.warn("invalid option", option); return null; } return { required: !!option.required, - description: `${option.description || ''}`, + description: `${option.description || ""}`, default: option.default, flags: processedFlags, operation: option.operation, diff --git a/index.d.ts b/index.d.ts index 9f063a38..ed8b5164 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,4 +1,4 @@ -import {MonoSchemaParser} from "./src/schema-parser/mono-schema-parser"; +import type { MonoSchemaParser } from "./src/schema-parser/mono-schema-parser"; type HttpClientType = "axios" | "fetch"; @@ -145,7 +145,9 @@ interface GenerateApiParamsBase { */ addReadonly?: boolean; - primitiveTypeConstructs?: (struct: PrimitiveTypeStruct) => Partial; + primitiveTypeConstructs?: ( + struct: PrimitiveTypeStruct, + ) => Partial; codeGenConstructs?: (struct: CodeGenConstruct) => Partial; @@ -213,17 +215,17 @@ interface GenerateApiParamsBase { /** fallback name for specific arg name resolver */ specificArgNameResolverName?: string; schemaParsers?: { - complexOneOf?:MonoSchemaParser; - complexAllOf?:MonoSchemaParser; - complexAnyOf?:MonoSchemaParser; - complexNot?:MonoSchemaParser; - enum?:MonoSchemaParser; - object?:MonoSchemaParser; - complex?:MonoSchemaParser; - primitive?:MonoSchemaParser; - discriminator?:MonoSchemaParser; + complexOneOf?: MonoSchemaParser; + complexAllOf?: MonoSchemaParser; + complexAnyOf?: MonoSchemaParser; + complexNot?: MonoSchemaParser; + enum?: MonoSchemaParser; + object?: MonoSchemaParser; + complex?: MonoSchemaParser; + primitive?: MonoSchemaParser; + discriminator?: MonoSchemaParser; array?: MonoSchemaParser; - } + }; } type CodeGenConstruct = { @@ -270,11 +272,18 @@ type CodeGenConstruct = { type PrimitiveTypeStructValue = | string - | ((schema: Record, parser: import("./src/schema-parser/schema-parser").SchemaParser) => string); + | (( + schema: Record, + parser: import("./src/schema-parser/schema-parser").SchemaParser, + ) => string); type PrimitiveTypeStruct = Record< "integer" | "number" | "boolean" | "object" | "file" | "string" | "array", - string | ({ $default: PrimitiveTypeStructValue } & Record) + | string + | ({ $default: PrimitiveTypeStructValue } & Record< + string, + PrimitiveTypeStructValue + >) >; interface GenerateApiParamsFromPath extends GenerateApiParamsBase { @@ -298,7 +307,10 @@ interface GenerateApiParamsFromSpecLiteral extends GenerateApiParamsBase { spec: import("swagger-schema-official").Spec; } -export type GenerateApiParams = GenerateApiParamsFromPath | GenerateApiParamsFromUrl | GenerateApiParamsFromSpecLiteral; +export type GenerateApiParams = + | GenerateApiParamsFromPath + | GenerateApiParamsFromUrl + | GenerateApiParamsFromSpecLiteral; type BuildRouteParam = { /** {bar} */ @@ -328,11 +340,20 @@ export interface Hooks { /** calls after parse\process route path */ onBuildRoutePath: (data: BuildRoutePath) => BuildRoutePath | void; /** calls before insert path param name into string path interpolation */ - onInsertPathParam: (paramName: string, index: number, arr: BuildRouteParam[], resultRoute: string) => string | void; + onInsertPathParam: ( + paramName: string, + index: number, + arr: BuildRouteParam[], + resultRoute: string, + ) => string | void; /** calls after parse schema component */ onCreateComponent: (component: SchemaComponent) => SchemaComponent | void; /** calls before parse any kind of schema */ - onPreParseSchema: (originalSchema: any, typeName: string, schemaType: string) => any; + onPreParseSchema: ( + originalSchema: any, + typeName: string, + schemaType: string, + ) => any; /** calls after parse any kind of schema */ onParseSchema: (originalSchema: any, parsedSchema: any) => any | void; /** calls after parse route (return type: customized route (ParsedRoute), nothing change (void), false (ignore this route)) */ @@ -343,18 +364,32 @@ export interface Hooks { codeGenProcess: import("./src/code-gen-process").CodeGenProcess, ) => C | void; /** customize configuration object before sending it to ETA templates */ - onPrepareConfig?: (currentConfiguration: C) => C | void; + onPrepareConfig?: ( + currentConfiguration: C, + ) => C | void; /** customize route name as you need */ - onCreateRouteName?: (routeNameInfo: RouteNameInfo, rawRouteInfo: RawRouteInfo) => RouteNameInfo | void; + onCreateRouteName?: ( + routeNameInfo: RouteNameInfo, + rawRouteInfo: RawRouteInfo, + ) => RouteNameInfo | void; /** customize request params (path params, query params) */ - onCreateRequestParams?: (rawType: SchemaComponent["rawTypeData"]) => SchemaComponent["rawTypeData"] | void; + onCreateRequestParams?: ( + rawType: SchemaComponent["rawTypeData"], + ) => SchemaComponent["rawTypeData"] | void; /** customize name of model type */ - onFormatTypeName?: (typeName: string, rawTypeName?: string, schemaType?: "type-name" | "enum-key") => string | void; + onFormatTypeName?: ( + typeName: string, + rawTypeName?: string, + schemaType?: "type-name" | "enum-key", + ) => string | void; /** customize name of route (operationId), you can do it with using onCreateRouteName too */ - onFormatRouteName?: (routeInfo: RawRouteInfo, templateRouteName: string) => string | void; + onFormatRouteName?: ( + routeInfo: RawRouteInfo, + templateRouteName: string, + ) => string | void; } -export interface RouteNameRouteInfo {} +export type RouteNameRouteInfo = {}; export type RouteNameInfo = { usage: string; @@ -424,10 +459,16 @@ export interface SchemaComponent { discriminator?: { propertyName?: string; }; - $parsed: ParsedSchema; + $parsed: ParsedSchema< + | SchemaTypeObjectContent + | SchemaTypeEnumContent + | SchemaTypePrimitiveContent + >; }; componentName: "schemas" | "paths"; - typeData: ParsedSchema | null; + typeData: ParsedSchema< + SchemaTypeObjectContent | SchemaTypeEnumContent | SchemaTypePrimitiveContent + > | null; } export enum RequestContentKind { @@ -495,7 +536,10 @@ export enum SCHEMA_TYPES { COMPLEX_UNKNOWN = "__unknown", } -type MAIN_SCHEMA_TYPES = SCHEMA_TYPES.PRIMITIVE | SCHEMA_TYPES.OBJECT | SCHEMA_TYPES.ENUM; +type MAIN_SCHEMA_TYPES = + | SCHEMA_TYPES.PRIMITIVE + | SCHEMA_TYPES.OBJECT + | SCHEMA_TYPES.ENUM; type ExtractingOptions = { requestBodySuffix: string[]; @@ -505,13 +549,31 @@ type ExtractingOptions = { enumSuffix: string[]; discriminatorMappingSuffix: string[]; discriminatorAbstractPrefix: string[]; - requestBodyNameResolver: (name: string, reservedNames: string) => string | undefined; - responseBodyNameResolver: (name: string, reservedNames: string) => string | undefined; - responseErrorNameResolver: (name: string, reservedNames: string) => string | undefined; - requestParamsNameResolver: (name: string, reservedNames: string) => string | undefined; + requestBodyNameResolver: ( + name: string, + reservedNames: string, + ) => string | undefined; + responseBodyNameResolver: ( + name: string, + reservedNames: string, + ) => string | undefined; + responseErrorNameResolver: ( + name: string, + reservedNames: string, + ) => string | undefined; + requestParamsNameResolver: ( + name: string, + reservedNames: string, + ) => string | undefined; enumNameResolver: (name: string, reservedNames: string) => string | undefined; - discriminatorMappingNameResolver: (name: string, reservedNames: string) => string | undefined; - discriminatorAbstractResolver: (name: string, reservedNames: string) => string | undefined; + discriminatorMappingNameResolver: ( + name: string, + reservedNames: string, + ) => string | undefined; + discriminatorAbstractResolver: ( + name: string, + reservedNames: string, + ) => string | undefined; }; export interface GenerateApiConfiguration { @@ -588,7 +650,9 @@ export interface GenerateApiConfiguration { typeNameResolverName: string; specificArgNameResolverName: string; /** do not use constructor args, it can break functionality of this property, just send class reference */ - customTranslator?: new (...args: never[]) => typeof import("./src/translators/translator").Translator; + customTranslator?: new ( + ...args: never[] + ) => typeof import("./src/translators/translator").Translator; internalTemplateOptions: { addUtilRequiredKeysType: boolean; }; @@ -635,16 +699,28 @@ export interface GenerateApiConfiguration { /** @deprecated */ classNameCase: (value: string) => string; pascalCase: (value: string) => string; - getInlineParseContent: (rawTypeData: SchemaComponent["rawTypeData"], typeName?: string) => string; - getParseContent: (rawTypeData: SchemaComponent["rawTypeData"], typeName?: string) => ModelType; + getInlineParseContent: ( + rawTypeData: SchemaComponent["rawTypeData"], + typeName?: string, + ) => string; + getParseContent: ( + rawTypeData: SchemaComponent["rawTypeData"], + typeName?: string, + ) => ModelType; getComponentByRef: (ref: string) => SchemaComponent; parseSchema: ( rawSchema: string | SchemaComponent["rawTypeData"], typeName?: string, formattersMap?: Record string>, ) => ModelType; - formatters: Record string>; - inlineExtraFormatters: Record, (schema: ModelType) => string>; + formatters: Record< + MAIN_SCHEMA_TYPES, + (content: string | object | string[] | object[]) => string + >; + inlineExtraFormatters: Record< + Exclude, + (schema: ModelType) => string + >; formatModelName: (name: string) => string; fmtToJSDocLine: (line: string, params?: { eol?: boolean }) => string; _: import("lodash").LoDashStatic; @@ -664,17 +740,28 @@ type FileInfo = { export interface GenerateApiOutput { configuration: GenerateApiConfiguration; files: FileInfo[]; - createFile: (params: { path: string; fileName: string; content: string; withPrefix?: boolean }) => void; + createFile: (params: { + path: string; + fileName: string; + content: string; + withPrefix?: boolean; + }) => void; renderTemplate: ( templateContent: string, data: Record, etaOptions?: import("eta/dist/types/config").PartialConfig, ) => string; - getTemplate: (params: { fileName?: string; name?: string; path?: string }) => string; + getTemplate: (params: { + fileName?: string; + name?: string; + path?: string; + }) => string; formatTSContent: (content: string) => Promise; } -export declare function generateApi(params: GenerateApiParams): Promise; +export declare function generateApi( + params: GenerateApiParams, +): Promise; export interface GenerateTemplatesParams { cleanOutput?: boolean; @@ -684,6 +771,9 @@ export interface GenerateTemplatesParams { silent?: boolean; } -export interface GenerateTemplatesOutput extends Pick {} +export interface GenerateTemplatesOutput + extends Pick {} -export declare function generateTemplates(params: GenerateTemplatesParams): Promise; +export declare function generateTemplates( + params: GenerateTemplatesParams, +): Promise; diff --git a/index.js b/index.js index 229639ea..042182ff 100755 --- a/index.js +++ b/index.js @@ -10,7 +10,7 @@ const { version, name } = require("./package.json"); const { cli } = require("./cli"); const { generateApi, generateTemplates } = require("./src"); const { HTTP_CLIENT } = require("./src/constants"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const { CodeGenConfig } = require("./src/configuration"); const { TemplatesGenConfig, diff --git a/scripts_runner.js b/scripts_runner.js index b9bd3b9b..22ec34e1 100644 --- a/scripts_runner.js +++ b/scripts_runner.js @@ -1,5 +1,5 @@ -const packageJson = require('./package.json'); -const { spawn } = require('child_process'); +const packageJson = require("./package.json"); +const { spawn } = require("node:child_process"); const commands = process.argv.slice(2); @@ -8,25 +8,25 @@ const packageScripts = Object.keys(packageJson.scripts); const execute = (scriptName) => new Promise((resolve, reject) => { console.log(`yarn ${scriptName}`); - const spawned = spawn('yarn', [scriptName]); + const spawned = spawn("yarn", [scriptName]); - spawned.stdout.on('data', (data) => { + spawned.stdout.on("data", (data) => { process.stdout.write(data); }); - spawned.stderr.on('data', (data) => { + spawned.stderr.on("data", (data) => { process.stderr.write(data); }); - spawned.on('error', (error) => { + spawned.on("error", (error) => { console.error(error); }); - spawned.on('message', (message) => { + spawned.on("message", (message) => { console.log(message); }); - spawned.on('close', (code) => { + spawned.on("close", (code) => { if (code) { reject(code); } else { @@ -43,8 +43,8 @@ const run = async () => { await execute(scriptName); } - if (command.includes('*')) { - const commandPart = command.replace('*', ''); + if (command.includes("*")) { + const commandPart = command.replace("*", ""); // TODO: refactor if ( scriptName.startsWith(commandPart) || diff --git a/src/code-formatter.js b/src/code-formatter.js index a9bfa88e..90141fba 100644 --- a/src/code-formatter.js +++ b/src/code-formatter.js @@ -1,6 +1,6 @@ -const _ = require('lodash'); -const ts = require('typescript'); -const prettier = require('prettier'); +const _ = require("lodash"); +const ts = require("typescript"); +const prettier = require("prettier"); class CodeFormatter { /** @@ -13,13 +13,13 @@ class CodeFormatter { } removeUnusedImports = (content) => { - const tempFileName = 'file.ts'; + const tempFileName = "file.ts"; const host = new TsLanguageServiceHost(tempFileName, content); const languageService = ts.createLanguageService(host); const fileTextChanges = languageService.organizeImports( - { type: 'file', fileName: tempFileName }, + { type: "file", fileName: tempFileName }, { newLineCharacter: ts.sys.newLine }, )[0]; @@ -79,7 +79,7 @@ class TsLanguageServiceHost { } getNewLine() { - return 'newLine' in ts.sys ? ts.sys.newLine : '\n'; + return "newLine" in ts.sys ? ts.sys.newLine : "\n"; } getScriptFileNames() { return [this.fileName]; diff --git a/src/code-gen-process.js b/src/code-gen-process.js index 22d12b49..0c352497 100644 --- a/src/code-gen-process.js +++ b/src/code-gen-process.js @@ -1,32 +1,32 @@ -const { SwaggerSchemaResolver } = require('./swagger-schema-resolver.js'); -const { SchemaComponentsMap } = require('./schema-components-map.js'); -const { NameResolver } = require('./util/name-resolver'); -const { Logger } = require('./util/logger.js'); -const { TypeNameFormatter } = require('./type-name-formatter.js'); -const _ = require('lodash'); -const { SchemaParserFabric } = require('./schema-parser/schema-parser-fabric'); -const { SchemaRoutes } = require('./schema-routes/schema-routes.js'); -const { CodeGenConfig } = require('./configuration.js'); -const { SchemaWalker } = require('./schema-walker'); -const { FileSystem } = require('./util/file-system'); -const { TemplatesWorker } = require('./templates-worker'); -const { JavascriptTranslator } = require('./translators/javascript'); -const ts = require('typescript'); -const { CodeFormatter } = require('./code-formatter'); -const { pascalCase } = require('./util/pascal-case'); -const { internalCase } = require('./util/internal-case'); -const { sortByProperty } = require('./util/sort-by-property'); +const { SwaggerSchemaResolver } = require("./swagger-schema-resolver.js"); +const { SchemaComponentsMap } = require("./schema-components-map.js"); +const { NameResolver } = require("./util/name-resolver"); +const { Logger } = require("./util/logger.js"); +const { TypeNameFormatter } = require("./type-name-formatter.js"); +const _ = require("lodash"); +const { SchemaParserFabric } = require("./schema-parser/schema-parser-fabric"); +const { SchemaRoutes } = require("./schema-routes/schema-routes.js"); +const { CodeGenConfig } = require("./configuration.js"); +const { SchemaWalker } = require("./schema-walker"); +const { FileSystem } = require("./util/file-system"); +const { TemplatesWorker } = require("./templates-worker"); +const { JavascriptTranslator } = require("./translators/javascript"); +const ts = require("typescript"); +const { CodeFormatter } = require("./code-formatter"); +const { pascalCase } = require("./util/pascal-case"); +const { internalCase } = require("./util/internal-case"); +const { sortByProperty } = require("./util/sort-by-property"); const PATCHABLE_INSTANCES = [ - 'schemaWalker', - 'swaggerSchemaResolver', - 'schemaComponentsMap', - 'typeNameFormatter', - 'templatesWorker', - 'codeFormatter', - 'schemaParserFabric', - 'schemaRoutes', - 'javascriptTranslator', + "schemaWalker", + "swaggerSchemaResolver", + "schemaComponentsMap", + "typeNameFormatter", + "templatesWorker", + "codeFormatter", + "schemaParserFabric", + "schemaRoutes", + "javascriptTranslator", ]; class CodeGenProcess { @@ -92,10 +92,10 @@ class CodeGenProcess { originalSchema: swagger.originalSchema, }); - this.schemaWalker.addSchema('$usage', swagger.usageSchema); - this.schemaWalker.addSchema('$original', swagger.originalSchema); + this.schemaWalker.addSchema("$usage", swagger.usageSchema); + this.schemaWalker.addSchema("$original", swagger.originalSchema); - this.logger.event('start generating your typescript api'); + this.logger.event("start generating your typescript api"); this.config.update( this.config.hooks.onInit(this.config, this) || this.config, @@ -107,7 +107,7 @@ class CodeGenProcess { _.each(component, (rawTypeData, typeName) => { this.schemaComponentsMap.createComponent( this.schemaComponentsMap.createRef([ - 'components', + "components", componentName, typeName, ]), @@ -120,7 +120,7 @@ class CodeGenProcess { * @type {SchemaComponent[]} */ const componentsToParse = this.schemaComponentsMap.filter( - _.compact(['schemas', this.config.extractResponses && 'responses']), + _.compact(["schemas", this.config.extractResponses && "responses"]), ); const parsedSchemas = componentsToParse.map((schemaComponent) => { @@ -186,7 +186,7 @@ class CodeGenProcess { }); this.logger.success( - `api file`, + "api file", `"${file.fileName}${file.fileExtension}"`, `created in ${this.config.output}`, ); @@ -225,7 +225,7 @@ class CodeGenProcess { formatters: this.schemaParserFabric.schemaFormatters.base, formatModelName: this.typeNameFormatter.format, fmtToJSDocLine: function fmtToJSDocLine(line, { eol = true }) { - return ` * ${line}${eol ? '\n' : ''}`; + return ` * ${line}${eol ? "\n" : ""}`; }, NameResolver: NameResolver, _, @@ -240,8 +240,8 @@ class CodeGenProcess { let modelTypes = []; const modelTypeComponents = _.compact([ - 'schemas', - this.config.extractResponses && 'responses', + "schemas", + this.config.extractResponses && "responses", ]); const getSchemaComponentsCount = () => @@ -266,7 +266,7 @@ class CodeGenProcess { } if (this.config.sortTypes) { - return modelTypes.sort(sortByProperty('name')); + return modelTypes.sort(sortByProperty("name")); } return modelTypes; @@ -487,7 +487,7 @@ class CodeGenProcess { templatesToRender.api, configuration, ), - ]).join('\n'), + ]).join("\n"), ); }; @@ -503,7 +503,7 @@ class CodeGenProcess { const fileExtension = ts.Extension.Ts; if (configuration.translateToJavaScript) { - this.logger.debug('using js translator for', fileName); + this.logger.debug("using js translator for", fileName); return await this.javascriptTranslator.translate({ fileName: fileName, fileExtension: fileExtension, @@ -512,7 +512,7 @@ class CodeGenProcess { } if (configuration.customTranslator) { - this.logger.debug('using custom translator for', fileName); + this.logger.debug("using custom translator for", fileName); return await configuration.customTranslator.translate({ fileName: fileName, fileExtension: fileExtension, @@ -520,7 +520,7 @@ class CodeGenProcess { }); } - this.logger.debug('generating output for', `${fileName}${fileExtension}`); + this.logger.debug("generating output for", `${fileName}${fileExtension}`); return [ { @@ -533,8 +533,8 @@ class CodeGenProcess { createApiConfig = (swaggerSchema) => { const { info, servers, host, basePath, externalDocs, tags } = swaggerSchema; - const server = (servers && servers[0]) || { url: '' }; - const { title = 'No title', version } = info || {}; + const server = (servers && servers[0]) || { url: "" }; + const { title = "No title", version } = info || {}; const { url: serverUrl } = server; return { @@ -544,8 +544,8 @@ class CodeGenProcess { host, externalDocs: _.merge( { - url: '', - description: '', + url: "", + description: "", }, externalDocs, ), diff --git a/src/commands/generate-templates/configuration.js b/src/commands/generate-templates/configuration.js index e9aaabc0..dd1529c2 100644 --- a/src/commands/generate-templates/configuration.js +++ b/src/commands/generate-templates/configuration.js @@ -1,5 +1,5 @@ -const { objectAssign } = require('../../util/object-assign'); -const { HTTP_CLIENT, PROJECT_VERSION } = require('../../constants'); +const { objectAssign } = require("../../util/object-assign"); +const { HTTP_CLIENT, PROJECT_VERSION } = require("../../constants"); /** * @type {GenerateTemplatesParams}} diff --git a/src/commands/generate-templates/index.js b/src/commands/generate-templates/index.js index 2abc69cf..d32283b1 100644 --- a/src/commands/generate-templates/index.js +++ b/src/commands/generate-templates/index.js @@ -6,7 +6,7 @@ // License text available at https://opensource.org/licenses/MIT // Repository https://github.com/acacode/swagger-typescript-api -const { TemplatesGenProcess } = require('./templates-gen-process'); +const { TemplatesGenProcess } = require("./templates-gen-process"); module.exports = { generateTemplates: async (config) => { diff --git a/src/commands/generate-templates/templates-gen-process.js b/src/commands/generate-templates/templates-gen-process.js index 186e1420..15ba87f3 100644 --- a/src/commands/generate-templates/templates-gen-process.js +++ b/src/commands/generate-templates/templates-gen-process.js @@ -1,7 +1,7 @@ -const { TemplatesGenConfig } = require('./configuration'); -const { FileSystem } = require('../../util/file-system'); -const { Logger } = require('../../util/logger'); -const path = require('path'); +const { TemplatesGenConfig } = require("./configuration"); +const { FileSystem } = require("../../util/file-system"); +const { Logger } = require("../../util/logger"); +const path = require("node:path"); class TemplatesGenProcess { /** @@ -17,16 +17,16 @@ class TemplatesGenProcess { */ logger; - rootDir = path.resolve(__dirname, '../../../'); + rootDir = path.resolve(__dirname, "../../../"); paths = { - baseTemplates: 'templates/base', - httpClientTemplates: 'templates/base/http-clients', - moduleApiTemplates: 'templates/modular', - defaultApiTemplates: 'templates/default', + baseTemplates: "templates/base", + httpClientTemplates: "templates/base/http-clients", + moduleApiTemplates: "templates/modular", + defaultApiTemplates: "templates/default", }; - importTemplatePrefixes = ['@base', '@modular', '@default']; + importTemplatePrefixes = ["@base", "@modular", "@default"]; constructor(config) { this.config = new TemplatesGenConfig(config); @@ -45,7 +45,7 @@ class TemplatesGenProcess { const templates = this.getTemplates(); if (this.config.output) { - this.logger.log('preparing output directory for source templates'); + this.logger.log("preparing output directory for source templates"); const outputPath = path.resolve(process.cwd(), this.config.output); if (this.fileSystem.pathIsExist(outputPath)) { @@ -122,7 +122,7 @@ class TemplatesGenProcess { template.startsWith(`${this.config.httpClientType}-`), ); - let httpClientTemplateContent = ''; + let httpClientTemplateContent = ""; if (usingHttpClientTemplate) { httpClientTemplateContent = this.fixTemplateContent( @@ -134,7 +134,7 @@ class TemplatesGenProcess { for (const fileName of baseTemplates) { const templateContent = - (fileName === 'http-client.ejs' && httpClientTemplateContent) || + (fileName === "http-client.ejs" && httpClientTemplateContent) || this.fixTemplateContent( this.getTemplateContent(`${this.paths.baseTemplates}/${fileName}`), ); @@ -162,34 +162,34 @@ class TemplatesGenProcess { const importsRegExp1 = new RegExp( `includeFile\\("(${this.importTemplatePrefixes .map((v) => `(${v})`) - .join('|')})/`, - 'g', + .join("|")})/`, + "g", ); // includeFile(`@base/ const importsRegExp2 = new RegExp( `includeFile\\(\`(${this.importTemplatePrefixes .map((v) => `(${v})`) - .join('|')})/`, - 'g', + .join("|")})/`, + "g", ); // includeFile('@base/ const importsRegExp3 = new RegExp( `includeFile\\('(${this.importTemplatePrefixes .map((v) => `(${v})`) - .join('|')})/`, - 'g', + .join("|")})/`, + "g", ); return content .replace(importsRegExp1, 'includeFile("./') - .replace(importsRegExp2, 'includeFile(`./') + .replace(importsRegExp2, "includeFile(`./") .replace(importsRegExp3, "includeFile('./"); }; getTemplateNamesFromDir = (dir) => { return this.fileSystem .readDir(path.resolve(this.rootDir, dir)) - .filter((file) => file.endsWith('.ejs')); + .filter((file) => file.endsWith(".ejs")); }; getTemplateContent = (pathToFile) => { diff --git a/src/component-type-name-resolver.js b/src/component-type-name-resolver.js index 1d64b885..63dde60d 100644 --- a/src/component-type-name-resolver.js +++ b/src/component-type-name-resolver.js @@ -1,5 +1,5 @@ -const { getRandomInt } = require('./util/random'); -const { NameResolver } = require('./util/name-resolver'); +const { getRandomInt } = require("./util/random"); +const { NameResolver } = require("./util/name-resolver"); class ComponentTypeNameResolver extends NameResolver { counter = 1; @@ -22,7 +22,7 @@ class ComponentTypeNameResolver extends NameResolver { this.countersByVariant.set(randomVariant, variantCounter); const dirtyResolvedName = `${randomVariant}${variantCounter}`; this.logger.debug( - 'generated dirty resolved type name for component - ', + "generated dirty resolved type name for component - ", dirtyResolvedName, ); return dirtyResolvedName; @@ -31,7 +31,7 @@ class ComponentTypeNameResolver extends NameResolver { const fallbackName = `${this.config.componentTypeNameResolver}${this .fallbackNameCounter++}`; this.logger.debug( - 'generated fallback type name for component - ', + "generated fallback type name for component - ", fallbackName, ); return fallbackName; diff --git a/src/configuration.js b/src/configuration.js index 10e52905..5d238884 100644 --- a/src/configuration.js +++ b/src/configuration.js @@ -1,34 +1,34 @@ /* eslint-disable no-unused-vars */ -const { objectAssign } = require('./util/object-assign'); -const _ = require('lodash'); -const CONSTANTS = require('./constants'); -const { ComponentTypeNameResolver } = require('./component-type-name-resolver'); -const { cosmiconfigSync } = require('cosmiconfig'); -const ts = require('typescript'); +const { objectAssign } = require("./util/object-assign"); +const _ = require("lodash"); +const CONSTANTS = require("./constants"); +const { ComponentTypeNameResolver } = require("./component-type-name-resolver"); +const { cosmiconfigSync } = require("cosmiconfig"); +const ts = require("typescript"); const TsKeyword = { - Number: 'number', - String: 'string', - Boolean: 'boolean', - Any: 'any', - Void: 'void', - Unknown: 'unknown', - Null: 'null', - Undefined: 'undefined', - Object: 'object', - File: 'File', - Date: 'Date', - Type: 'type', - Enum: 'enum', - Interface: 'interface', - Array: 'Array', - Record: 'Record', - Intersection: '&', - Union: '|', + Number: "number", + String: "string", + Boolean: "boolean", + Any: "any", + Void: "void", + Unknown: "unknown", + Null: "null", + Undefined: "undefined", + Object: "object", + File: "File", + Date: "Date", + Type: "type", + Enum: "enum", + Interface: "interface", + Array: "Array", + Record: "Record", + Intersection: "&", + Union: "|", }; const TsCodeGenKeyword = { - UtilRequiredKeys: 'UtilRequiredKeys', + UtilRequiredKeys: "UtilRequiredKeys", }; /** @@ -37,7 +37,7 @@ const TsCodeGenKeyword = { class CodeGenConfig { version = CONSTANTS.PROJECT_VERSION; /** CLI flag */ - templates = ''; + templates = ""; /** CLI flag */ generateResponses = false; /** CLI flag */ @@ -77,10 +77,10 @@ class CodeGenConfig { extractResponses = false; extractEnums = false; fileNames = { - dataContracts: 'data-contracts', - routeTypes: 'route-types', - httpClient: 'http-client', - outOfModuleApi: 'Common', + dataContracts: "data-contracts", + routeTypes: "route-types", + httpClient: "http-client", + outOfModuleApi: "Common", }; routeNameDuplicatesMap = new Map(); prettierOptions = { ...CONSTANTS.PRETTIER_OPTIONS }; @@ -108,28 +108,28 @@ class CodeGenConfig { sortRoutes = false; templatePaths = { /** `templates/base` */ - base: '', + base: "", /** `templates/default` */ - default: '', + default: "", /** `templates/modular` */ - modular: '', + modular: "", /** usage path if `--templates` option is not set */ - original: '', + original: "", /** custom path to templates (`--templates`) */ - custom: '', + custom: "", }; /** Record */ templatesToRender = { - api: '', - dataContracts: '', - dataContractJsDoc: '', - interfaceDataContract: '', - typeDataContract: '', - enumDataContract: '', - objectFieldJsDoc: '', - httpClient: '', - routeTypes: '', - routeName: '', + api: "", + dataContracts: "", + dataContractJsDoc: "", + interfaceDataContract: "", + typeDataContract: "", + enumDataContract: "", + objectFieldJsDoc: "", + httpClient: "", + routeTypes: "", + routeName: "", }; /** * @type {Record MonoSchemaParser>} @@ -137,68 +137,68 @@ class CodeGenConfig { schemaParsers = {}; toJS = false; silent = false; - typePrefix = ''; - typeSuffix = ''; - enumKeyPrefix = ''; - enumKeySuffix = ''; + typePrefix = ""; + typeSuffix = ""; + enumKeyPrefix = ""; + enumKeySuffix = ""; patch = false; /** @type {ComponentTypeNameResolver} */ componentTypeNameResolver; /** name of the main exported class */ - apiClassName = 'Api'; + apiClassName = "Api"; debug = false; anotherArrayType = false; internalTemplateOptions = { addUtilRequiredKeysType: false, }; extraTemplates = []; - input = ''; + input = ""; modular = false; - output = ''; - url = ''; + output = ""; + url = ""; cleanOutput = false; spec = null; - fileName = 'Api.ts'; + fileName = "Api.ts"; authorizationToken = void 0; requestOptions = null; jsPrimitiveTypes = []; jsEmptyTypes = []; - fixInvalidTypeNamePrefix = 'Type'; - fixInvalidEnumKeyPrefix = 'Value'; + fixInvalidTypeNamePrefix = "Type"; + fixInvalidEnumKeyPrefix = "Value"; - enumKeyResolverName = 'Value'; - typeNameResolverName = 'ComponentType'; - specificArgNameResolverName = 'arg'; + enumKeyResolverName = "Value"; + typeNameResolverName = "ComponentType"; + specificArgNameResolverName = "arg"; successResponseStatusRange = [200, 299]; /** @type {ExtractingOptions} */ extractingOptions = { - requestBodySuffix: ['Payload', 'Body', 'Input'], - requestParamsSuffix: ['Params'], - responseBodySuffix: ['Data', 'Result', 'Output'], + requestBodySuffix: ["Payload", "Body", "Input"], + requestParamsSuffix: ["Params"], + responseBodySuffix: ["Data", "Result", "Output"], responseErrorSuffix: [ - 'Error', - 'Fail', - 'Fails', - 'ErrorData', - 'HttpError', - 'BadResponse', + "Error", + "Fail", + "Fails", + "ErrorData", + "HttpError", + "BadResponse", ], - enumSuffix: ['Enum'], - discriminatorMappingSuffix: ['Mapping', 'Mapper', 'MapType'], + enumSuffix: ["Enum"], + discriminatorMappingSuffix: ["Mapping", "Mapper", "MapType"], discriminatorAbstractPrefix: [ - 'Base', - 'Abstract', - 'Discriminator', - 'Internal', - 'Polymorph', + "Base", + "Abstract", + "Discriminator", + "Internal", + "Polymorph", ], }; compilerTsConfig = { - module: 'ESNext', + module: "ESNext", noImplicitReturns: true, alwaysStrict: true, target: ts.ScriptTarget.ESNext, @@ -241,7 +241,7 @@ class CodeGenConfig { /** * $A */ - NullValue: (content) => `null`, + NullValue: (content) => "null", /** * $A1 | $A2 */ @@ -250,7 +250,7 @@ class CodeGenConfig { /** * ($A1) */ - ExpressionGroup: (content) => (content ? `(${content})` : ''), + ExpressionGroup: (content) => (content ? `(${content})` : ""), /** * $A1 & $A2 */ @@ -266,12 +266,12 @@ class CodeGenConfig { */ TypeField: ({ readonly, key, optional, value }) => _.compact([ - readonly && 'readonly ', + readonly && "readonly ", key, - optional && '?', - ': ', + optional && "?", + ": ", value, - ]).join(''), + ]).join(""), /** * [key: $A1]: $A2 */ @@ -294,7 +294,7 @@ class CodeGenConfig { _.map( contents, ({ key, value }) => ` ${this.Ts.EnumField(key, value)}`, - ).join(',\n'), + ).join(",\n"), /** * {\n $A \n} */ @@ -306,21 +306,21 @@ class CodeGenConfig { [ ...(contents.length === 1 ? [`/** ${contents[0]} */`] - : ['/**', ...contents.map((content) => ` * ${content}`), ' */']), + : ["/**", ...contents.map((content) => ` * ${content}`), " */"]), ].map((part) => `${formatFn ? formatFn(part) : part}\n`), /** * $A1<...$A2.join(,)> */ TypeWithGeneric: (typeName, genericArgs) => { return `${typeName}${ - genericArgs.length ? `<${genericArgs.join(',')}>` : '' + genericArgs.length ? `<${genericArgs.join(",")}>` : "" }`; }, /** * [$A1, $A2, ...$AN] */ Tuple: (values) => { - return `[${values.join(', ')}]`; + return `[${values.join(", ")}]`; }, }; @@ -341,39 +341,39 @@ class CodeGenConfig { /** formats */ binary: () => this.Ts.Keyword.File, file: () => this.Ts.Keyword.File, - 'date-time': () => this.Ts.Keyword.String, + "date-time": () => this.Ts.Keyword.String, time: () => this.Ts.Keyword.String, date: () => this.Ts.Keyword.String, duration: () => this.Ts.Keyword.String, email: () => this.Ts.Keyword.String, - 'idn-email': () => this.Ts.Keyword.String, - 'idn-hostname': () => this.Ts.Keyword.String, + "idn-email": () => this.Ts.Keyword.String, + "idn-hostname": () => this.Ts.Keyword.String, ipv4: () => this.Ts.Keyword.String, ipv6: () => this.Ts.Keyword.String, uuid: () => this.Ts.Keyword.String, uri: () => this.Ts.Keyword.String, - 'uri-reference': () => this.Ts.Keyword.String, - 'uri-template': () => this.Ts.Keyword.String, - 'json-pointer': () => this.Ts.Keyword.String, - 'relative-json-pointer': () => this.Ts.Keyword.String, + "uri-reference": () => this.Ts.Keyword.String, + "uri-template": () => this.Ts.Keyword.String, + "json-pointer": () => this.Ts.Keyword.String, + "relative-json-pointer": () => this.Ts.Keyword.String, regex: () => this.Ts.Keyword.String, }, }; templateInfos = [ - { name: 'api', fileName: 'api' }, - { name: 'dataContracts', fileName: 'data-contracts' }, - { name: 'dataContractJsDoc', fileName: 'data-contract-jsdoc' }, - { name: 'interfaceDataContract', fileName: 'interface-data-contract' }, - { name: 'typeDataContract', fileName: 'type-data-contract' }, - { name: 'enumDataContract', fileName: 'enum-data-contract' }, - { name: 'objectFieldJsDoc', fileName: 'object-field-jsdoc' }, - { name: 'httpClient', fileName: 'http-client' }, - { name: 'routeTypes', fileName: 'route-types' }, - { name: 'routeName', fileName: 'route-name' }, + { name: "api", fileName: "api" }, + { name: "dataContracts", fileName: "data-contracts" }, + { name: "dataContractJsDoc", fileName: "data-contract-jsdoc" }, + { name: "interfaceDataContract", fileName: "interface-data-contract" }, + { name: "typeDataContract", fileName: "type-data-contract" }, + { name: "enumDataContract", fileName: "enum-data-contract" }, + { name: "objectFieldJsDoc", fileName: "object-field-jsdoc" }, + { name: "httpClient", fileName: "http-client" }, + { name: "routeTypes", fileName: "route-types" }, + { name: "routeName", fileName: "route-name" }, ]; - templateExtensions = ['.eta', '.ejs']; + templateExtensions = [".eta", ".ejs"]; /** * @param config {Partial} @@ -429,12 +429,12 @@ class CodeGenConfig { } const getDefaultPrettierOptions = () => { - const prettier = cosmiconfigSync('prettier').search(); + const prettier = cosmiconfigSync("prettier").search(); if (prettier) { return { ...prettier.config, - parser: 'typescript', + parser: "typescript", }; } diff --git a/src/constants.js b/src/constants.js index 61b55e14..d6916fd5 100644 --- a/src/constants.js +++ b/src/constants.js @@ -1,33 +1,33 @@ -const packageJson = require('../package.json'); -const RESERVED_QUERY_ARG_NAMES = ['query', 'queryParams', 'queryArg']; -const RESERVED_BODY_ARG_NAMES = ['data', 'body', 'reqBody']; +const packageJson = require("../package.json"); +const RESERVED_QUERY_ARG_NAMES = ["query", "queryParams", "queryArg"]; +const RESERVED_BODY_ARG_NAMES = ["data", "body", "reqBody"]; const RESERVED_REQ_PARAMS_ARG_NAMES = [ - 'params', - 'requestParams', - 'reqParams', - 'httpParams', + "params", + "requestParams", + "reqParams", + "httpParams", ]; -const RESERVED_PATH_ARG_NAMES = ['path', 'pathParams']; -const RESERVED_HEADER_ARG_NAMES = ['headers', 'headersParams']; +const RESERVED_PATH_ARG_NAMES = ["path", "pathParams"]; +const RESERVED_HEADER_ARG_NAMES = ["headers", "headersParams"]; const SCHEMA_TYPES = { - ARRAY: 'array', - OBJECT: 'object', - ENUM: 'enum', - REF: '$ref', - PRIMITIVE: 'primitive', - COMPLEX: 'complex', - DISCRIMINATOR: 'discriminator', - COMPLEX_ONE_OF: 'oneOf', - COMPLEX_ANY_OF: 'anyOf', - COMPLEX_ALL_OF: 'allOf', - COMPLEX_NOT: 'not', - COMPLEX_UNKNOWN: '__unknown', + ARRAY: "array", + OBJECT: "object", + ENUM: "enum", + REF: "$ref", + PRIMITIVE: "primitive", + COMPLEX: "complex", + DISCRIMINATOR: "discriminator", + COMPLEX_ONE_OF: "oneOf", + COMPLEX_ANY_OF: "anyOf", + COMPLEX_ALL_OF: "allOf", + COMPLEX_NOT: "not", + COMPLEX_UNKNOWN: "__unknown", }; const HTTP_CLIENT = { - FETCH: 'fetch', - AXIOS: 'axios', + FETCH: "fetch", + AXIOS: "axios", }; const PROJECT_VERSION = packageJson.version; @@ -47,7 +47,7 @@ const FILE_PREFIX = `/* eslint-disable */ module.exports = { FILE_PREFIX, - DEFAULT_BODY_ARG_NAME: 'data', + DEFAULT_BODY_ARG_NAME: "data", PROJECT_VERSION, SCHEMA_TYPES, HTTP_CLIENT, @@ -59,7 +59,7 @@ module.exports = { PRETTIER_OPTIONS: { printWidth: 120, tabWidth: 2, - trailingComma: 'all', - parser: 'typescript', + trailingComma: "all", + parser: "typescript", }, }; diff --git a/src/index.js b/src/index.js index cfbce631..e8950158 100644 --- a/src/index.js +++ b/src/index.js @@ -6,9 +6,9 @@ // License text available at https://opensource.org/licenses/MIT // Repository https://github.com/acacode/swagger-typescript-api -const constants = require('./constants'); -const { CodeGenProcess } = require('./code-gen-process.js'); -const { generateTemplates } = require('./commands/generate-templates'); +const constants = require("./constants"); +const { CodeGenProcess } = require("./code-gen-process.js"); +const { generateTemplates } = require("./commands/generate-templates"); module.exports = { constants: constants, diff --git a/src/schema-components-map.js b/src/schema-components-map.js index 7062788d..d196636c 100644 --- a/src/schema-components-map.js +++ b/src/schema-components-map.js @@ -1,4 +1,4 @@ -const _ = require('lodash'); +const _ = require("lodash"); class SchemaComponentsMap { /** @type {SchemaComponent[]} */ @@ -15,11 +15,11 @@ class SchemaComponentsMap { } createRef = (paths) => { - return ['#', ...paths].join('/'); + return ["#", ...paths].join("/"); }; parseRef = (ref) => { - return ref.split('/'); + return ref.split("/"); }; createComponent($ref, rawTypeData) { diff --git a/src/schema-parser/base-schema-parsers/array.js b/src/schema-parser/base-schema-parsers/array.js index 977153f5..7245ca11 100644 --- a/src/schema-parser/base-schema-parsers/array.js +++ b/src/schema-parser/base-schema-parsers/array.js @@ -1,6 +1,6 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); -const _ = require('lodash'); -const { SCHEMA_TYPES } = require('../../constants'); +const { MonoSchemaParser } = require("../mono-schema-parser"); +const _ = require("lodash"); +const { SCHEMA_TYPES } = require("../../constants"); class ArraySchemaParser extends MonoSchemaParser { parse() { diff --git a/src/schema-parser/base-schema-parsers/complex.js b/src/schema-parser/base-schema-parsers/complex.js index a23dac4c..49a46f28 100644 --- a/src/schema-parser/base-schema-parsers/complex.js +++ b/src/schema-parser/base-schema-parsers/complex.js @@ -1,6 +1,6 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); -const _ = require('lodash'); -const { SCHEMA_TYPES } = require('../../constants'); +const { MonoSchemaParser } = require("../mono-schema-parser"); +const _ = require("lodash"); +const { SCHEMA_TYPES } = require("../../constants"); class ComplexSchemaParser extends MonoSchemaParser { parse() { @@ -23,8 +23,8 @@ class ComplexSchemaParser extends MonoSchemaParser { name: this.typeName, description: this.schemaFormatters.formatDescription( this.schema.description || - _.compact(_.map(this.schema[complexType], 'description'))[0] || - '', + _.compact(_.map(this.schema[complexType], "description"))[0] || + "", ), content: this.config.Ts.IntersectionType( diff --git a/src/schema-parser/base-schema-parsers/discriminator.js b/src/schema-parser/base-schema-parsers/discriminator.js index 478cd3e3..f28f6bea 100644 --- a/src/schema-parser/base-schema-parsers/discriminator.js +++ b/src/schema-parser/base-schema-parsers/discriminator.js @@ -1,6 +1,6 @@ -const _ = require('lodash'); -const { SCHEMA_TYPES } = require('../../constants'); -const { MonoSchemaParser } = require('../mono-schema-parser'); +const _ = require("lodash"); +const { SCHEMA_TYPES } = require("../../constants"); +const { MonoSchemaParser } = require("../mono-schema-parser"); class DiscriminatorSchemaParser extends MonoSchemaParser { parse() { @@ -54,8 +54,8 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { const ts = this.config.Ts; const refPath = this.schemaComponentsMap.createRef([ - 'components', - 'schemas', + "components", + "schemas", this.typeName, ]); const { discriminator } = this.schema; @@ -85,18 +85,18 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { ts.ObjectWrapper( ts.TypeField({ key: ts.StringValue(discriminator.propertyName), - value: 'Key', + value: "Key", }), ), - 'Type', + "Type", ]); const component = this.schemaParserFabric.createParsedComponent({ typeName: generatedTypeName, schema: { - type: 'object', + type: "object", properties: {}, - genericArgs: [{ name: 'Key' }, { name: 'Type' }], + genericArgs: [{ name: "Key" }, { name: "Type" }], internal: true, }, }); @@ -138,7 +138,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { for (const [mappingKey, schema] of mappingEntries) { const mappingSchema = - typeof schema === 'string' ? { $ref: schema } : schema; + typeof schema === "string" ? { $ref: schema } : schema; this.mutateMappingDependentSchema({ discPropertyName: discriminator.propertyName, @@ -169,7 +169,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { let mappingPropertySchemaEnumKeysMap = {}; let mappingPropertySchema = _.get( abstractSchemaStruct?.component?.rawTypeData, - ['properties', discPropertyName], + ["properties", discPropertyName], ); if (this.schemaUtils.isRefSchema(mappingPropertySchema)) { mappingPropertySchema = this.schemaUtils.getSchemaRefType( @@ -271,7 +271,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { resolver: this.config.extractingOptions.discriminatorAbstractResolver, }); const component = this.schemaComponentsMap.createComponent( - this.schemaComponentsMap.createRef(['components', 'schemas', typeName]), + this.schemaComponentsMap.createRef(["components", "schemas", typeName]), { ...schema, internal: true, diff --git a/src/schema-parser/base-schema-parsers/enum.js b/src/schema-parser/base-schema-parsers/enum.js index 9a9f18dc..af380c42 100644 --- a/src/schema-parser/base-schema-parsers/enum.js +++ b/src/schema-parser/base-schema-parsers/enum.js @@ -1,7 +1,7 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); -const _ = require('lodash'); -const { SCHEMA_TYPES } = require('../../constants'); -const { EnumKeyResolver } = require('../util/enum-key-resolver'); +const { MonoSchemaParser } = require("../mono-schema-parser"); +const _ = require("lodash"); +const { SCHEMA_TYPES } = require("../../constants"); +const { EnumKeyResolver } = require("../util/enum-key-resolver"); class EnumSchemaParser extends MonoSchemaParser { /** @type {EnumKeyResolver} */ @@ -19,8 +19,8 @@ class EnumSchemaParser extends MonoSchemaParser { }); const customComponent = this.schemaComponentsMap.createComponent( this.schemaComponentsMap.createRef([ - 'components', - 'schemas', + "components", + "schemas", generatedTypeName, ]), { @@ -49,9 +49,9 @@ class EnumSchemaParser extends MonoSchemaParser { return this.schemaParserFabric.parseSchema( { oneOf: this.schema.enum.map((enumNames) => ({ - type: 'array', + type: "array", items: enumNames.map((enumName) => ({ - type: 'string', + type: "string", enum: [enumName], })), })), @@ -70,12 +70,12 @@ class EnumSchemaParser extends MonoSchemaParser { return this.config.Ts.NullValue(value); } if ( - _.includes(keyType, this.schemaUtils.getSchemaType({ type: 'number' })) + _.includes(keyType, this.schemaUtils.getSchemaType({ type: "number" })) ) { return this.config.Ts.NumberValue(value); } if ( - _.includes(keyType, this.schemaUtils.getSchemaType({ type: 'boolean' })) + _.includes(keyType, this.schemaUtils.getSchemaType({ type: "boolean" })) ) { return this.config.Ts.BooleanValue(value); } @@ -139,13 +139,13 @@ class EnumSchemaParser extends MonoSchemaParser { if (key) { formatted = this.typeNameFormatter.format(key, { - type: 'enum-key', + type: "enum-key", }); } if (!formatted) { formatted = this.typeNameFormatter.format(`${value}`, { - type: 'enum-key', + type: "enum-key", }); } diff --git a/src/schema-parser/base-schema-parsers/object.js b/src/schema-parser/base-schema-parsers/object.js index 034b20ed..53fb7815 100644 --- a/src/schema-parser/base-schema-parsers/object.js +++ b/src/schema-parser/base-schema-parsers/object.js @@ -1,6 +1,6 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); -const _ = require('lodash'); -const { SCHEMA_TYPES } = require('../../constants'); +const { MonoSchemaParser } = require("../mono-schema-parser"); +const _ = require("lodash"); +const { SCHEMA_TYPES } = require("../../constants"); class ObjectSchemaParser extends MonoSchemaParser { parse() { @@ -36,7 +36,7 @@ class ObjectSchemaParser extends MonoSchemaParser { ); const rawTypeData = _.get( this.schemaUtils.getSchemaRefType(property), - 'rawTypeData', + "rawTypeData", {}, ); const nullable = !!(rawTypeData.nullable || property.nullable); @@ -60,17 +60,17 @@ class ObjectSchemaParser extends MonoSchemaParser { _.compact( _.map( property[this.schemaUtils.getComplexType(property)], - 'description', + "description", ), )[0] || rawTypeData.description || _.compact( _.map( rawTypeData[this.schemaUtils.getComplexType(rawTypeData)], - 'description', + "description", ), )[0] || - '', + "", isRequired: required, isNullable: nullable, name: fieldName, @@ -87,7 +87,7 @@ class ObjectSchemaParser extends MonoSchemaParser { if (additionalProperties) { propertiesContent.push({ $$raw: { additionalProperties }, - description: '', + description: "", isRequired: false, field: this.config.Ts.InterfaceDynamicField( this.config.Ts.Keyword.String, diff --git a/src/schema-parser/base-schema-parsers/primitive.js b/src/schema-parser/base-schema-parsers/primitive.js index 48fee765..3a01962d 100644 --- a/src/schema-parser/base-schema-parsers/primitive.js +++ b/src/schema-parser/base-schema-parsers/primitive.js @@ -1,6 +1,6 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); -const _ = require('lodash'); -const { SCHEMA_TYPES } = require('../../constants'); +const { MonoSchemaParser } = require("../mono-schema-parser"); +const _ = require("lodash"); +const { SCHEMA_TYPES } = require("../../constants"); class PrimitiveSchemaParser extends MonoSchemaParser { parse() { diff --git a/src/schema-parser/complex-schema-parsers/all-of.js b/src/schema-parser/complex-schema-parsers/all-of.js index 8cbe0df5..8992c5fc 100644 --- a/src/schema-parser/complex-schema-parsers/all-of.js +++ b/src/schema-parser/complex-schema-parsers/all-of.js @@ -1,5 +1,5 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); -const _ = require('lodash'); +const { MonoSchemaParser } = require("../mono-schema-parser"); +const _ = require("lodash"); // T1 & T2 class AllOfSchemaParser extends MonoSchemaParser { diff --git a/src/schema-parser/complex-schema-parsers/any-of.js b/src/schema-parser/complex-schema-parsers/any-of.js index 4d81b3da..667c307f 100644 --- a/src/schema-parser/complex-schema-parsers/any-of.js +++ b/src/schema-parser/complex-schema-parsers/any-of.js @@ -1,5 +1,5 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); -const _ = require('lodash'); +const { MonoSchemaParser } = require("../mono-schema-parser"); +const _ = require("lodash"); // T1 | T2 class AnyOfSchemaParser extends MonoSchemaParser { diff --git a/src/schema-parser/complex-schema-parsers/not.js b/src/schema-parser/complex-schema-parsers/not.js index b4b9bc71..cc6bfddd 100644 --- a/src/schema-parser/complex-schema-parsers/not.js +++ b/src/schema-parser/complex-schema-parsers/not.js @@ -1,4 +1,4 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); +const { MonoSchemaParser } = require("../mono-schema-parser"); class NotSchemaParser extends MonoSchemaParser { parse() { diff --git a/src/schema-parser/complex-schema-parsers/one-of.js b/src/schema-parser/complex-schema-parsers/one-of.js index ec8edf38..58117de0 100644 --- a/src/schema-parser/complex-schema-parsers/one-of.js +++ b/src/schema-parser/complex-schema-parsers/one-of.js @@ -1,5 +1,5 @@ -const { MonoSchemaParser } = require('../mono-schema-parser'); -const _ = require('lodash'); +const { MonoSchemaParser } = require("../mono-schema-parser"); +const _ = require("lodash"); // T1 | T2 class OneOfSchemaParser extends MonoSchemaParser { diff --git a/src/schema-parser/mono-schema-parser.js b/src/schema-parser/mono-schema-parser.js index 6c4d2aa9..f5d6e0d3 100644 --- a/src/schema-parser/mono-schema-parser.js +++ b/src/schema-parser/mono-schema-parser.js @@ -35,7 +35,7 @@ class MonoSchemaParser { } parse() { - throw new Error('not implemented'); + throw new Error("not implemented"); } buildTypeNameFromPath = () => { diff --git a/src/schema-parser/schema-formatters.js b/src/schema-parser/schema-formatters.js index 2ef9f229..4a079e13 100644 --- a/src/schema-parser/schema-formatters.js +++ b/src/schema-parser/schema-formatters.js @@ -1,5 +1,5 @@ -const { SCHEMA_TYPES } = require('../constants'); -const _ = require('lodash'); +const { SCHEMA_TYPES } = require("../constants"); +const _ = require("lodash"); class SchemaFormatters { /** @type {CodeGenConfig} */ @@ -100,22 +100,22 @@ class SchemaFormatters { * @param parsedSchema {Record} * @param formatType {"base" | "inline"} */ - formatSchema = (parsedSchema, formatType = 'base') => { + formatSchema = (parsedSchema, formatType = "base") => { const schemaType = - _.get(parsedSchema, ['schemaType']) || - _.get(parsedSchema, ['$parsed', 'schemaType']); + _.get(parsedSchema, ["schemaType"]) || + _.get(parsedSchema, ["$parsed", "schemaType"]); const formatterFn = _.get(this, [formatType, schemaType]); return (formatterFn && formatterFn(parsedSchema)) || parsedSchema; }; formatDescription = (description, inline) => { - if (!description) return ''; + if (!description) return ""; let prettified = description; - prettified = _.replace(prettified, /\*\//g, '*/'); + prettified = _.replace(prettified, /\*\//g, "*/"); - const hasMultipleLines = _.includes(prettified, '\n'); + const hasMultipleLines = _.includes(prettified, "\n"); if (!hasMultipleLines) return prettified; @@ -124,18 +124,18 @@ class SchemaFormatters { .split(/\n/g) .map((part) => _.trim(part)) .compact() - .join(' ') + .join(" ") .valueOf(); } - return _.replace(prettified, /\n$/g, ''); + return _.replace(prettified, /\n$/g, ""); }; formatObjectContent = (content) => { const fields = []; for (const part of content) { - const extraSpace = ' '; + const extraSpace = " "; const result = `${extraSpace}${part.field},\n`; const renderedJsDoc = this.templatesWorker.renderTemplate( @@ -146,9 +146,9 @@ class SchemaFormatters { ); const routeNameFromTemplate = renderedJsDoc - .split('\n') + .split("\n") .map((c) => `${extraSpace}${c}`) - .join('\n'); + .join("\n"); if (routeNameFromTemplate) { fields.push(`${routeNameFromTemplate}${result}`); @@ -157,7 +157,7 @@ class SchemaFormatters { } } - return fields.join(''); + return fields.join(""); }; } diff --git a/src/schema-parser/schema-parser-fabric.js b/src/schema-parser/schema-parser-fabric.js index fbe93a45..044aa2c4 100644 --- a/src/schema-parser/schema-parser-fabric.js +++ b/src/schema-parser/schema-parser-fabric.js @@ -1,7 +1,7 @@ -const _ = require('lodash'); -const { SchemaFormatters } = require('./schema-formatters'); -const { SchemaUtils } = require('./schema-utils'); -const { SchemaParser } = require('./schema-parser'); +const _ = require("lodash"); +const { SchemaFormatters } = require("./schema-formatters"); +const { SchemaUtils } = require("./schema-utils"); +const { SchemaParser } = require("./schema-parser"); class SchemaParserFabric { /** @type {CodeGenConfig} */ @@ -75,7 +75,7 @@ class SchemaParserFabric { createParsedComponent = ({ typeName, schema, schemaPath }) => { const schemaCopy = _.cloneDeep(schema); const customComponent = this.schemaComponentsMap.createComponent( - this.schemaComponentsMap.createRef(['components', 'schemas', typeName]), + this.schemaComponentsMap.createRef(["components", "schemas", typeName]), schemaCopy, ); const parsed = this.parseSchema(schemaCopy, null, schemaPath); diff --git a/src/schema-parser/schema-parser.js b/src/schema-parser/schema-parser.js index 53e4a969..b4cc4b56 100644 --- a/src/schema-parser/schema-parser.js +++ b/src/schema-parser/schema-parser.js @@ -1,21 +1,21 @@ /* eslint-disable no-unused-vars */ -const { SCHEMA_TYPES } = require('../constants.js'); -const _ = require('lodash'); -const { SchemaFormatters } = require('./schema-formatters'); -const { SchemaUtils } = require('./schema-utils'); +const { SCHEMA_TYPES } = require("../constants.js"); +const _ = require("lodash"); +const { SchemaFormatters } = require("./schema-formatters"); +const { SchemaUtils } = require("./schema-utils"); const { DiscriminatorSchemaParser, -} = require('./base-schema-parsers/discriminator'); -const { EnumSchemaParser } = require('./base-schema-parsers/enum'); -const { ObjectSchemaParser } = require('./base-schema-parsers/object'); -const { PrimitiveSchemaParser } = require('./base-schema-parsers/primitive'); -const { ComplexSchemaParser } = require('./base-schema-parsers/complex'); -const { OneOfSchemaParser } = require('./complex-schema-parsers/one-of'); -const { AllOfSchemaParser } = require('./complex-schema-parsers/all-of'); -const { AnyOfSchemaParser } = require('./complex-schema-parsers/any-of'); -const { NotSchemaParser } = require('./complex-schema-parsers/not'); -const { ArraySchemaParser } = require('./base-schema-parsers/array'); -const { sortByProperty } = require('../util/sort-by-property'); +} = require("./base-schema-parsers/discriminator"); +const { EnumSchemaParser } = require("./base-schema-parsers/enum"); +const { ObjectSchemaParser } = require("./base-schema-parsers/object"); +const { PrimitiveSchemaParser } = require("./base-schema-parsers/primitive"); +const { ComplexSchemaParser } = require("./base-schema-parsers/complex"); +const { OneOfSchemaParser } = require("./complex-schema-parsers/one-of"); +const { AllOfSchemaParser } = require("./complex-schema-parsers/all-of"); +const { AnyOfSchemaParser } = require("./complex-schema-parsers/any-of"); +const { NotSchemaParser } = require("./complex-schema-parsers/not"); +const { ArraySchemaParser } = require("./base-schema-parsers/array"); +const { sortByProperty } = require("../util/sort-by-property"); class SchemaParser { /** @type {SchemaParserFabric} */ @@ -184,7 +184,7 @@ class SchemaParser { let schemaType = null; let parsedSchema = null; - if (typeof this.schema === 'string') { + if (typeof this.schema === "string") { return this.schema; } @@ -209,13 +209,13 @@ class SchemaParser { this.schema.enum.length === 1 && this.schema.enum[0] == null ) { - this.logger.debug('invalid enum schema', this.schema); + this.logger.debug("invalid enum schema", this.schema); this.schema = { type: this.config.Ts.Keyword.Null }; } // schema is response schema if ( - 'content' in this.schema && - typeof this.schema['content'] === 'object' + "content" in this.schema && + typeof this.schema["content"] === "object" ) { const schema = this.extractSchemaFromResponseStruct(this.schema); const schemaParser = this.schemaParserFabric.createSchemaParser({ @@ -254,7 +254,7 @@ class SchemaParser { Array.isArray(this.schema.$parsed?.content) ) { this.schema.$parsed.content = this.schema.$parsed.content.sort( - sortByProperty('name'), + sortByProperty("name"), ); } } @@ -268,7 +268,7 @@ class SchemaParser { const parsedSchema = this.parseSchema(); const formattedSchema = this.schemaFormatters.formatSchema( parsedSchema, - 'inline', + "inline", ); return formattedSchema.content; }; @@ -277,7 +277,7 @@ class SchemaParser { const parsedSchema = this.parseSchema(); const formattedSchema = this.schemaFormatters.formatSchema( parsedSchema, - 'base', + "base", ); return formattedSchema.content; }; @@ -286,13 +286,13 @@ class SchemaParser { const { content, ...extras } = responseStruct; const firstResponse = _.first(_.values(content)); - const firstSchema = _.get(firstResponse, 'schema'); + const firstSchema = _.get(firstResponse, "schema"); if (!firstSchema) return; return { ...extras, - ..._.omit(firstResponse, 'schema'), + ..._.omit(firstResponse, "schema"), ...firstSchema, }; }; diff --git a/src/schema-parser/schema-utils.js b/src/schema-parser/schema-utils.js index 79133645..f297f181 100644 --- a/src/schema-parser/schema-utils.js +++ b/src/schema-parser/schema-utils.js @@ -1,8 +1,8 @@ -const _ = require('lodash'); -const { SCHEMA_TYPES } = require('../constants'); -const { internalCase } = require('../util/internal-case'); -const { pascalCase } = require('../util/pascal-case'); -const { camelCase } = require('lodash'); +const _ = require("lodash"); +const { SCHEMA_TYPES } = require("../constants"); +const { internalCase } = require("../util/internal-case"); +const { pascalCase } = require("../util/pascal-case"); +const { camelCase } = require("lodash"); class SchemaUtils { /** @type {CodeGenConfig} */ @@ -33,15 +33,15 @@ class SchemaUtils { }; isRefSchema = (schema) => { - return !!(schema && schema['$ref']); + return !!(schema && schema["$ref"]); }; getEnumNames = (schema) => { return ( - schema['x-enumNames'] || - schema['xEnumNames'] || - schema['x-enumnames'] || - schema['x-enum-varnames'] + schema["x-enumNames"] || + schema["xEnumNames"] || + schema["x-enumnames"] || + schema["x-enum-varnames"] ); }; @@ -52,15 +52,15 @@ class SchemaUtils { }; isPropertyRequired = (name, propertySchema, rootSchema) => { - if (propertySchema['x-omitempty'] === false) { + if (propertySchema["x-omitempty"] === false) { return true; } const isRequired = _.isBoolean(propertySchema.required) ? !!propertySchema.required : _.isArray(rootSchema.required) - ? rootSchema.required.includes(name) - : !!rootSchema.required; + ? rootSchema.required.includes(name) + : !!rootSchema.required; if (this.config.convertedFromSwagger2) { return typeof propertySchema.nullable === this.config.Ts.Keyword.Undefined @@ -74,7 +74,7 @@ class SchemaUtils { const { nullable, type: schemaType } = schema || {}; return ( (nullable || - !!_.get(schema, 'x-nullable') || + !!_.get(schema, "x-nullable") || schemaType === this.config.Ts.Keyword.Null) && _.isString(type) && !type.includes(` ${this.config.Ts.Keyword.Null}`) && @@ -112,7 +112,7 @@ class SchemaUtils { }; checkAndAddRequiredKeys = (schema, resultType) => { - if ('$$requiredKeys' in schema && schema.$$requiredKeys.length) { + if ("$$requiredKeys" in schema && schema.$$requiredKeys.length) { this.config.update({ internalTemplateOptions: { addUtilRequiredKeysType: true, @@ -261,7 +261,7 @@ class SchemaUtils { const typeAlias = _.get(this.config.primitiveTypes, [primitiveType, schema.format]) || - _.get(this.config.primitiveTypes, [primitiveType, '$default']) || + _.get(this.config.primitiveTypes, [primitiveType, "$default"]) || this.config.primitiveTypes[primitiveType]; if (_.isFunction(typeAlias)) { @@ -288,24 +288,24 @@ class SchemaUtils { return pascalCase( camelCase( - _.uniq([schemaPath[0], schemaPath[schemaPath.length - 1]]).join('_'), + _.uniq([schemaPath[0], schemaPath[schemaPath.length - 1]]).join("_"), ), ); }; isConstantSchema(schema) { - return 'const' in schema; + return "const" in schema; } formatJsValue = (value) => { switch (typeof value) { - case 'string': { + case "string": { return this.config.Ts.StringValue(value); } - case 'boolean': { + case "boolean": { return this.config.Ts.BooleanValue(value); } - case 'number': { + case "number": { return this.config.Ts.NumberValue(value); } default: { diff --git a/src/schema-parser/util/enum-key-resolver.js b/src/schema-parser/util/enum-key-resolver.js index 8db6a226..b609e5fa 100644 --- a/src/schema-parser/util/enum-key-resolver.js +++ b/src/schema-parser/util/enum-key-resolver.js @@ -1,4 +1,4 @@ -const { NameResolver } = require('../../util/name-resolver'); +const { NameResolver } = require("../../util/name-resolver"); class EnumKeyResolver extends NameResolver { counter = 1; @@ -13,7 +13,7 @@ class EnumKeyResolver extends NameResolver { (variants[0] && `${variants[0]}${this.counter++}`) || `${this.config.enumKeyResolverName}${this.counter++}`; this.logger.debug( - 'generated fallback type name for enum key - ', + "generated fallback type name for enum key - ", generatedVariant, ); return generatedVariant; diff --git a/src/schema-routes/schema-routes.js b/src/schema-routes/schema-routes.js index 365f2328..81a73a8f 100644 --- a/src/schema-routes/schema-routes.js +++ b/src/schema-routes/schema-routes.js @@ -1,24 +1,24 @@ -const _ = require('lodash'); -const { generateId } = require('../util/id.js'); +const _ = require("lodash"); +const { generateId } = require("../util/id.js"); const { SpecificArgNameResolver, -} = require('./util/specific-arg-name-resolver'); +} = require("./util/specific-arg-name-resolver"); const { DEFAULT_BODY_ARG_NAME, RESERVED_BODY_ARG_NAMES, RESERVED_HEADER_ARG_NAMES, RESERVED_PATH_ARG_NAMES, RESERVED_QUERY_ARG_NAMES, -} = require('../constants.js'); -const { camelCase } = require('lodash'); +} = require("../constants.js"); +const { camelCase } = require("lodash"); const CONTENT_KIND = { - JSON: 'JSON', - URL_ENCODED: 'URL_ENCODED', - FORM_DATA: 'FORM_DATA', - IMAGE: 'IMAGE', - OTHER: 'OTHER', - TEXT: 'TEXT', + JSON: "JSON", + URL_ENCODED: "URL_ENCODED", + FORM_DATA: "FORM_DATA", + IMAGE: "IMAGE", + OTHER: "OTHER", + TEXT: "TEXT", }; class SchemaRoutes { @@ -75,20 +75,20 @@ class SchemaRoutes { this.templatesWorker = templatesWorker; this.FORM_DATA_TYPES = _.uniq([ - this.schemaUtils.getSchemaType({ type: 'string', format: 'file' }), - this.schemaUtils.getSchemaType({ type: 'string', format: 'binary' }), + this.schemaUtils.getSchemaType({ type: "string", format: "file" }), + this.schemaUtils.getSchemaType({ type: "string", format: "binary" }), ]); } createRequestsMap = (routeInfoByMethodsMap) => { - const parameters = _.get(routeInfoByMethodsMap, 'parameters'); + const parameters = _.get(routeInfoByMethodsMap, "parameters"); return _.reduce( routeInfoByMethodsMap, (acc, requestInfo, method) => { if ( - _.startsWith(method, 'x-') || - ['parameters', '$ref'].includes(method) + _.startsWith(method, "x-") || + ["parameters", "$ref"].includes(method) ) { return acc; } @@ -109,7 +109,7 @@ class SchemaRoutes { this.config.hooks.onPreBuildRoutePath(originalRouteName) || originalRouteName; - const pathParamMatches = (routeName || '').match( + const pathParamMatches = (routeName || "").match( /({(([A-z]){1}([a-zA-Z0-9]-?_?\.?)+)([0-9]+)?})|(:(([A-z]){1}([a-zA-Z0-9]-?_?\.?)+)([0-9]+)?:?)/g, ); @@ -117,24 +117,24 @@ class SchemaRoutes { const pathParams = _.reduce( pathParamMatches, (pathParams, match) => { - const paramName = _.replace(match, /\{|\}|:/g, ''); + const paramName = _.replace(match, /\{|\}|:/g, ""); if (!paramName) return pathParams; - if (_.includes(paramName, '-')) { - this.logger.warn('wrong path param name', paramName); + if (_.includes(paramName, "-")) { + this.logger.warn("wrong path param name", paramName); } pathParams.push({ $match: match, name: _.camelCase(paramName), required: true, - type: 'string', - description: '', + type: "string", + description: "", schema: { - type: 'string', + type: "string", }, - in: 'path', + in: "path", }); return pathParams; @@ -154,7 +154,7 @@ class SchemaRoutes { ) || pathParam.name; return _.replace(fixedRoute, pathParam.$match, `\${${insertion}}`); }, - routeName || '', + routeName || "", ); const queryParamMatches = fixedRoute.match(/(\{\?.*\})/g); @@ -162,35 +162,35 @@ class SchemaRoutes { if (queryParamMatches && queryParamMatches.length) { queryParamMatches.forEach((match) => { - fixedRoute = fixedRoute.replace(match, ''); + fixedRoute = fixedRoute.replace(match, ""); }); _.uniq( queryParamMatches - .join(',') - .replace(/(\{\?)|(\})|\s/g, '') - .split(','), + .join(",") + .replace(/(\{\?)|(\})|\s/g, "") + .split(","), ).forEach((paramName) => { - if (_.includes(paramName, '-')) { - this.logger.warn('wrong query param name', paramName); + if (_.includes(paramName, "-")) { + this.logger.warn("wrong query param name", paramName); } queryParams.push({ $match: paramName, name: _.camelCase(paramName), required: true, - type: 'string', - description: '', + type: "string", + description: "", schema: { - type: 'string', + type: "string", }, - in: 'query', + in: "query", }); }); } const result = { - originalRoute: originalRouteName || '', + originalRoute: originalRouteName || "", route: fixedRoute, pathParams, queryParams, @@ -246,7 +246,7 @@ class SchemaRoutes { }; } - if (routeParam.in === 'path') { + if (routeParam.in === "path") { if (!routeParam.name) return; routeParam.name = _.camelCase(routeParam.name); @@ -300,29 +300,29 @@ class SchemaRoutes { getContentKind = (contentTypes) => { if ( _.some(contentTypes, (contentType) => - _.startsWith(contentType, 'application/json'), + _.startsWith(contentType, "application/json"), ) || - _.some(contentTypes, (contentType) => _.endsWith(contentType, '+json')) + _.some(contentTypes, (contentType) => _.endsWith(contentType, "+json")) ) { return CONTENT_KIND.JSON; } - if (contentTypes.includes('application/x-www-form-urlencoded')) { + if (contentTypes.includes("application/x-www-form-urlencoded")) { return CONTENT_KIND.URL_ENCODED; } - if (contentTypes.includes('multipart/form-data')) { + if (contentTypes.includes("multipart/form-data")) { return CONTENT_KIND.FORM_DATA; } if ( - _.some(contentTypes, (contentType) => _.includes(contentType, 'image/')) + _.some(contentTypes, (contentType) => _.includes(contentType, "image/")) ) { return CONTENT_KIND.IMAGE; } if ( - _.some(contentTypes, (contentType) => _.startsWith(contentType, 'text/')) + _.some(contentTypes, (contentType) => _.startsWith(contentType, "text/")) ) { return CONTENT_KIND.TEXT; } @@ -331,13 +331,13 @@ class SchemaRoutes { }; isSuccessStatus = (status) => - (this.config.defaultResponseAsSuccess && status === 'default') || + (this.config.defaultResponseAsSuccess && status === "default") || (+status >= this.config.successResponseStatusRange[0] && +status <= this.config.successResponseStatusRange[1]) || - status === '2xx'; + status === "2xx"; getSchemaFromRequestType = (requestInfo) => { - const content = _.get(requestInfo, 'content'); + const content = _.get(requestInfo, "content"); if (!content) return null; @@ -398,7 +398,7 @@ class SchemaRoutes { const typeNameWithoutOpId = _.replace( refTypeInfo.typeName, operationId, - '', + "", ); if ( _.find(parsedSchemas, (schema) => schema.name === typeNameWithoutOpId) @@ -407,10 +407,10 @@ class SchemaRoutes { } switch (refTypeInfo.componentName) { - case 'schemas': + case "schemas": return this.typeNameFormatter.format(refTypeInfo.typeName); - case 'responses': - case 'requestBodies': + case "responses": + case "requestBodies": return this.schemaParserFabric.getInlineParseContent( this.getSchemaFromRequestType(refTypeInfo.rawTypeData), refTypeInfo.typeName || null, @@ -456,7 +456,7 @@ class SchemaRoutes { ), description: this.schemaParserFabric.schemaFormatters.formatDescription( - requestInfo.description || '', + requestInfo.description || "", true, ), status: _.isNaN(+status) ? status : +status, @@ -472,7 +472,7 @@ class SchemaRoutes { const contentTypes = this.getContentTypes(responses, [ ...(produces || []), - routeInfo['x-accepts'], + routeInfo["x-accepts"], ]); const responseInfos = this.getRequestInfoTypes({ @@ -492,7 +492,7 @@ class SchemaRoutes { const handleResponseHeaders = (src) => { if (!src) { - return 'headers: {},'; + return "headers: {},"; } const headerTypes = Object.fromEntries( Object.entries(src).map(([k, v]) => { @@ -501,7 +501,7 @@ class SchemaRoutes { ); const r = `headers: { ${Object.entries(headerTypes) .map(([k, v]) => `"${k}": ${v}`) - .join(',')} },`; + .join(",")} },`; return r; }; @@ -545,7 +545,7 @@ class SchemaRoutes { let usageName = `${schemaPart.name}`; - if (usageName.includes('.')) { + if (usageName.includes(".")) { usageName = camelCase(usageName); } @@ -564,7 +564,7 @@ class SchemaRoutes { }, { properties: {}, - type: 'object', + type: "object", }, ); }; @@ -576,7 +576,7 @@ class SchemaRoutes { const contentTypes = this.getContentTypes( [requestBody], - [...(consumes || []), routeInfo['x-contentType']], + [...(consumes || []), routeInfo["x-contentType"]], ); let contentKind = this.getContentKind(contentTypes); @@ -650,7 +650,7 @@ class SchemaRoutes { type: content, required: requestBody && - (typeof requestBody.required === 'undefined' || !!requestBody.required), + (typeof requestBody.required === "undefined" || !!requestBody.required), }; }; @@ -669,7 +669,7 @@ class SchemaRoutes { if (pathArgSchema.name) { acc[pathArgSchema.name] = { ...pathArgSchema, - in: 'path', + in: "path", }; } @@ -679,12 +679,12 @@ class SchemaRoutes { ); const fixedQueryParams = _.reduce( - _.get(queryObjectSchema, 'properties', {}), + _.get(queryObjectSchema, "properties", {}), (acc, property, name) => { if (name && _.isObject(property)) { acc[name] = { ...property, - in: 'query', + in: "query", }; } @@ -784,17 +784,17 @@ class SchemaRoutes { title: errorSchemas .map((schema) => schema.title) .filter(Boolean) - .join(' '), + .join(" "), description: errorSchemas .map((schema) => schema.description) .filter(Boolean) - .join('\n'), + .join("\n"), }, null, [routeInfo.operationId], ); const component = this.schemaComponentsMap.createComponent( - this.schemaComponentsMap.createRef(['components', 'schemas', typeName]), + this.schemaComponentsMap.createRef(["components", "schemas", typeName]), { ...schema }, ); responseBodyInfo.error.schemas = [component]; @@ -843,7 +843,7 @@ class SchemaRoutes { const duplicates = routeNameDuplicatesMap.get(duplicateIdentifier); const routeNameInfo = { - usage: routeName + (duplicates > 1 ? duplicates : ''), + usage: routeName + (duplicates > 1 ? duplicates : ""), original: routeName, duplicate: duplicates > 1, }; @@ -891,7 +891,7 @@ class SchemaRoutes { const moduleName = moduleNameFirstTag && firstTag ? _.camelCase(firstTag) - : _.camelCase(_.compact(_.split(route, '/'))[moduleNameIndex]); + : _.camelCase(_.compact(_.split(route, "/"))[moduleNameIndex]); let hasSecurity = !!(globalSecurity && globalSecurity.length); if (security) { hasSecurity = security.length > 0; @@ -1059,7 +1059,7 @@ class SchemaRoutes { return { id: routeId, - namespace: _.replace(moduleName, /^(\d)/, 'v$1'), + namespace: _.replace(moduleName, /^(\d)/, "v$1"), routeName, routeParams, requestBodyInfo, @@ -1156,7 +1156,7 @@ class SchemaRoutes { const routeGroups = _.reduce( groupedRoutes, (acc, routesGroup, moduleName) => { - if (moduleName === '$outOfModule') { + if (moduleName === "$outOfModule") { acc.outOfModule = routesGroup; } else { if (!acc.combined) acc.combined = []; diff --git a/src/schema-routes/util/specific-arg-name-resolver.js b/src/schema-routes/util/specific-arg-name-resolver.js index ca3c64f3..cd624f46 100644 --- a/src/schema-routes/util/specific-arg-name-resolver.js +++ b/src/schema-routes/util/specific-arg-name-resolver.js @@ -1,4 +1,4 @@ -const { NameResolver } = require('../../util/name-resolver'); +const { NameResolver } = require("../../util/name-resolver"); class SpecificArgNameResolver extends NameResolver { counter = 1; @@ -13,7 +13,7 @@ class SpecificArgNameResolver extends NameResolver { (variants[0] && `${variants[0]}${this.counter++}`) || `${this.config.specificArgNameResolverName}${this.counter++}`; this.logger.debug( - 'generated fallback type name for specific arg - ', + "generated fallback type name for specific arg - ", generatedVariant, ); return generatedVariant; diff --git a/src/schema-walker.js b/src/schema-walker.js index 01c05f9d..e2055c31 100644 --- a/src/schema-walker.js +++ b/src/schema-walker.js @@ -1,4 +1,4 @@ -const _ = require('lodash'); +const _ = require("lodash"); // TODO: WIP // this class will be needed to walk by schema everywhere @@ -32,7 +32,7 @@ class SchemaWalker { * @returns {any} */ findByRef = (ref) => { - this.logger.debug('try to resolve ref by path', ref); + this.logger.debug("try to resolve ref by path", ref); if (this.caches.has(ref)) { return this.caches.get(ref); @@ -47,10 +47,10 @@ class SchemaWalker { } } } else if (this._isRemoteRef(ref)) { - this.logger.debug('remote refs not supported', ref); + this.logger.debug("remote refs not supported", ref); return null; } else { - const [address, path] = path.split('#'); + const [address, path] = path.split("#"); let swaggerSchemaObject; if (this.schemas.has(address)) { @@ -71,15 +71,15 @@ class SchemaWalker { }; _isLocalRef = (ref) => { - return ref.startsWith('#'); + return ref.startsWith("#"); }; _isRemoteRef = (ref) => { - return ref.startsWith('http://') || ref.startsWith('https://'); + return ref.startsWith("http://") || ref.startsWith("https://"); }; _getRefDataFromSchema = (schema, ref) => { - const path = ref.replace('#', '').split('/'); + const path = ref.replace("#", "").split("/"); const refData = _.get(schema, path); if (refData) { this.caches.set(ref, refData); diff --git a/src/swagger-schema-resolver.js b/src/swagger-schema-resolver.js index 6725e666..1196650f 100644 --- a/src/swagger-schema-resolver.js +++ b/src/swagger-schema-resolver.js @@ -1,7 +1,7 @@ -const _ = require('lodash'); -const converter = require('swagger2openapi'); -const yaml = require('js-yaml'); -const { Request } = require('./util/request'); +const _ = require("lodash"); +const converter = require("swagger2openapi"); +const yaml = require("js-yaml"); +const { Request } = require("./util/request"); class SwaggerSchemaResolver { /** @@ -70,8 +70,8 @@ class SwaggerSchemaResolver { const result = _.cloneDeep(swaggerSchema); result.info = _.merge( { - title: 'No title', - version: '', + title: "No title", + version: "", }, result.info, ); @@ -84,14 +84,14 @@ class SwaggerSchemaResolver { { ...converterOptions, warnOnly: true, - refSiblings: 'preserve', - rbname: 'requestBodyName', + refSiblings: "preserve", + rbname: "requestBodyName", }, (err, options) => { const parsedSwaggerSchema = _.get( err, - 'options.openapi', - _.get(options, 'openapi'), + "options.openapi", + _.get(options, "openapi"), ); if (!parsedSwaggerSchema && err) { throw new Error(err); @@ -138,7 +138,7 @@ class SwaggerSchemaResolver { } processSwaggerSchemaFile(file) { - if (typeof file !== 'string') return file; + if (typeof file !== "string") return file; try { return JSON.parse(file); @@ -148,8 +148,8 @@ class SwaggerSchemaResolver { } fixSwaggerSchema({ usageSchema, originalSchema }) { - const usagePaths = _.get(usageSchema, 'paths'); - const originalPaths = _.get(originalSchema, 'paths'); + const usagePaths = _.get(usageSchema, "paths"); + const originalPaths = _.get(originalSchema, "paths"); // walk by routes _.each(usagePaths, (usagePathObject, route) => { @@ -158,10 +158,10 @@ class SwaggerSchemaResolver { // walk by methods _.each(usagePathObject, (usageRouteInfo, methodName) => { const originalRouteInfo = _.get(originalPathObject, methodName); - const usageRouteParams = _.get(usageRouteInfo, 'parameters', []); - const originalRouteParams = _.get(originalRouteInfo, 'parameters', []); + const usageRouteParams = _.get(usageRouteInfo, "parameters", []); + const originalRouteParams = _.get(originalRouteInfo, "parameters", []); - if (typeof usageRouteInfo === 'object') { + if (typeof usageRouteInfo === "object") { usageRouteInfo.consumes = _.uniq( _.compact([ ...(usageRouteInfo.consumes || []), diff --git a/src/templates-worker.js b/src/templates-worker.js index 8fed4e3a..9d4e3214 100644 --- a/src/templates-worker.js +++ b/src/templates-worker.js @@ -1,7 +1,7 @@ -const { resolve } = require('path'); -const _ = require('lodash'); -const Eta = require('eta'); -const path = require('path'); +const { resolve } = require("node:path"); +const _ = require("lodash"); +const Eta = require("eta"); +const path = require("node:path"); class TemplatesWorker { /** @@ -34,9 +34,9 @@ class TemplatesWorker { * @returns {CodeGenConfig.templatePaths} */ getTemplatePaths = (config) => { - const baseTemplatesPath = resolve(__dirname, '../templates/base'); - const defaultTemplatesPath = resolve(__dirname, '../templates/default'); - const modularTemplatesPath = resolve(__dirname, '../templates/modular'); + const baseTemplatesPath = resolve(__dirname, "../templates/base"); + const defaultTemplatesPath = resolve(__dirname, "../templates/default"); + const modularTemplatesPath = resolve(__dirname, "../templates/modular"); const originalTemplatesPath = config.modular ? modularTemplatesPath : defaultTemplatesPath; @@ -59,12 +59,12 @@ class TemplatesWorker { cropExtension = (path) => this.config.templateExtensions.reduce( - (path, ext) => (_.endsWith(path, ext) ? path.replace(ext, '') : path), + (path, ext) => (_.endsWith(path, ext) ? path.replace(ext, "") : path), path, ); getTemplateFullPath = (path, fileName) => { - const raw = resolve(path, './', this.cropExtension(fileName)); + const raw = resolve(path, "./", this.cropExtension(fileName)); const pathVariants = this.config.templateExtensions.map( (extension) => `${raw}${extension}`, ); @@ -76,13 +76,16 @@ class TemplatesWorker { requireFnFromTemplate = (packageOrPath) => { const isPath = - _.startsWith(packageOrPath, './') || _.startsWith(packageOrPath, '../'); + _.startsWith(packageOrPath, "./") || _.startsWith(packageOrPath, "../"); if (isPath) { - return require(path.resolve( - this.config.templatePaths.custom || this.config.templatePaths.original, - packageOrPath, - )); + return require( + path.resolve( + this.config.templatePaths.custom || + this.config.templatePaths.original, + packageOrPath, + ), + ); } return require(packageOrPath); @@ -95,7 +98,7 @@ class TemplatesWorker { return this.fileSystem.getFileContent(path); } - if (!fileName) return ''; + if (!fileName) return ""; const customFullPath = templatePaths.custom && @@ -120,7 +123,7 @@ class TemplatesWorker { `"${_.lowerCase(name)}" template not found in "${ templatePaths.custom }"`, - `\nCode generator will use the default template`, + "\nCode generator will use the default template", ); } else { this.logger.log( @@ -202,7 +205,7 @@ class TemplatesWorker { return this.fileSystem.getFileContent(originalPath); } - return ''; + return ""; }; /** @@ -212,7 +215,7 @@ class TemplatesWorker { * @returns {Promise} */ renderTemplate = (template, configuration, options) => { - if (!template) return ''; + if (!template) return ""; return Eta.render( template, diff --git a/src/translators/javascript.js b/src/translators/javascript.js index 75e4959a..133980fc 100644 --- a/src/translators/javascript.js +++ b/src/translators/javascript.js @@ -1,5 +1,5 @@ -const ts = require('typescript'); -const { Translator } = require('./translator'); +const ts = require("typescript"); +const { Translator } = require("./translator"); class JavascriptTranslator extends Translator { /** @@ -51,17 +51,17 @@ class JavascriptTranslator extends Translator { const dtsFileName = `${input.fileName}${ts.Extension.Dts}`; const sourceContent = compiled[jsFileName]; const tsImportRows = input.fileContent - .split('\n') - .filter((line) => line.startsWith('import ')); + .split("\n") + .filter((line) => line.startsWith("import ")); const declarationContent = compiled[dtsFileName] - .split('\n') + .split("\n") .map((line) => { - if (line.startsWith('import ')) { + if (line.startsWith("import ")) { return tsImportRows.shift(); } return line; }) - .join('\n'); + .join("\n"); return [ { diff --git a/src/translators/translator.js b/src/translators/translator.js index e6b2d72e..1d68168e 100644 --- a/src/translators/translator.js +++ b/src/translators/translator.js @@ -26,7 +26,7 @@ class Translator { */ // eslint-disable-next-line no-unused-vars translate(input) { - throw new Error('not implemented'); + throw new Error("not implemented"); } } diff --git a/src/type-name-formatter.js b/src/type-name-formatter.js index 49bc1aee..f8806471 100644 --- a/src/type-name-formatter.js +++ b/src/type-name-formatter.js @@ -1,4 +1,4 @@ -const _ = require('lodash'); +const _ = require("lodash"); /** * @typedef {"enum-key" | "type-name"} FormattingSchemaType @@ -30,27 +30,27 @@ class TypeNameFormatter { /** * @type {FormattingSchemaType} */ - const schemaType = options.type || 'type-name'; + const schemaType = options.type || "type-name"; const typePrefix = - schemaType === 'enum-key' + schemaType === "enum-key" ? this.config.enumKeyPrefix : this.config.typePrefix; const typeSuffix = - schemaType === 'enum-key' + schemaType === "enum-key" ? this.config.enumKeySuffix : this.config.typeSuffix; const hashKey = `${typePrefix}_${name}_${typeSuffix}`; - if (typeof name !== 'string') { - this.logger.warn('wrong name of the model name', name); + if (typeof name !== "string") { + this.logger.warn("wrong name of the model name", name); return name; } // constant names like LEFT_ARROW, RIGHT_FORWARD, ETC_KEY, _KEY_NUM_ if (/^([A-Z_]{1,})$/g.test(name)) { - return _.compact([typePrefix, name, typeSuffix]).join('_'); + return _.compact([typePrefix, name, typeSuffix]).join("_"); } if (this.formattedModelNamesMap.has(hashKey)) { @@ -62,7 +62,7 @@ class TypeNameFormatter { const formattedName = _.replace( _.startCase(`${typePrefix}_${fixedModelName}_${typeSuffix}`), /\s/g, - '', + "", ); const formattedResultName = this.config.hooks.onFormatTypeName(formattedName, name, schemaType) || @@ -86,22 +86,22 @@ class TypeNameFormatter { if (!this.isValidName(name)) { if (!/^[a-zA-Z_$]/g.test(name)) { const fixPrefix = - type === 'enum-key' + type === "enum-key" ? this.config.fixInvalidEnumKeyPrefix : this.config.fixInvalidTypeNamePrefix; name = `${fixPrefix} ${name}`; } // specific replaces for TSOA 3.x - if (name.includes('.')) + if (name.includes(".")) name = name - .replace(/Exclude_keyof[A-Za-z]+/g, () => 'ExcludeKeys') - .replace(/%22~AND~%22/g, 'And') - .replace(/%22~OR~%22/g, 'Or') - .replace(/(\.?%22)|\./g, '_') - .replace(/__+$/, ''); + .replace(/Exclude_keyof[A-Za-z]+/g, () => "ExcludeKeys") + .replace(/%22~AND~%22/g, "And") + .replace(/%22~OR~%22/g, "Or") + .replace(/(\.?%22)|\./g, "_") + .replace(/__+$/, ""); - if (name.includes('-')) name = _.startCase(name).replace(/ /g, ''); + if (name.includes("-")) name = _.startCase(name).replace(/ /g, ""); } return name; diff --git a/src/util/file-system.js b/src/util/file-system.js index e99ba03d..9408bb57 100644 --- a/src/util/file-system.js +++ b/src/util/file-system.js @@ -1,8 +1,8 @@ -const fs = require('fs'); -const makeDir = require('make-dir'); -const { resolve } = require('path'); -const _ = require('lodash'); -const { Logger } = require('./logger'); +const fs = require("node:fs"); +const makeDir = require("make-dir"); +const { resolve } = require("node:path"); +const _ = require("lodash"); +const { Logger } = require("./logger"); const FILE_PREFIX = `/* eslint-disable */ /* tslint:disable */ @@ -21,12 +21,12 @@ class FileSystem { /** @type {Logger} */ logger; - constructor({ logger = new Logger('file-system') } = {}) { + constructor({ logger = new Logger("file-system") } = {}) { this.logger = logger; } getFileContent = (path) => { - return fs.readFileSync(path, { encoding: 'UTF-8' }); + return fs.readFileSync(path, { encoding: "UTF-8" }); }; readDir = (path) => { @@ -45,24 +45,24 @@ class FileSystem { }; cropExtension = (fileName) => { - const fileNameParts = _.split(fileName, '.'); + const fileNameParts = _.split(fileName, "."); if (fileNameParts.length > 1) { fileNameParts.pop(); } - return fileNameParts.join('.'); + return fileNameParts.join("."); }; removeDir = (path) => { try { - if (typeof fs.rmSync === 'function') { + if (typeof fs.rmSync === "function") { fs.rmSync(path, { recursive: true }); } else { fs.rmdirSync(path, { recursive: true }); } } catch (e) { - this.logger.debug('failed to remove dir', e); + this.logger.debug("failed to remove dir", e); } }; @@ -70,7 +70,7 @@ class FileSystem { try { makeDir.sync(path); } catch (e) { - this.logger.debug('failed to create dir', e); + this.logger.debug("failed to create dir", e); } }; @@ -85,7 +85,7 @@ class FileSystem { createFile = ({ path, fileName, content, withPrefix }) => { const absolutePath = resolve(__dirname, path, `./${fileName}`); - const fileContent = `${withPrefix ? FILE_PREFIX : ''}${content}`; + const fileContent = `${withPrefix ? FILE_PREFIX : ""}${content}`; return fs.writeFileSync(absolutePath, fileContent, _.noop); }; diff --git a/src/util/id.js b/src/util/id.js index 95847a64..d4c6b30e 100644 --- a/src/util/id.js +++ b/src/util/id.js @@ -1,6 +1,6 @@ -const { customAlphabet } = require('nanoid'); +const { customAlphabet } = require("nanoid"); -const ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'; +const ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; const generateId = customAlphabet(ALPHABET, 12); diff --git a/src/util/internal-case.js b/src/util/internal-case.js index bc6727f5..81ae2b60 100644 --- a/src/util/internal-case.js +++ b/src/util/internal-case.js @@ -1,4 +1,4 @@ -const _ = require('lodash'); +const _ = require("lodash"); module.exports = { internalCase: (value) => _.camelCase(_.lowerCase(value)), diff --git a/src/util/logger.js b/src/util/logger.js index 141fce11..52119a8f 100644 --- a/src/util/logger.js +++ b/src/util/logger.js @@ -1,5 +1,5 @@ -const { emojify } = require('node-emoji'); -const _ = require('lodash'); +const { emojify } = require("node-emoji"); +const _ = require("lodash"); class Logger { firstLog = true; @@ -22,43 +22,43 @@ class Logger { this.log( `swagger-typescript-api(${this.config.version}),${ process.env.npm_config_user_agent || `nodejs(${process.version})` - },debug mode ${this.config.debug ? 'ENABLED' : 'DISABLED'}`, + },debug mode ${this.config.debug ? "ENABLED" : "DISABLED"}`, ); } - if (type === 'debug' || this.config.debug) { + if (type === "debug" || this.config.debug) { const trace = new Error().stack - .split('\n') + .split("\n") .splice(3) .filter( (line) => - !line.includes('swagger-typescript-api\\node_modules') && - !line.includes('swagger-typescript-api/node_modules'), + !line.includes("swagger-typescript-api\\node_modules") && + !line.includes("swagger-typescript-api/node_modules"), ) .slice(0, 10); const logFn = console[type] || console.log; logFn(`${emoji} [${type}]`, new Date().toISOString()); if (this.config.debugExtras && Array.isArray(this.config.debugExtras)) { - logFn(`[${this.config.debugExtras.join(' ')}]`); + logFn(`[${this.config.debugExtras.join(" ")}]`); } logFn( - '[message]', + "[message]", ..._.map(messages, (message) => - _.startsWith(message, '\n') - ? `\n ${message.replace(/\n/, '')}` + _.startsWith(message, "\n") + ? `\n ${message.replace(/\n/, "")}` : message, ), ); - logFn(trace.join('\n') + '\n---'); + logFn(trace.join("\n") + "\n---"); return; } console[type]( emoji, - ' ', + " ", ..._.map(messages, (message) => - _.startsWith(message, '\n') - ? `\n${emoji} ${message.replace(/\n/, '')}` + _.startsWith(message, "\n") + ? `\n${emoji} ${message.replace(/\n/, "")}` : message, ), ); @@ -70,8 +70,8 @@ class Logger { */ log = (...messages) => this.createLogMessage({ - type: 'log', - emojiName: ':sparkles:', + type: "log", + emojiName: ":sparkles:", messages, }); @@ -82,8 +82,8 @@ class Logger { */ event = (...messages) => this.createLogMessage({ - type: 'log', - emojiName: ':star:', + type: "log", + emojiName: ":star:", messages, }); @@ -94,8 +94,8 @@ class Logger { */ success = (...messages) => this.createLogMessage({ - type: 'log', - emojiName: ':white_check_mark:', + type: "log", + emojiName: ":white_check_mark:", messages, }); @@ -106,8 +106,8 @@ class Logger { */ warn = (...messages) => this.createLogMessage({ - type: 'warn', - emojiName: ':exclamation:', + type: "warn", + emojiName: ":exclamation:", messages, }); @@ -118,8 +118,8 @@ class Logger { */ error = (...messages) => this.createLogMessage({ - type: 'error', - emojiName: ':no_entry:', + type: "error", + emojiName: ":no_entry:", messages, }); @@ -132,8 +132,8 @@ class Logger { if (!this.config.debug) return; this.createLogMessage({ - type: 'debug', - emojiName: ':black_large_square:', + type: "debug", + emojiName: ":black_large_square:", messages, }); }; diff --git a/src/util/name-resolver.js b/src/util/name-resolver.js index 4671c560..5c816407 100644 --- a/src/util/name-resolver.js +++ b/src/util/name-resolver.js @@ -1,4 +1,4 @@ -const _ = require('lodash'); +const _ = require("lodash"); class NameResolver { reservedNames = []; @@ -51,14 +51,14 @@ class NameResolver { * @returns {string | null} */ resolve(variants, resolver, extras, shouldReserve = true) { - if (typeof resolver === 'function') { + if (typeof resolver === "function") { let usageName = null; while (usageName === null) { const variant = resolver(variants, extras); if (variant === undefined) { this.logger.warn( - 'unable to resolve name. current reserved names: ', + "unable to resolve name. current reserved names: ", this.reservedNames, ); return null; @@ -86,14 +86,14 @@ class NameResolver { } this.logger.debug( - 'trying to resolve name with using fallback name generator using variants', + "trying to resolve name with using fallback name generator using variants", variants, ); return this.resolve(variants, this.getFallbackName, extras); } this.logger.debug( - 'problem with reserving names. current reserved names: ', + "problem with reserving names. current reserved names: ", this.reservedNames, ); return null; diff --git a/src/util/object-assign.js b/src/util/object-assign.js index 8dde53c9..365c5a18 100644 --- a/src/util/object-assign.js +++ b/src/util/object-assign.js @@ -1,9 +1,9 @@ -const _ = require('lodash'); +const _ = require("lodash"); const objectAssign = (target, updaterFn) => { if (!updaterFn) return; const update = - typeof updaterFn === 'function' ? updaterFn(target) : updaterFn; + typeof updaterFn === "function" ? updaterFn(target) : updaterFn; const undefinedKeys = _.map( update, (value, key) => value === undefined && key, diff --git a/src/util/pascal-case.js b/src/util/pascal-case.js index a78aed50..1bb41c49 100644 --- a/src/util/pascal-case.js +++ b/src/util/pascal-case.js @@ -1,4 +1,4 @@ -const _ = require('lodash'); +const _ = require("lodash"); module.exports = { pascalCase: (value) => _.upperFirst(_.camelCase(value)), diff --git a/src/util/request.js b/src/util/request.js index bf22a16b..44db6c4e 100644 --- a/src/util/request.js +++ b/src/util/request.js @@ -1,6 +1,6 @@ -const _ = require('lodash'); -const https = require('https'); -const fetch = require('node-fetch-h2'); +const _ = require("lodash"); +const https = require("node:https"); +const fetch = require("node-fetch-h2"); class Request { /** @@ -31,7 +31,7 @@ class Request { */ const requestOptions = {}; - if (disableStrictSSL && !_.startsWith(url, 'http://')) { + if (disableStrictSSL && !_.startsWith(url, "http://")) { requestOptions.agent = new https.Agent({ rejectUnauthorized: false, }); @@ -49,7 +49,7 @@ class Request { return await response.text(); } catch (error) { const message = `error while fetching data from URL "${url}"`; - this.logger.error(message, 'response' in error ? error.response : error); + this.logger.error(message, "response" in error ? error.response : error); return message; } } diff --git a/tests/allSchemas.js b/tests/allSchemas.js index fdeb31cb..b94af4a7 100644 --- a/tests/allSchemas.js +++ b/tests/allSchemas.js @@ -1,4 +1,4 @@ -const { resolve } = require("path"); +const { resolve } = require("node:path"); const dotenv = require("dotenv"); const createSchemaInfos = require("./helpers/createSchemaInfos"); @@ -16,17 +16,31 @@ let allSchemas = [ ]; if (process.env.TEST_FILE_NAME) { - allSchemas = allSchemas.filter((schema) => schema.apiFileName === process.env.TEST_FILE_NAME); - console.warn("TEST ONLY", process.env.TEST_FILE_NAME, 'found:', allSchemas.map(it => it.apiFileName).join(', ') || ''); + allSchemas = allSchemas.filter( + (schema) => schema.apiFileName === process.env.TEST_FILE_NAME, + ); + console.warn( + "TEST ONLY", + process.env.TEST_FILE_NAME, + "found:", + allSchemas.map((it) => it.apiFileName).join(", ") || "", + ); } if (process.env.TEST_SCHEMA_VERSION) { - allSchemas = allSchemas.filter((schema) => schema.outputPath.endsWith(process.env.TEST_SCHEMA_VERSION)); - console.warn("TEST ONLY", process.env.TEST_SCHEMA_VERSION, 'found:', allSchemas.map(it => it.apiFileName).join(', ') || ''); + allSchemas = allSchemas.filter((schema) => + schema.outputPath.endsWith(process.env.TEST_SCHEMA_VERSION), + ); + console.warn( + "TEST ONLY", + process.env.TEST_SCHEMA_VERSION, + "found:", + allSchemas.map((it) => it.apiFileName).join(", ") || "", + ); } if (!allSchemas.length) { - console.warn("TEST SCHEMES NOT FOUND") + console.warn("TEST SCHEMES NOT FOUND"); } module.exports = allSchemas; diff --git a/tests/generate-extended.js b/tests/generate-extended.js index 1b98ce12..4bb4ef6e 100644 --- a/tests/generate-extended.js +++ b/tests/generate-extended.js @@ -1,5 +1,5 @@ const _ = require("lodash"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const dotenv = require("dotenv"); const allSchemas = require("./allSchemas"); const { generateApiForTest } = require("./helpers/generateApiForTest"); @@ -12,9 +12,14 @@ class GenerateExtendedError extends Error { const stackLines = _.split(this.stack, "\n"); const realStack = stackLines.slice(1); - const stackLineExtraSpace = (realStack[0] && realStack[0].split("at")[0]) || ""; + const stackLineExtraSpace = + (realStack[0] && realStack[0].split("at")[0]) || ""; - this.stack = [stackLines[0], `${stackLineExtraSpace}at ${resolve(outputPath, fileName)}`, ...realStack].join("\n"); + this.stack = [ + stackLines[0], + `${stackLineExtraSpace}at ${resolve(outputPath, fileName)}`, + ...realStack, + ].join("\n"); } } @@ -23,8 +28,8 @@ allSchemas.forEach(async ({ absolutePath, apiFileName, outputPath }) => { const input = absolutePath; const output = outputPath; - const typePrefix = 'IMySuperPrefix' - const typeSuffix = 'MySuperSuffix' + const typePrefix = "IMySuperPrefix"; + const typeSuffix = "MySuperSuffix"; await generateApiForTest({ name: name, @@ -50,30 +55,30 @@ allSchemas.forEach(async ({ absolutePath, apiFileName, outputPath }) => { if (modelType.name) { if (modelType.name.startsWith(`${typePrefix}${typePrefix}`)) { throw new GenerateExtendedError( - `[${outputPath}][${apiFileName}] modelType has prefix/suffix duplicates - ${modelType.name}`, - output, - name, + `[${outputPath}][${apiFileName}] modelType has prefix/suffix duplicates - ${modelType.name}`, + output, + name, ); } if (!modelType.name.startsWith(typePrefix)) { throw new GenerateExtendedError( - `[${outputPath}][${apiFileName}] modelType has not prefix/suffix - ${modelType.name}`, - output, - name, + `[${outputPath}][${apiFileName}] modelType has not prefix/suffix - ${modelType.name}`, + output, + name, ); } if (modelType.name.endsWith(`${typeSuffix}${typeSuffix}`)) { throw new GenerateExtendedError( - `[${outputPath}][${apiFileName}] modelType has prefix/suffix duplicates - ${modelType.name}`, - output, - name, + `[${outputPath}][${apiFileName}] modelType has prefix/suffix duplicates - ${modelType.name}`, + output, + name, ); } if (!modelType.name.endsWith(typeSuffix)) { throw new GenerateExtendedError( - `[${outputPath}][${apiFileName}] modelType has not prefix/suffix - ${modelType.name}`, - output, - name, + `[${outputPath}][${apiFileName}] modelType has not prefix/suffix - ${modelType.name}`, + output, + name, ); } } diff --git a/tests/helpers/assertGeneratedModule.js b/tests/helpers/assertGeneratedModule.js index 94b5dd3b..2e24e282 100644 --- a/tests/helpers/assertGeneratedModule.js +++ b/tests/helpers/assertGeneratedModule.js @@ -1,4 +1,4 @@ -const fs = require("fs"); +const fs = require("node:fs"); const gitDiff = require("git-diff"); const _ = require("lodash"); @@ -32,7 +32,10 @@ const assertGeneratedModule = (pathToModule1, pathToModule2) => { }; for (let i = 0; i < lines.length; i++) { const line = lines[i]; - if (line.startsWith(minusLinePrefix1) || line.startsWith(minusLinePrefix2)) { + if ( + line.startsWith(minusLinePrefix1) || + line.startsWith(minusLinePrefix2) + ) { lineStructs.push({ pos: i, id: Math.random().toString() + i, @@ -76,7 +79,10 @@ const assertGeneratedModule = (pathToModule1, pathToModule2) => { } const sortedLines = _.sortBy(_.uniqBy(computedLines, "id"), "pos"); - const maxLine = (sortedLines.map((v) => v.line).sort((a, b) => b.length - a.length)[0] || "").length; + const maxLine = ( + sortedLines.map((v) => v.line).sort((a, b) => b.length - a.length)[0] || + "" + ).length; const fixedLines = sortedLines.reduce((acc, computedLine, i, arr) => { const prev = arr[i - 1]; if ((prev && computedLine.pos - prev.pos > 10) || !i) { diff --git a/tests/helpers/createGeneratedApiInfos.js b/tests/helpers/createGeneratedApiInfos.js index 74902459..a3a22a5d 100644 --- a/tests/helpers/createGeneratedApiInfos.js +++ b/tests/helpers/createGeneratedApiInfos.js @@ -1,6 +1,7 @@ -const fs = require("fs"); -const { resolve } = require("path"); +const fs = require("node:fs"); +const { resolve } = require("node:path"); module.exports = (pathToApis) => - (fs.readdirSync(pathToApis) || []) - .map(fileName => resolve(pathToApis, fileName)) \ No newline at end of file + (fs.readdirSync(pathToApis) || []).map((fileName) => + resolve(pathToApis, fileName), + ); diff --git a/tests/helpers/createSchemaInfos.js b/tests/helpers/createSchemaInfos.js index eac996a1..a7ae4fd0 100644 --- a/tests/helpers/createSchemaInfos.js +++ b/tests/helpers/createSchemaInfos.js @@ -1,6 +1,6 @@ const _ = require("lodash"); -const fs = require("fs"); -const path = require("path"); +const fs = require("node:fs"); +const path = require("node:path"); /** * @@ -14,41 +14,57 @@ const path = require("path"); * }[]} */ const createSchemaInfos = ({ absolutePathToSchemas, absoluteOutputPath }) => { - return (fs.readdirSync(absolutePathToSchemas) || []).reduce((schemas, fileName) => { - if (fileName.endsWith(".yaml") || fileName.endsWith(".json") || fileName.endsWith(".yml")) { - const apiFileName = fileName.replace(/.(yaml|json|yml)/g, ".ts"); - const outputPath = absoluteOutputPath || path.resolve(__dirname, "./"); + return (fs.readdirSync(absolutePathToSchemas) || []).reduce( + (schemas, fileName) => { + if ( + fileName.endsWith(".yaml") || + fileName.endsWith(".json") || + fileName.endsWith(".yml") + ) { + const apiFileName = fileName.replace(/.(yaml|json|yml)/g, ".ts"); + const outputPath = absoluteOutputPath || path.resolve(__dirname, "./"); - schemas.push({ - absolutePath: path.resolve(absolutePathToSchemas, fileName), - schemaFileName: fileName, - apiFileName: apiFileName, - outputPath: outputPath, - Exception: class TestError extends Error { - constructor(message, ...datas) { - super(message); + schemas.push({ + absolutePath: path.resolve(absolutePathToSchemas, fileName), + schemaFileName: fileName, + apiFileName: apiFileName, + outputPath: outputPath, + Exception: class TestError extends Error { + constructor(message, ...datas) { + super(message); - const stackLines = _.split(this.stack, "\n"); - const realStack = stackLines.slice(1); - const stackLineExtraSpace = (realStack[0] && realStack[0].split("at")[0]) || ""; + const stackLines = _.split(this.stack, "\n"); + const realStack = stackLines.slice(1); + const stackLineExtraSpace = + (realStack[0] && realStack[0].split("at")[0]) || ""; - this.stack = [ - stackLines[0], - `${stackLineExtraSpace}at ${path.resolve(outputPath, apiFileName)}`, - ...realStack, - ].join("\n"); + this.stack = [ + stackLines[0], + `${stackLineExtraSpace}at ${path.resolve( + outputPath, + apiFileName, + )}`, + ...realStack, + ].join("\n"); - console.error(stackLines[0], ...datas); - console.error(`${stackLineExtraSpace}at ${path.resolve(outputPath, apiFileName)}`); - console.error(realStack.join("\n")); - process.exit(1); - } - }, - }); - } + console.error(stackLines[0], ...datas); + console.error( + `${stackLineExtraSpace}at ${path.resolve( + outputPath, + apiFileName, + )}`, + ); + console.error(realStack.join("\n")); + process.exit(1); + } + }, + }); + } - return schemas; - }, []); + return schemas; + }, + [], + ); }; module.exports = createSchemaInfos; diff --git a/tests/helpers/specGenerateOptions.js b/tests/helpers/specGenerateOptions.js index 4a461581..f57b2c9f 100644 --- a/tests/helpers/specGenerateOptions.js +++ b/tests/helpers/specGenerateOptions.js @@ -1,6 +1,6 @@ -const path = require("path") +const path = require("node:path"); module.exports = { name: "Api.ts", input: path.resolve(__dirname, "../schemas/v2.0/petstore-simple.yaml"), -} \ No newline at end of file +}; diff --git a/tests/helpers/validateGeneratedModule.js b/tests/helpers/validateGeneratedModule.js index 1af08d5e..2e796a8e 100644 --- a/tests/helpers/validateGeneratedModule.js +++ b/tests/helpers/validateGeneratedModule.js @@ -19,15 +19,29 @@ function compile(fileNames) { let program = ts.createProgram(fileNames, compilerOptions); let emitResult = program.emit(); - let allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); + let allDiagnostics = ts + .getPreEmitDiagnostics(program) + .concat(emitResult.diagnostics); allDiagnostics.forEach((diagnostic) => { if (diagnostic.file) { - let { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); - let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); - console.error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); + let { line, character } = ts.getLineAndCharacterOfPosition( + diagnostic.file, + diagnostic.start, + ); + let message = ts.flattenDiagnosticMessageText( + diagnostic.messageText, + "\n", + ); + console.error( + `${diagnostic.file.fileName} (${line + 1},${ + character + 1 + }): ${message}`, + ); } else { - console.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")); + console.error( + ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), + ); } }); diff --git a/tests/spec/additional-properties-2.0/test.js b/tests/spec/additional-properties-2.0/test.js index cb6eb22e..b4702dc7 100644 --- a/tests/spec/additional-properties-2.0/test.js +++ b/tests/spec/additional-properties-2.0/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/another-array-type/test.js b/tests/spec/another-array-type/test.js index 901a8e2e..3ae98179 100644 --- a/tests/spec/another-array-type/test.js +++ b/tests/spec/another-array-type/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { anotherArrayType: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/another-query-params/test.js b/tests/spec/another-query-params/test.js index 5d8496ca..4dda1565 100644 --- a/tests/spec/another-query-params/test.js +++ b/tests/spec/another-query-params/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/axios/test.js b/tests/spec/axios/test.js index ed47b590..8e84da14 100644 --- a/tests/spec/axios/test.js +++ b/tests/spec/axios/test.js @@ -1,10 +1,12 @@ -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const { generateApiForTest } = require("../../helpers/generateApiForTest"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { httpClientType: "axios", }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/axiosSingleHttpClient/test.js b/tests/spec/axiosSingleHttpClient/test.js index 18bf067f..dce152fa 100644 --- a/tests/spec/axiosSingleHttpClient/test.js +++ b/tests/spec/axiosSingleHttpClient/test.js @@ -1,10 +1,12 @@ -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const { generateApiForTest } = require("../../helpers/generateApiForTest"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -18,6 +20,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { httpClientType: "axios", }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/cli/test.js b/tests/spec/cli/test.js index a9d9df66..837b19c3 100644 --- a/tests/spec/cli/test.js +++ b/tests/spec/cli/test.js @@ -1,6 +1,9 @@ const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -validateGeneratedModule(resolve(__dirname, `./schema.ts`)); -assertGeneratedModule(resolve(__dirname, `./schema.ts`), resolve(__dirname, `./expected.ts`)); +validateGeneratedModule(resolve(__dirname, "./schema.ts")); +assertGeneratedModule( + resolve(__dirname, "./schema.ts"), + resolve(__dirname, "./expected.ts"), +); diff --git a/tests/spec/const-keyword/test.js b/tests/spec/const-keyword/test.js index ff7785e3..a46e7796 100644 --- a/tests/spec/const-keyword/test.js +++ b/tests/spec/const-keyword/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/custom-extensions/test.js b/tests/spec/custom-extensions/test.js index 877d7a26..2dc72722 100644 --- a/tests/spec/custom-extensions/test.js +++ b/tests/spec/custom-extensions/test.js @@ -1,10 +1,12 @@ const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const { generateApiForTest } = require("../../helpers/generateApiForTest"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -15,6 +17,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { output: resolve(__dirname, "./"), }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, "./expected.ts")); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/defaultAsSuccess/test.js b/tests/spec/defaultAsSuccess/test.js index c6eac255..b8f5b182 100644 --- a/tests/spec/defaultAsSuccess/test.js +++ b/tests/spec/defaultAsSuccess/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { defaultResponseAsSuccess: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/defaultResponse/test.js b/tests/spec/defaultResponse/test.js index afd5a8c8..255e03c3 100644 --- a/tests/spec/defaultResponse/test.js +++ b/tests/spec/defaultResponse/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { defaultResponseType: "unknown", }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/deprecated/test.js b/tests/spec/deprecated/test.js index d1db7fd0..fab46f43 100644 --- a/tests/spec/deprecated/test.js +++ b/tests/spec/deprecated/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { queryParamsWithBrackets: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/discriminator/test.js b/tests/spec/discriminator/test.js index 67870298..3f98388e 100644 --- a/tests/spec/discriminator/test.js +++ b/tests/spec/discriminator/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/dot-path-params/test.js b/tests/spec/dot-path-params/test.js index c654f209..34c5c833 100644 --- a/tests/spec/dot-path-params/test.js +++ b/tests/spec/dot-path-params/test.js @@ -1,6 +1,6 @@ const _ = require("lodash"); const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); @@ -20,6 +20,9 @@ schemas.forEach(({ absolutePath, apiFileName, Exception }) => { generateClient: true, }).then((output) => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/enumNamesAsValues/test.js b/tests/spec/enumNamesAsValues/test.js index 63eddba0..5433d3d1 100644 --- a/tests/spec/enumNamesAsValues/test.js +++ b/tests/spec/enumNamesAsValues/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { enumNamesAsValues: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/enums-2.0/test.js b/tests/spec/enums-2.0/test.js index ebc7be6e..802558e7 100644 --- a/tests/spec/enums-2.0/test.js +++ b/tests/spec/enums-2.0/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -20,6 +22,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/extra-templates/test.js b/tests/spec/extra-templates/test.js index 42b667bc..ce7d4ba9 100644 --- a/tests/spec/extra-templates/test.js +++ b/tests/spec/extra-templates/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -26,7 +28,10 @@ schemas.forEach(({ absolutePath, apiFileName }) => { }, ], }).then(() => { - validateGeneratedModule(resolve(__dirname, `./external-template-name.ts`)); - assertGeneratedModule(resolve(__dirname, `./external-template-name.ts`), resolve(__dirname, `./expected.ts`)); + validateGeneratedModule(resolve(__dirname, "./external-template-name.ts")); + assertGeneratedModule( + resolve(__dirname, "./external-template-name.ts"), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/extract-enums/test.js b/tests/spec/extract-enums/test.js index 77e47fd1..3156738d 100644 --- a/tests/spec/extract-enums/test.js +++ b/tests/spec/extract-enums/test.js @@ -1,5 +1,5 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); @@ -7,48 +7,58 @@ const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const schemasv2 = resolve(__dirname, "./v2.0"); const schemasv3 = resolve(__dirname, "./v3.0"); -createSchemaInfos({ absolutePathToSchemas: schemasv2 }).forEach(({ absolutePath, apiFileName }) => { - generateApiForTest({ - testName: "--extract-enums (v2.0) option test", - silent: true, - name: apiFileName, - input: absolutePath, - output: resolve(schemasv2, "./"), - extractEnums: true, - extractRequestParams: true, - extractResponseBody: true, - extractResponseError: true, - generateClient: false, - fixInvalidEnumKeyPrefix: "InvalidKey", - enumKeyPrefix: "EnumKeyPrefix", - enumKeySuffix: "EnumKeySuffix", - typePrefix: "TypeNamePrefix", - typeSuffix: "TypeNameSuffix", - }).then(() => { - validateGeneratedModule(resolve(schemasv2, `./${apiFileName}`)); - assertGeneratedModule(resolve(schemasv2, `./${apiFileName}`), resolve(schemasv2, `./expected.ts`)); - }); -}); +createSchemaInfos({ absolutePathToSchemas: schemasv2 }).forEach( + ({ absolutePath, apiFileName }) => { + generateApiForTest({ + testName: "--extract-enums (v2.0) option test", + silent: true, + name: apiFileName, + input: absolutePath, + output: resolve(schemasv2, "./"), + extractEnums: true, + extractRequestParams: true, + extractResponseBody: true, + extractResponseError: true, + generateClient: false, + fixInvalidEnumKeyPrefix: "InvalidKey", + enumKeyPrefix: "EnumKeyPrefix", + enumKeySuffix: "EnumKeySuffix", + typePrefix: "TypeNamePrefix", + typeSuffix: "TypeNameSuffix", + }).then(() => { + validateGeneratedModule(resolve(schemasv2, `./${apiFileName}`)); + assertGeneratedModule( + resolve(schemasv2, `./${apiFileName}`), + resolve(schemasv2, "./expected.ts"), + ); + }); + }, +); -createSchemaInfos({ absolutePathToSchemas: resolve(schemasv3, "./") }).forEach(({ absolutePath, apiFileName }) => { - generateApiForTest({ - testName: "--extract-enums (v3.0) option test", - silent: true, - name: apiFileName, - input: absolutePath, - output: resolve(schemasv3, "./"), - extractEnums: true, - extractRequestParams: true, - extractResponseBody: true, - extractResponseError: true, - generateClient: false, - fixInvalidEnumKeyPrefix: "InvalidKey", - enumKeyPrefix: "EnumKeyPrefix", - enumKeySuffix: "EnumKeySuffix", - typePrefix: "TypeNamePrefix", - typeSuffix: "TypeNameSuffix", - }).then(() => { - validateGeneratedModule(resolve(schemasv3, `./${apiFileName}`)); - assertGeneratedModule(resolve(schemasv3, `./${apiFileName}`), resolve(schemasv3, `./expected.ts`)); - }); -}); +createSchemaInfos({ absolutePathToSchemas: resolve(schemasv3, "./") }).forEach( + ({ absolutePath, apiFileName }) => { + generateApiForTest({ + testName: "--extract-enums (v3.0) option test", + silent: true, + name: apiFileName, + input: absolutePath, + output: resolve(schemasv3, "./"), + extractEnums: true, + extractRequestParams: true, + extractResponseBody: true, + extractResponseError: true, + generateClient: false, + fixInvalidEnumKeyPrefix: "InvalidKey", + enumKeyPrefix: "EnumKeyPrefix", + enumKeySuffix: "EnumKeySuffix", + typePrefix: "TypeNamePrefix", + typeSuffix: "TypeNameSuffix", + }).then(() => { + validateGeneratedModule(resolve(schemasv3, `./${apiFileName}`)); + assertGeneratedModule( + resolve(schemasv3, `./${apiFileName}`), + resolve(schemasv3, "./expected.ts"), + ); + }); + }, +); diff --git a/tests/spec/extractRequestBody/test.js b/tests/spec/extractRequestBody/test.js index 4dcaf1b8..96cd716b 100644 --- a/tests/spec/extractRequestBody/test.js +++ b/tests/spec/extractRequestBody/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { typeSuffix: "TTT", }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/extractRequestParams/test.js b/tests/spec/extractRequestParams/test.js index e1d6c4da..e89d798b 100644 --- a/tests/spec/extractRequestParams/test.js +++ b/tests/spec/extractRequestParams/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { extractRequestParams: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/extractResponseBody/test.js b/tests/spec/extractResponseBody/test.js index 1bdd8f62..1f3a9406 100644 --- a/tests/spec/extractResponseBody/test.js +++ b/tests/spec/extractResponseBody/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { typeSuffix: "TTT", }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/extractResponseError/test.js b/tests/spec/extractResponseError/test.js index 714f26d1..697342e0 100644 --- a/tests/spec/extractResponseError/test.js +++ b/tests/spec/extractResponseError/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { typeSuffix: "TTT", }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/js/schema.d.ts b/tests/spec/js/schema.d.ts index 42997921..80295387 100644 --- a/tests/spec/js/schema.d.ts +++ b/tests/spec/js/schema.d.ts @@ -1801,14 +1801,19 @@ export interface FullRequestParams extends Omit { /** request cancellation token */ cancelToken?: CancelToken; } -export type RequestParams = Omit; +export type RequestParams = Omit< + FullRequestParams, + "body" | "method" | "query" | "path" +>; export interface ApiConfig { baseUrl?: string; baseApiParams?: Omit; - securityWorker?: (securityData: SecurityDataType | null) => Promise | RequestParams | void; + securityWorker?: ( + securityData: SecurityDataType | null, + ) => Promise | RequestParams | void; customFetch?: typeof fetch; } -export interface HttpResponse extends Response { +export interface HttpResponse extends Response { data: D; error: E; } @@ -1834,8 +1839,13 @@ export declare class HttpClient { protected toQueryString(rawQuery?: QueryParamsType): string; protected addQueryParams(rawQuery?: QueryParamsType): string; private contentFormatters; - protected mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams; - protected createAbortSignal: (cancelToken: CancelToken) => AbortSignal | undefined; + protected mergeRequestParams( + params1: RequestParams, + params2?: RequestParams, + ): RequestParams; + protected createAbortSignal: ( + cancelToken: CancelToken, + ) => AbortSignal | undefined; abortRequest: (cancelToken: CancelToken) => void; request: ({ body, @@ -1858,7 +1868,9 @@ export declare class HttpClient { * * Powerful collaboration, code review, and code management for open source and private projects. */ -export declare class Api extends HttpClient { +export declare class Api< + SecurityDataType, +> extends HttpClient { emojis: { /** * @description Lists all the emojis available to use on GitHub. @@ -1909,7 +1921,10 @@ export declare class Api extends HttpClient Promise>; + gistsCreate: ( + body: PostGist, + params?: RequestParams, + ) => Promise>; /** * @description List all public gists. * @@ -1948,42 +1963,63 @@ export declare class Api extends HttpClient Promise>; + gistsDelete: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a single gist. * * @name GistsDetail * @request GET:/gists/{id} */ - gistsDetail: (id: number, params?: RequestParams) => Promise>; + gistsDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Edit a gist. * * @name GistsPartialUpdate * @request PATCH:/gists/{id} */ - gistsPartialUpdate: (id: number, body: PatchGist, params?: RequestParams) => Promise>; + gistsPartialUpdate: ( + id: number, + body: PatchGist, + params?: RequestParams, + ) => Promise>; /** * @description List comments on a gist. * * @name CommentsDetail * @request GET:/gists/{id}/comments */ - commentsDetail: (id: number, params?: RequestParams) => Promise>; + commentsDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Create a commen * * @name CommentsCreate * @request POST:/gists/{id}/comments */ - commentsCreate: (id: number, body: CommentBody, params?: RequestParams) => Promise>; + commentsCreate: ( + id: number, + body: CommentBody, + params?: RequestParams, + ) => Promise>; /** * @description Delete a comment. * * @name CommentsDelete * @request DELETE:/gists/{id}/comments/{commentId} */ - commentsDelete: (id: number, commentId: number, params?: RequestParams) => Promise>; + commentsDelete: ( + id: number, + commentId: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a single comment. * @@ -1992,7 +2028,11 @@ export declare class Api extends HttpClient Promise>; + commentsDetail2: ( + id: number, + commentId: number, + params?: RequestParams, + ) => Promise>; /** * @description Edit a comment. * @@ -2011,28 +2051,40 @@ export declare class Api extends HttpClient Promise>; + forksCreate: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Unstar a gist. * * @name StarDelete * @request DELETE:/gists/{id}/star */ - starDelete: (id: number, params?: RequestParams) => Promise>; + starDelete: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Check if a gist is starred. * * @name StarDetail * @request GET:/gists/{id}/star */ - starDetail: (id: number, params?: RequestParams) => Promise>; + starDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Star a gist. * * @name StarUpdate * @request PUT:/gists/{id}/star */ - starUpdate: (id: number, params?: RequestParams) => Promise>; + starUpdate: ( + id: number, + params?: RequestParams, + ) => Promise>; }; gitignore: { /** @@ -2041,14 +2093,19 @@ export declare class Api extends HttpClient Promise>; + templatesList: ( + params?: RequestParams, + ) => Promise>; /** * @description Get a single template. * * @name TemplatesDetail * @request GET:/gitignore/templates/{language} */ - templatesDetail: (language: string, params?: RequestParams) => Promise>; + templatesDetail: ( + language: string, + params?: RequestParams, + ) => Promise>; }; issues: { /** @@ -2128,7 +2185,10 @@ export declare class Api extends HttpClient Promise>; + userEmailDetail: ( + email: string, + params?: RequestParams, + ) => Promise>; /** * @description Find users by keyword. * @@ -2159,7 +2219,10 @@ export declare class Api extends HttpClient Promise>; + markdownCreate: ( + body: Markdown, + params?: RequestParams, + ) => Promise>; /** * @description Render a Markdown document in raw mode * @@ -2184,7 +2247,11 @@ export declare class Api extends HttpClient Promise>; + eventsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; }; notifications: { /** @@ -2216,35 +2283,50 @@ export declare class Api extends HttpClient Promise>; + notificationsUpdate: ( + body: NotificationMarkRead, + params?: RequestParams, + ) => Promise>; /** * @description View a single thread. * * @name ThreadsDetail * @request GET:/notifications/threads/{id} */ - threadsDetail: (id: number, params?: RequestParams) => Promise>; + threadsDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Mark a thread as read * * @name ThreadsPartialUpdate * @request PATCH:/notifications/threads/{id} */ - threadsPartialUpdate: (id: number, params?: RequestParams) => Promise>; + threadsPartialUpdate: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Delete a Thread Subscription. * * @name ThreadsSubscriptionDelete * @request DELETE:/notifications/threads/{id}/subscription */ - threadsSubscriptionDelete: (id: number, params?: RequestParams) => Promise>; + threadsSubscriptionDelete: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a Thread Subscription. * * @name ThreadsSubscriptionDetail * @request GET:/notifications/threads/{id}/subscription */ - threadsSubscriptionDetail: (id: number, params?: RequestParams) => Promise>; + threadsSubscriptionDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Set a Thread Subscription. This lets you subscribe to a thread, or ignore it. Subscribing to a thread is unnecessary if the user is already subscribed to the repository. Ignoring a thread will mute all future notifications (until you comment or get @mentioned). * @@ -2264,7 +2346,10 @@ export declare class Api extends HttpClient Promise>; + orgsDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description Edit an Organization. * @@ -2282,7 +2367,10 @@ export declare class Api extends HttpClient Promise>; + eventsDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description List issues. List all issues for a given organization for the authenticated user. * @@ -2320,14 +2408,21 @@ export declare class Api extends HttpClient Promise>; + membersDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description Remove a member. Removing a user from this list will remove them from all teams and they will no longer have any access to the organization's repositories. * * @name MembersDelete * @request DELETE:/orgs/{org}/members/{username} */ - membersDelete: (org: string, username: string, params?: RequestParams) => Promise>; + membersDelete: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if a user is, publicly or privately, a member of the organization. * @@ -2336,21 +2431,32 @@ export declare class Api extends HttpClient Promise>; + membersDetail2: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Public members list. Members of an organization can choose to have their membership publicized or not. * * @name PublicMembersDetail * @request GET:/orgs/{org}/public_members */ - publicMembersDetail: (org: string, params?: RequestParams) => Promise>; + publicMembersDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description Conceal a user's membership. * * @name PublicMembersDelete * @request DELETE:/orgs/{org}/public_members/{username} */ - publicMembersDelete: (org: string, username: string, params?: RequestParams) => Promise>; + publicMembersDelete: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Check public membership. * @@ -2359,14 +2465,22 @@ export declare class Api extends HttpClient Promise>; + publicMembersDetail2: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Publicize a user's membership. * * @name PublicMembersUpdate * @request PUT:/orgs/{org}/public_members/{username} */ - publicMembersUpdate: (org: string, username: string, params?: RequestParams) => Promise>; + publicMembersUpdate: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List repositories for the specified org. * @@ -2387,21 +2501,32 @@ export declare class Api extends HttpClient Promise>; + reposCreate: ( + org: string, + body: PostRepo, + params?: RequestParams, + ) => Promise>; /** * @description List teams. * * @name TeamsDetail * @request GET:/orgs/{org}/teams */ - teamsDetail: (org: string, params?: RequestParams) => Promise>; + teamsDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description Create team. In order to create a team, the authenticated user must be an owner of organization. * * @name TeamsCreate * @request POST:/orgs/{org}/teams */ - teamsCreate: (org: string, body: OrgTeamsPost, params?: RequestParams) => Promise>; + teamsCreate: ( + org: string, + body: OrgTeamsPost, + params?: RequestParams, + ) => Promise>; }; rateLimit: { /** @@ -2410,7 +2535,9 @@ export declare class Api extends HttpClient Promise>; + rateLimitList: ( + params?: RequestParams, + ) => Promise>; }; repos: { /** @@ -2419,14 +2546,22 @@ export declare class Api extends HttpClient Promise>; + reposDelete: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get repository. * * @name ReposDetail * @request GET:/repos/{owner}/{repo} */ - reposDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + reposDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Edit repository. * @@ -2445,7 +2580,11 @@ export declare class Api extends HttpClient Promise>; + assigneesDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Check assignee. You may also check to see if a particular user is an assignee for a repository. * @@ -2466,7 +2605,11 @@ export declare class Api extends HttpClient Promise>; + branchesDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get Branch * @@ -2487,7 +2630,11 @@ export declare class Api extends HttpClient Promise>; + collaboratorsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Remove collaborator. * @@ -2532,7 +2679,11 @@ export declare class Api extends HttpClient Promise>; + commentsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Delete a commit comment * @@ -2776,7 +2927,11 @@ export declare class Api extends HttpClient Promise>; + downloadsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Deprecated. Delete a download. * @@ -2811,7 +2966,11 @@ export declare class Api extends HttpClient Promise>; + eventsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description List forks. * @@ -2893,7 +3052,11 @@ export declare class Api extends HttpClient Promise>; + gitRefsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a Reference * @@ -3003,7 +3166,11 @@ export declare class Api extends HttpClient Promise>; + hooksDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a hook. * @@ -3335,7 +3502,11 @@ export declare class Api extends HttpClient Promise>; + keysDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a key. * @@ -3380,7 +3551,11 @@ export declare class Api extends HttpClient Promise>; + labelsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a label. * @@ -3438,7 +3613,11 @@ export declare class Api extends HttpClient Promise>; + languagesDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Perform a merge. * @@ -3794,7 +3973,11 @@ export declare class Api extends HttpClient Promise>; + releasesDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a release Users with push access to the repository can create a release. * @@ -3903,7 +4086,11 @@ export declare class Api extends HttpClient Promise>; + stargazersDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get the number of additions and deletions per week. Returns a weekly aggregate of the number of additions and deletions pushed to a repository. * @@ -3990,14 +4177,22 @@ export declare class Api extends HttpClient Promise>; + subscribersDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Delete a Repository Subscription. * * @name SubscriptionDelete * @request DELETE:/repos/{owner}/{repo}/subscription */ - subscriptionDelete: (owner: string, repo: string, params?: RequestParams) => Promise>; + subscriptionDelete: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get a Repository Subscription. * @@ -4027,21 +4222,33 @@ export declare class Api extends HttpClient Promise>; + tagsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get list of teams * * @name TeamsDetail * @request GET:/repos/{owner}/{repo}/teams */ - teamsDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + teamsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description List Stargazers. New implementation. * * @name WatchersDetail * @request GET:/repos/{owner}/{repo}/watchers */ - watchersDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + watchersDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get archive link. This method will return a 302 to a URL to download a tarball or zipball archive for a repository. Please make sure your HTTP framework is configured to follow redirects or you will need to use the Location header to make a second GET request. Note: For private repositories, these links are temporary and expire quickly. * @@ -4210,28 +4417,41 @@ export declare class Api extends HttpClient Promise>; + teamsDelete: ( + teamId: number, + params?: RequestParams, + ) => Promise>; /** * @description Get team. * * @name TeamsDetail * @request GET:/teams/{teamId} */ - teamsDetail: (teamId: number, params?: RequestParams) => Promise>; + teamsDetail: ( + teamId: number, + params?: RequestParams, + ) => Promise>; /** * @description Edit team. In order to edit a team, the authenticated user must be an owner of the org that the team is associated with. * * @name TeamsPartialUpdate * @request PATCH:/teams/{teamId} */ - teamsPartialUpdate: (teamId: number, body: EditTeam, params?: RequestParams) => Promise>; + teamsPartialUpdate: ( + teamId: number, + body: EditTeam, + params?: RequestParams, + ) => Promise>; /** * @description List team members. In order to list members in a team, the authenticated user must be a member of the team. * * @name MembersDetail * @request GET:/teams/{teamId}/members */ - membersDetail: (teamId: number, params?: RequestParams) => Promise>; + membersDetail: ( + teamId: number, + params?: RequestParams, + ) => Promise>; /** * @description The "Remove team member" API is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Remove team membership API instead. It allows you to remove both active and pending memberships. Remove team member. In order to remove a user from a team, the authenticated user must have 'admin' permissions to the team or be an owner of the org that the team is associated with. NOTE This does not delete the user, it just remove them from the team. * @@ -4239,7 +4459,11 @@ export declare class Api extends HttpClient Promise>; + membersDelete: ( + teamId: number, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description The "Get team member" API is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Get team membership API instead. It allows you to get both active and pending memberships. Get team member. In order to get if a user is a member of a team, the authenticated user mus be a member of the team. * @@ -4249,7 +4473,11 @@ export declare class Api extends HttpClient Promise>; + membersDetail2: ( + teamId: number, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description The API (described below) is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Add team membership API instead. It allows you to invite new organization members to your teams. Add team member. In order to add a user to a team, the authenticated user must have 'admin' permissions to the team or be an owner of the org that the team is associated with. * @@ -4268,7 +4496,11 @@ export declare class Api extends HttpClient Promise>; + membershipsDelete: ( + teamId: number, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Get team membership. In order to get a user's membership with a team, the authenticated user must be a member of the team or an owner of the team's organization. * @@ -4297,7 +4529,10 @@ export declare class Api extends HttpClient Promise>; + reposDetail: ( + teamId: number, + params?: RequestParams, + ) => Promise>; /** * @description In order to remove a repository from a team, the authenticated user must be an owner of the org that the team is associated with. NOTE: This does not delete the repository, it just removes it from the team. * @@ -4351,63 +4586,87 @@ export declare class Api extends HttpClient Promise>; + userPartialUpdate: ( + body: UserUpdate, + params?: RequestParams, + ) => Promise>; /** * @description Delete email address(es). You can include a single email address or an array of addresses. * * @name EmailsDelete * @request DELETE:/user/emails */ - emailsDelete: (body: UserEmails, params?: RequestParams) => Promise>; + emailsDelete: ( + body: UserEmails, + params?: RequestParams, + ) => Promise>; /** * @description List email addresses for a user. In the final version of the API, this method will return an array of hashes with extended information for each email address indicating if the address has been verified and if it's primary email address for GitHub. Until API v3 is finalized, use the application/vnd.github.v3 media type to get other response format. * * @name EmailsList * @request GET:/user/emails */ - emailsList: (params?: RequestParams) => Promise>; + emailsList: ( + params?: RequestParams, + ) => Promise>; /** * @description Add email address(es). You can post a single email address or an array of addresses. * * @name EmailsCreate * @request POST:/user/emails */ - emailsCreate: (body: EmailsPost, params?: RequestParams) => Promise>; + emailsCreate: ( + body: EmailsPost, + params?: RequestParams, + ) => Promise>; /** * @description List the authenticated user's followers * * @name FollowersList * @request GET:/user/followers */ - followersList: (params?: RequestParams) => Promise>; + followersList: ( + params?: RequestParams, + ) => Promise>; /** * @description List who the authenticated user is following. * * @name FollowingList * @request GET:/user/following */ - followingList: (params?: RequestParams) => Promise>; + followingList: ( + params?: RequestParams, + ) => Promise>; /** * @description Unfollow a user. Unfollowing a user requires the user to be logged in and authenticated with basic auth or OAuth with the user:follow scope. * * @name FollowingDelete * @request DELETE:/user/following/{username} */ - followingDelete: (username: string, params?: RequestParams) => Promise>; + followingDelete: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if you are following a user. * * @name FollowingDetail * @request GET:/user/following/{username} */ - followingDetail: (username: string, params?: RequestParams) => Promise>; + followingDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Follow a user. Following a user requires the user to be logged in and authenticated with basic auth or OAuth with the user:follow scope. * * @name FollowingUpdate * @request PUT:/user/following/{username} */ - followingUpdate: (username: string, params?: RequestParams) => Promise>; + followingUpdate: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List issues. List all issues across owned and member repositories for the authenticated user. * @@ -4444,35 +4703,48 @@ export declare class Api extends HttpClient Promise>; + keysList: ( + params?: RequestParams, + ) => Promise>; /** * @description Create a public key. * * @name KeysCreate * @request POST:/user/keys */ - keysCreate: (body: UserKeysPost, params?: RequestParams) => Promise>; + keysCreate: ( + body: UserKeysPost, + params?: RequestParams, + ) => Promise>; /** * @description Delete a public key. Removes a public key. Requires that you are authenticated via Basic Auth or via OAuth with at least admin:public_key scope. * * @name KeysDelete * @request DELETE:/user/keys/{keyId} */ - keysDelete: (keyId: number, params?: RequestParams) => Promise>; + keysDelete: ( + keyId: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a single public key. * * @name KeysDetail * @request GET:/user/keys/{keyId} */ - keysDetail: (keyId: number, params?: RequestParams) => Promise>; + keysDetail: ( + keyId: number, + params?: RequestParams, + ) => Promise>; /** * @description List public and private organizations for the authenticated user. * * @name OrgsList * @request GET:/user/orgs */ - orgsList: (params?: RequestParams) => Promise>; + orgsList: ( + params?: RequestParams, + ) => Promise>; /** * @description List repositories for the authenticated user. Note that this does not include repositories owned by organizations which the user can access. You can lis user organizations and list organization repositories separately. * @@ -4492,7 +4764,10 @@ export declare class Api extends HttpClient Promise>; + reposCreate: ( + body: PostRepo, + params?: RequestParams, + ) => Promise>; /** * @description List repositories being starred by the authenticated user. * @@ -4514,28 +4789,42 @@ export declare class Api extends HttpClient Promise>; + starredDelete: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if you are starring a repository. * * @name StarredDetail * @request GET:/user/starred/{owner}/{repo} */ - starredDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + starredDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Star a repository. * * @name StarredUpdate * @request PUT:/user/starred/{owner}/{repo} */ - starredUpdate: (owner: string, repo: string, params?: RequestParams) => Promise>; + starredUpdate: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description List repositories being watched by the authenticated user. * * @name SubscriptionsList * @request GET:/user/subscriptions */ - subscriptionsList: (params?: RequestParams) => Promise>; + subscriptionsList: ( + params?: RequestParams, + ) => Promise>; /** * @description Stop watching a repository * @@ -4543,7 +4832,11 @@ export declare class Api extends HttpClient Promise>; + subscriptionsDelete: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if you are watching a repository. * @@ -4551,7 +4844,11 @@ export declare class Api extends HttpClient Promise>; + subscriptionsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Watch a repository. * @@ -4559,14 +4856,20 @@ export declare class Api extends HttpClient Promise>; + subscriptionsUpdate: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description List all of the teams across all of the organizations to which the authenticated user belongs. This method requires user or repo scope when authenticating via OAuth. * * @name TeamsList * @request GET:/user/teams */ - teamsList: (params?: RequestParams) => Promise>; + teamsList: ( + params?: RequestParams, + ) => Promise>; }; users: { /** @@ -4588,28 +4891,41 @@ export declare class Api extends HttpClient Promise>; + usersDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description If you are authenticated as the given user, you will see your private events. Otherwise, you'll only see public events. * * @name EventsDetail * @request GET:/users/{username}/events */ - eventsDetail: (username: string, params?: RequestParams) => Promise>; + eventsDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description This is the user's organization dashboard. You must be authenticated as the user to view this. * * @name EventsOrgsDetail * @request GET:/users/{username}/events/orgs/{org} */ - eventsOrgsDetail: (username: string, org: string, params?: RequestParams) => Promise>; + eventsOrgsDetail: ( + username: string, + org: string, + params?: RequestParams, + ) => Promise>; /** * @description List a user's followers * * @name FollowersDetail * @request GET:/users/{username}/followers */ - followersDetail: (username: string, params?: RequestParams) => Promise>; + followersDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if one user follows another. * @@ -4644,28 +4960,40 @@ export declare class Api extends HttpClient Promise>; + keysDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List all public organizations for a user. * * @name OrgsDetail * @request GET:/users/{username}/orgs */ - orgsDetail: (username: string, params?: RequestParams) => Promise>; + orgsDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description These are events that you'll only see public events. * * @name ReceivedEventsDetail * @request GET:/users/{username}/received_events */ - receivedEventsDetail: (username: string, params?: RequestParams) => Promise>; + receivedEventsDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List public events that a user has received * * @name ReceivedEventsPublicDetail * @request GET:/users/{username}/received_events/public */ - receivedEventsPublicDetail: (username: string, params?: RequestParams) => Promise>; + receivedEventsPublicDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List public repositories for the specified user. * @@ -4686,14 +5014,19 @@ export declare class Api extends HttpClient Promise>; + starredDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List repositories being watched by a user. * * @name SubscriptionsDetail * @request GET:/users/{username}/subscriptions */ - subscriptionsDetail: (username: string, params?: RequestParams) => Promise>; + subscriptionsDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; }; } -export {}; diff --git a/tests/spec/js/schema.js b/tests/spec/js/schema.js index bb353961..fbc1fc59 100644 --- a/tests/spec/js/schema.js +++ b/tests/spec/js/schema.js @@ -9,8 +9,8 @@ * --------------------------------------------------------------- */ -export var ContentType; -(function (ContentType) { +export let ContentType; +((ContentType) => { ContentType["Json"] = "application/json"; ContentType["FormData"] = "multipart/form-data"; ContentType["UrlEncoded"] = "application/x-www-form-urlencoded"; @@ -36,7 +36,9 @@ export class HttpClient { }; encodeQueryParam(key, value) { const encodedKey = encodeURIComponent(key); - return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`; + return `${encodedKey}=${encodeURIComponent( + typeof value === "number" ? value : `${value}`, + )}`; } addQueryParam(query, key) { return this.encodeQueryParam(key, query[key]); @@ -47,9 +49,15 @@ export class HttpClient { } toQueryString(rawQuery) { const query = rawQuery || {}; - const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]); + const keys = Object.keys(query).filter( + (key) => "undefined" !== typeof query[key], + ); return keys - .map((key) => (Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key))) + .map((key) => + Array.isArray(query[key]) + ? this.addArrayQueryParam(query, key) + : this.addQueryParam(query, key), + ) .join("&"); } addQueryParams(rawQuery) { @@ -58,8 +66,13 @@ export class HttpClient { } contentFormatters = { [ContentType.Json]: (input) => - input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input, - [ContentType.Text]: (input) => (input !== null && typeof input !== "string" ? JSON.stringify(input) : input), + input !== null && (typeof input === "object" || typeof input === "string") + ? JSON.stringify(input) + : input, + [ContentType.Text]: (input) => + input !== null && typeof input !== "string" + ? JSON.stringify(input) + : input, [ContentType.FormData]: (input) => Object.keys(input || {}).reduce((formData, key) => { const property = input[key]; @@ -68,8 +81,8 @@ export class HttpClient { property instanceof Blob ? property : typeof property === "object" && property !== null - ? JSON.stringify(property) - : `${property}`, + ? JSON.stringify(property) + : `${property}`, ); return formData; }, new FormData()), @@ -106,7 +119,17 @@ export class HttpClient { this.abortControllers.delete(cancelToken); } }; - request = async ({ body, secure, path, type, query, format, baseUrl, cancelToken, ...params }) => { + request = async ({ + body, + secure, + path, + type, + query, + format, + baseUrl, + cancelToken, + ...params + }) => { const secureParams = ((typeof secure === "boolean" ? secure : this.baseApiParams.secure) && this.securityWorker && @@ -116,15 +139,28 @@ export class HttpClient { const queryString = query && this.toQueryString(query); const payloadFormatter = this.contentFormatters[type || ContentType.Json]; const responseFormat = format || requestParams.format; - return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, { - ...requestParams, - headers: { - ...(requestParams.headers || {}), - ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}), + return this.customFetch( + `${baseUrl || this.baseUrl || ""}${path}${ + queryString ? `?${queryString}` : "" + }`, + { + ...requestParams, + headers: { + ...(requestParams.headers || {}), + ...(type && type !== ContentType.FormData + ? { "Content-Type": type } + : {}), + }, + signal: + (cancelToken + ? this.createAbortSignal(cancelToken) + : requestParams.signal) || null, + body: + typeof body === "undefined" || body === null + ? null + : payloadFormatter(body), }, - signal: (cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal) || null, - body: typeof body === "undefined" || body === null ? null : payloadFormatter(body), - }).then(async (response) => { + ).then(async (response) => { const r = response; r.data = null; r.error = null; @@ -170,7 +206,7 @@ export class Api extends HttpClient { */ emojisList: (params = {}) => this.request({ - path: `/emojis`, + path: "/emojis", method: "GET", format: "json", ...params, @@ -185,7 +221,7 @@ export class Api extends HttpClient { */ eventsList: (params = {}) => this.request({ - path: `/events`, + path: "/events", method: "GET", format: "json", ...params, @@ -200,7 +236,7 @@ export class Api extends HttpClient { */ feedsList: (params = {}) => this.request({ - path: `/feeds`, + path: "/feeds", method: "GET", format: "json", ...params, @@ -215,7 +251,7 @@ export class Api extends HttpClient { */ gistsList: (query, params = {}) => this.request({ - path: `/gists`, + path: "/gists", method: "GET", query: query, format: "json", @@ -229,7 +265,7 @@ export class Api extends HttpClient { */ gistsCreate: (body, params = {}) => this.request({ - path: `/gists`, + path: "/gists", method: "POST", body: body, type: ContentType.Json, @@ -244,7 +280,7 @@ export class Api extends HttpClient { */ publicList: (query, params = {}) => this.request({ - path: `/gists/public`, + path: "/gists/public", method: "GET", query: query, format: "json", @@ -258,7 +294,7 @@ export class Api extends HttpClient { */ starredList: (query, params = {}) => this.request({ - path: `/gists/starred`, + path: "/gists/starred", method: "GET", query: query, format: "json", @@ -431,7 +467,7 @@ export class Api extends HttpClient { */ templatesList: (params = {}) => this.request({ - path: `/gitignore/templates`, + path: "/gitignore/templates", method: "GET", format: "json", ...params, @@ -459,7 +495,7 @@ export class Api extends HttpClient { */ issuesList: (query, params = {}) => this.request({ - path: `/issues`, + path: "/issues", method: "GET", query: query, format: "json", @@ -535,7 +571,7 @@ export class Api extends HttpClient { */ markdownCreate: (body, params = {}) => this.request({ - path: `/markdown`, + path: "/markdown", method: "POST", body: body, type: ContentType.Json, @@ -549,7 +585,7 @@ export class Api extends HttpClient { */ postMarkdown: (params = {}) => this.request({ - path: `/markdown/raw`, + path: "/markdown/raw", method: "POST", type: ContentType.Text, ...params, @@ -564,7 +600,7 @@ export class Api extends HttpClient { */ metaList: (params = {}) => this.request({ - path: `/meta`, + path: "/meta", method: "GET", format: "json", ...params, @@ -594,7 +630,7 @@ export class Api extends HttpClient { */ notificationsList: (query, params = {}) => this.request({ - path: `/notifications`, + path: "/notifications", method: "GET", query: query, format: "json", @@ -608,7 +644,7 @@ export class Api extends HttpClient { */ notificationsUpdate: (body, params = {}) => this.request({ - path: `/notifications`, + path: "/notifications", method: "PUT", body: body, ...params, @@ -891,7 +927,7 @@ export class Api extends HttpClient { */ rateLimitList: (params = {}) => this.request({ - path: `/rate_limit`, + path: "/rate_limit", method: "GET", format: "json", ...params, @@ -2708,7 +2744,7 @@ export class Api extends HttpClient { */ repositoriesList: (query, params = {}) => this.request({ - path: `/repositories`, + path: "/repositories", method: "GET", query: query, format: "json", @@ -2724,7 +2760,7 @@ export class Api extends HttpClient { */ codeList: (query, params = {}) => this.request({ - path: `/search/code`, + path: "/search/code", method: "GET", query: query, format: "json", @@ -2738,7 +2774,7 @@ export class Api extends HttpClient { */ issuesList: (query, params = {}) => this.request({ - path: `/search/issues`, + path: "/search/issues", method: "GET", query: query, format: "json", @@ -2752,7 +2788,7 @@ export class Api extends HttpClient { */ repositoriesList: (query, params = {}) => this.request({ - path: `/search/repositories`, + path: "/search/repositories", method: "GET", query: query, format: "json", @@ -2766,7 +2802,7 @@ export class Api extends HttpClient { */ usersList: (query, params = {}) => this.request({ - path: `/search/users`, + path: "/search/users", method: "GET", query: query, format: "json", @@ -2967,7 +3003,7 @@ export class Api extends HttpClient { */ userList: (params = {}) => this.request({ - path: `/user`, + path: "/user", method: "GET", format: "json", ...params, @@ -2980,7 +3016,7 @@ export class Api extends HttpClient { */ userPartialUpdate: (body, params = {}) => this.request({ - path: `/user`, + path: "/user", method: "PATCH", body: body, type: ContentType.Json, @@ -2995,7 +3031,7 @@ export class Api extends HttpClient { */ emailsDelete: (body, params = {}) => this.request({ - path: `/user/emails`, + path: "/user/emails", method: "DELETE", body: body, type: ContentType.Json, @@ -3009,7 +3045,7 @@ export class Api extends HttpClient { */ emailsList: (params = {}) => this.request({ - path: `/user/emails`, + path: "/user/emails", method: "GET", ...params, }), @@ -3021,7 +3057,7 @@ export class Api extends HttpClient { */ emailsCreate: (body, params = {}) => this.request({ - path: `/user/emails`, + path: "/user/emails", method: "POST", body: body, ...params, @@ -3034,7 +3070,7 @@ export class Api extends HttpClient { */ followersList: (params = {}) => this.request({ - path: `/user/followers`, + path: "/user/followers", method: "GET", format: "json", ...params, @@ -3047,7 +3083,7 @@ export class Api extends HttpClient { */ followingList: (params = {}) => this.request({ - path: `/user/following`, + path: "/user/following", method: "GET", format: "json", ...params, @@ -3096,7 +3132,7 @@ export class Api extends HttpClient { */ issuesList: (query, params = {}) => this.request({ - path: `/user/issues`, + path: "/user/issues", method: "GET", query: query, format: "json", @@ -3110,7 +3146,7 @@ export class Api extends HttpClient { */ keysList: (params = {}) => this.request({ - path: `/user/keys`, + path: "/user/keys", method: "GET", format: "json", ...params, @@ -3123,7 +3159,7 @@ export class Api extends HttpClient { */ keysCreate: (body, params = {}) => this.request({ - path: `/user/keys`, + path: "/user/keys", method: "POST", body: body, format: "json", @@ -3162,7 +3198,7 @@ export class Api extends HttpClient { */ orgsList: (params = {}) => this.request({ - path: `/user/orgs`, + path: "/user/orgs", method: "GET", format: "json", ...params, @@ -3175,7 +3211,7 @@ export class Api extends HttpClient { */ reposList: (query, params = {}) => this.request({ - path: `/user/repos`, + path: "/user/repos", method: "GET", query: query, format: "json", @@ -3189,7 +3225,7 @@ export class Api extends HttpClient { */ reposCreate: (body, params = {}) => this.request({ - path: `/user/repos`, + path: "/user/repos", method: "POST", body: body, format: "json", @@ -3203,7 +3239,7 @@ export class Api extends HttpClient { */ starredList: (query, params = {}) => this.request({ - path: `/user/starred`, + path: "/user/starred", method: "GET", query: query, format: "json", @@ -3253,7 +3289,7 @@ export class Api extends HttpClient { */ subscriptionsList: (params = {}) => this.request({ - path: `/user/subscriptions`, + path: "/user/subscriptions", method: "GET", format: "json", ...params, @@ -3305,7 +3341,7 @@ export class Api extends HttpClient { */ teamsList: (params = {}) => this.request({ - path: `/user/teams`, + path: "/user/teams", method: "GET", format: "json", ...params, @@ -3320,7 +3356,7 @@ export class Api extends HttpClient { */ usersList: (query, params = {}) => this.request({ - path: `/users`, + path: "/users", method: "GET", query: query, format: "json", diff --git a/tests/spec/js/test.js b/tests/spec/js/test.js index ec1ce2a5..1d798142 100644 --- a/tests/spec/js/test.js +++ b/tests/spec/js/test.js @@ -1,9 +1,11 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ diff --git a/tests/spec/jsAxios/schema.d.ts b/tests/spec/jsAxios/schema.d.ts index 1c46ab41..61191955 100644 --- a/tests/spec/jsAxios/schema.d.ts +++ b/tests/spec/jsAxios/schema.d.ts @@ -1781,9 +1781,15 @@ export interface UserUpdate { name?: string; } export type Users = User[]; -import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, ResponseType } from "axios"; +import type { + AxiosInstance, + AxiosRequestConfig, + AxiosResponse, + ResponseType, +} from "axios"; export type QueryParamsType = Record; -export interface FullRequestParams extends Omit { +export interface FullRequestParams + extends Omit { /** set parameter to `true` for call `securityWorker` for this request */ secure?: boolean; /** request path */ @@ -1797,8 +1803,12 @@ export interface FullRequestParams extends Omit; -export interface ApiConfig extends Omit { +export type RequestParams = Omit< + FullRequestParams, + "body" | "method" | "query" | "path" +>; +export interface ApiConfig + extends Omit { securityWorker?: ( securityData: SecurityDataType | null, ) => Promise | AxiosRequestConfig | void; @@ -1817,9 +1827,17 @@ export declare class HttpClient { private securityWorker?; private secure?; private format?; - constructor({ securityWorker, secure, format, ...axiosConfig }?: ApiConfig); + constructor({ + securityWorker, + secure, + format, + ...axiosConfig + }?: ApiConfig); setSecurityData: (data: SecurityDataType | null) => void; - protected mergeRequestParams(params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig; + protected mergeRequestParams( + params1: AxiosRequestConfig, + params2?: AxiosRequestConfig, + ): AxiosRequestConfig; protected stringifyFormItem(formItem: unknown): string; protected createFormData(input: Record): FormData; request: ({ @@ -1841,7 +1859,9 @@ export declare class HttpClient { * * Powerful collaboration, code review, and code management for open source and private projects. */ -export declare class Api extends HttpClient { +export declare class Api< + SecurityDataType, +> extends HttpClient { emojis: { /** * @description Lists all the emojis available to use on GitHub. @@ -1892,7 +1912,10 @@ export declare class Api extends HttpClient Promise>; + gistsCreate: ( + body: PostGist, + params?: RequestParams, + ) => Promise>; /** * @description List all public gists. * @@ -1931,42 +1954,63 @@ export declare class Api extends HttpClient Promise>; + gistsDelete: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a single gist. * * @name GistsDetail * @request GET:/gists/{id} */ - gistsDetail: (id: number, params?: RequestParams) => Promise>; + gistsDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Edit a gist. * * @name GistsPartialUpdate * @request PATCH:/gists/{id} */ - gistsPartialUpdate: (id: number, body: PatchGist, params?: RequestParams) => Promise>; + gistsPartialUpdate: ( + id: number, + body: PatchGist, + params?: RequestParams, + ) => Promise>; /** * @description List comments on a gist. * * @name CommentsDetail * @request GET:/gists/{id}/comments */ - commentsDetail: (id: number, params?: RequestParams) => Promise>; + commentsDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Create a commen * * @name CommentsCreate * @request POST:/gists/{id}/comments */ - commentsCreate: (id: number, body: CommentBody, params?: RequestParams) => Promise>; + commentsCreate: ( + id: number, + body: CommentBody, + params?: RequestParams, + ) => Promise>; /** * @description Delete a comment. * * @name CommentsDelete * @request DELETE:/gists/{id}/comments/{commentId} */ - commentsDelete: (id: number, commentId: number, params?: RequestParams) => Promise>; + commentsDelete: ( + id: number, + commentId: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a single comment. * @@ -1975,7 +2019,11 @@ export declare class Api extends HttpClient Promise>; + commentsDetail2: ( + id: number, + commentId: number, + params?: RequestParams, + ) => Promise>; /** * @description Edit a comment. * @@ -1994,28 +2042,40 @@ export declare class Api extends HttpClient Promise>; + forksCreate: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Unstar a gist. * * @name StarDelete * @request DELETE:/gists/{id}/star */ - starDelete: (id: number, params?: RequestParams) => Promise>; + starDelete: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Check if a gist is starred. * * @name StarDetail * @request GET:/gists/{id}/star */ - starDetail: (id: number, params?: RequestParams) => Promise>; + starDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Star a gist. * * @name StarUpdate * @request PUT:/gists/{id}/star */ - starUpdate: (id: number, params?: RequestParams) => Promise>; + starUpdate: ( + id: number, + params?: RequestParams, + ) => Promise>; }; gitignore: { /** @@ -2024,14 +2084,19 @@ export declare class Api extends HttpClient Promise>; + templatesList: ( + params?: RequestParams, + ) => Promise>; /** * @description Get a single template. * * @name TemplatesDetail * @request GET:/gitignore/templates/{language} */ - templatesDetail: (language: string, params?: RequestParams) => Promise>; + templatesDetail: ( + language: string, + params?: RequestParams, + ) => Promise>; }; issues: { /** @@ -2111,7 +2176,10 @@ export declare class Api extends HttpClient Promise>; + userEmailDetail: ( + email: string, + params?: RequestParams, + ) => Promise>; /** * @description Find users by keyword. * @@ -2142,7 +2210,10 @@ export declare class Api extends HttpClient Promise>; + markdownCreate: ( + body: Markdown, + params?: RequestParams, + ) => Promise>; /** * @description Render a Markdown document in raw mode * @@ -2167,7 +2238,11 @@ export declare class Api extends HttpClient Promise>; + eventsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; }; notifications: { /** @@ -2199,35 +2274,50 @@ export declare class Api extends HttpClient Promise>; + notificationsUpdate: ( + body: NotificationMarkRead, + params?: RequestParams, + ) => Promise>; /** * @description View a single thread. * * @name ThreadsDetail * @request GET:/notifications/threads/{id} */ - threadsDetail: (id: number, params?: RequestParams) => Promise>; + threadsDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Mark a thread as read * * @name ThreadsPartialUpdate * @request PATCH:/notifications/threads/{id} */ - threadsPartialUpdate: (id: number, params?: RequestParams) => Promise>; + threadsPartialUpdate: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Delete a Thread Subscription. * * @name ThreadsSubscriptionDelete * @request DELETE:/notifications/threads/{id}/subscription */ - threadsSubscriptionDelete: (id: number, params?: RequestParams) => Promise>; + threadsSubscriptionDelete: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a Thread Subscription. * * @name ThreadsSubscriptionDetail * @request GET:/notifications/threads/{id}/subscription */ - threadsSubscriptionDetail: (id: number, params?: RequestParams) => Promise>; + threadsSubscriptionDetail: ( + id: number, + params?: RequestParams, + ) => Promise>; /** * @description Set a Thread Subscription. This lets you subscribe to a thread, or ignore it. Subscribing to a thread is unnecessary if the user is already subscribed to the repository. Ignoring a thread will mute all future notifications (until you comment or get @mentioned). * @@ -2247,21 +2337,31 @@ export declare class Api extends HttpClient Promise>; + orgsDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description Edit an Organization. * * @name OrgsPartialUpdate * @request PATCH:/orgs/{org} */ - orgsPartialUpdate: (org: string, body: PatchOrg, params?: RequestParams) => Promise>; + orgsPartialUpdate: ( + org: string, + body: PatchOrg, + params?: RequestParams, + ) => Promise>; /** * @description List public events for an organization. * * @name EventsDetail * @request GET:/orgs/{org}/events */ - eventsDetail: (org: string, params?: RequestParams) => Promise>; + eventsDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description List issues. List all issues for a given organization for the authenticated user. * @@ -2299,14 +2399,21 @@ export declare class Api extends HttpClient Promise>; + membersDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description Remove a member. Removing a user from this list will remove them from all teams and they will no longer have any access to the organization's repositories. * * @name MembersDelete * @request DELETE:/orgs/{org}/members/{username} */ - membersDelete: (org: string, username: string, params?: RequestParams) => Promise>; + membersDelete: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if a user is, publicly or privately, a member of the organization. * @@ -2315,21 +2422,32 @@ export declare class Api extends HttpClient Promise>; + membersDetail2: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Public members list. Members of an organization can choose to have their membership publicized or not. * * @name PublicMembersDetail * @request GET:/orgs/{org}/public_members */ - publicMembersDetail: (org: string, params?: RequestParams) => Promise>; + publicMembersDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description Conceal a user's membership. * * @name PublicMembersDelete * @request DELETE:/orgs/{org}/public_members/{username} */ - publicMembersDelete: (org: string, username: string, params?: RequestParams) => Promise>; + publicMembersDelete: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Check public membership. * @@ -2338,14 +2456,22 @@ export declare class Api extends HttpClient Promise>; + publicMembersDetail2: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Publicize a user's membership. * * @name PublicMembersUpdate * @request PUT:/orgs/{org}/public_members/{username} */ - publicMembersUpdate: (org: string, username: string, params?: RequestParams) => Promise>; + publicMembersUpdate: ( + org: string, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List repositories for the specified org. * @@ -2366,21 +2492,32 @@ export declare class Api extends HttpClient Promise>; + reposCreate: ( + org: string, + body: PostRepo, + params?: RequestParams, + ) => Promise>; /** * @description List teams. * * @name TeamsDetail * @request GET:/orgs/{org}/teams */ - teamsDetail: (org: string, params?: RequestParams) => Promise>; + teamsDetail: ( + org: string, + params?: RequestParams, + ) => Promise>; /** * @description Create team. In order to create a team, the authenticated user must be an owner of organization. * * @name TeamsCreate * @request POST:/orgs/{org}/teams */ - teamsCreate: (org: string, body: OrgTeamsPost, params?: RequestParams) => Promise>; + teamsCreate: ( + org: string, + body: OrgTeamsPost, + params?: RequestParams, + ) => Promise>; }; rateLimit: { /** @@ -2389,7 +2526,9 @@ export declare class Api extends HttpClient Promise>; + rateLimitList: ( + params?: RequestParams, + ) => Promise>; }; repos: { /** @@ -2398,14 +2537,22 @@ export declare class Api extends HttpClient Promise>; + reposDelete: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get repository. * * @name ReposDetail * @request GET:/repos/{owner}/{repo} */ - reposDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + reposDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Edit repository. * @@ -2424,7 +2571,11 @@ export declare class Api extends HttpClient Promise>; + assigneesDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Check assignee. You may also check to see if a particular user is an assignee for a repository. * @@ -2445,7 +2596,11 @@ export declare class Api extends HttpClient Promise>; + branchesDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get Branch * @@ -2466,7 +2621,11 @@ export declare class Api extends HttpClient Promise>; + collaboratorsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Remove collaborator. * @@ -2511,7 +2670,11 @@ export declare class Api extends HttpClient Promise>; + commentsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Delete a commit comment * @@ -2706,7 +2869,11 @@ export declare class Api extends HttpClient Promise>; + deploymentsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Users with push access can create a deployment for a given ref * @@ -2751,7 +2918,11 @@ export declare class Api extends HttpClient Promise>; + downloadsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Deprecated. Delete a download. * @@ -2786,7 +2957,11 @@ export declare class Api extends HttpClient Promise>; + eventsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description List forks. * @@ -2808,14 +2983,24 @@ export declare class Api extends HttpClient Promise>; + forksCreate: ( + owner: string, + repo: string, + body: ForkBody, + params?: RequestParams, + ) => Promise>; /** * @description Create a Blob. * * @name GitBlobsCreate * @request POST:/repos/{owner}/{repo}/git/blobs */ - gitBlobsCreate: (owner: string, repo: string, body: Blob, params?: RequestParams) => Promise>; + gitBlobsCreate: ( + owner: string, + repo: string, + body: Blob, + params?: RequestParams, + ) => Promise>; /** * @description Get a Blob. Since blobs can be any arbitrary binary data, the input and responses for the blob API takes an encoding parameter that can be either utf-8 or base64. If your data cannot be losslessly sent as a UTF-8 string, you can base64 encode it. * @@ -2858,7 +3043,11 @@ export declare class Api extends HttpClient Promise>; + gitRefsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a Reference * @@ -2877,7 +3066,12 @@ export declare class Api extends HttpClient Promise>; + gitRefsDelete: ( + owner: string, + repo: string, + ref: string, + params?: RequestParams, + ) => Promise>; /** * @description Get a Reference * @@ -2911,7 +3105,12 @@ export declare class Api extends HttpClient Promise>; + gitTagsCreate: ( + owner: string, + repo: string, + body: TagBody, + params?: RequestParams, + ) => Promise>; /** * @description Get a Tag. * @@ -2930,7 +3129,12 @@ export declare class Api extends HttpClient Promise>; + gitTreesCreate: ( + owner: string, + repo: string, + body: Tree, + params?: RequestParams, + ) => Promise>; /** * @description Get a Tree. * @@ -2953,21 +3157,35 @@ export declare class Api extends HttpClient Promise>; + hooksDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a hook. * * @name HooksCreate * @request POST:/repos/{owner}/{repo}/hooks */ - hooksCreate: (owner: string, repo: string, body: HookBody, params?: RequestParams) => Promise>; + hooksCreate: ( + owner: string, + repo: string, + body: HookBody, + params?: RequestParams, + ) => Promise>; /** * @description Delete a hook. * * @name HooksDelete * @request DELETE:/repos/{owner}/{repo}/hooks/{hookId} */ - hooksDelete: (owner: string, repo: string, hookId: number, params?: RequestParams) => Promise>; + hooksDelete: ( + owner: string, + repo: string, + hookId: number, + params?: RequestParams, + ) => Promise>; /** * @description Get single hook. * @@ -2976,7 +3194,12 @@ export declare class Api extends HttpClient Promise>; + hooksDetail2: ( + owner: string, + repo: string, + hookId: number, + params?: RequestParams, + ) => Promise>; /** * @description Edit a hook. * @@ -3040,7 +3263,12 @@ export declare class Api extends HttpClient Promise>; + issuesCreate: ( + owner: string, + repo: string, + body: Issue, + params?: RequestParams, + ) => Promise>; /** * @description List comments in a repository. * @@ -3107,7 +3335,11 @@ export declare class Api extends HttpClient Promise>; + issuesEventsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get a single event. * @@ -3261,7 +3493,11 @@ export declare class Api extends HttpClient Promise>; + keysDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a key. * @@ -3280,7 +3516,12 @@ export declare class Api extends HttpClient Promise>; + keysDelete: ( + owner: string, + repo: string, + keyId: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a key * @@ -3301,7 +3542,11 @@ export declare class Api extends HttpClient Promise>; + labelsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a label. * @@ -3320,7 +3565,12 @@ export declare class Api extends HttpClient Promise>; + labelsDelete: ( + owner: string, + repo: string, + name: string, + params?: RequestParams, + ) => Promise>; /** * @description Get a single label. * @@ -3329,7 +3579,12 @@ export declare class Api extends HttpClient Promise>; + labelsDetail2: ( + owner: string, + repo: string, + name: string, + params?: RequestParams, + ) => Promise>; /** * @description Update a label. * @@ -3349,7 +3604,11 @@ export declare class Api extends HttpClient Promise>; + languagesDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Perform a merge. * @@ -3705,7 +3964,11 @@ export declare class Api extends HttpClient Promise>; + releasesDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a release Users with push access to the repository can create a release. * @@ -3761,7 +4024,12 @@ export declare class Api extends HttpClient Promise>; + releasesDelete: ( + owner: string, + repo: string, + id: string, + params?: RequestParams, + ) => Promise>; /** * @description Get a single release * @@ -3809,7 +4077,11 @@ export declare class Api extends HttpClient Promise>; + stargazersDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get the number of additions and deletions per week. Returns a weekly aggregate of the number of additions and deletions pushed to a repository. * @@ -3871,7 +4143,12 @@ export declare class Api extends HttpClient Promise>; + statusesDetail: ( + owner: string, + repo: string, + ref: string, + params?: RequestParams, + ) => Promise>; /** * @description Create a Status. * @@ -3891,21 +4168,33 @@ export declare class Api extends HttpClient Promise>; + subscribersDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Delete a Repository Subscription. * * @name SubscriptionDelete * @request DELETE:/repos/{owner}/{repo}/subscription */ - subscriptionDelete: (owner: string, repo: string, params?: RequestParams) => Promise>; + subscriptionDelete: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get a Repository Subscription. * * @name SubscriptionDetail * @request GET:/repos/{owner}/{repo}/subscription */ - subscriptionDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + subscriptionDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Set a Repository Subscription * @@ -3924,21 +4213,33 @@ export declare class Api extends HttpClient Promise>; + tagsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get list of teams * * @name TeamsDetail * @request GET:/repos/{owner}/{repo}/teams */ - teamsDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + teamsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description List Stargazers. New implementation. * * @name WatchersDetail * @request GET:/repos/{owner}/{repo}/watchers */ - watchersDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + watchersDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Get archive link. This method will return a 302 to a URL to download a tarball or zipball archive for a repository. Please make sure your HTTP framework is configured to follow redirects or you will need to use the Location header to make a second GET request. Note: For private repositories, these links are temporary and expire quickly. * @@ -4107,28 +4408,41 @@ export declare class Api extends HttpClient Promise>; + teamsDelete: ( + teamId: number, + params?: RequestParams, + ) => Promise>; /** * @description Get team. * * @name TeamsDetail * @request GET:/teams/{teamId} */ - teamsDetail: (teamId: number, params?: RequestParams) => Promise>; + teamsDetail: ( + teamId: number, + params?: RequestParams, + ) => Promise>; /** * @description Edit team. In order to edit a team, the authenticated user must be an owner of the org that the team is associated with. * * @name TeamsPartialUpdate * @request PATCH:/teams/{teamId} */ - teamsPartialUpdate: (teamId: number, body: EditTeam, params?: RequestParams) => Promise>; + teamsPartialUpdate: ( + teamId: number, + body: EditTeam, + params?: RequestParams, + ) => Promise>; /** * @description List team members. In order to list members in a team, the authenticated user must be a member of the team. * * @name MembersDetail * @request GET:/teams/{teamId}/members */ - membersDetail: (teamId: number, params?: RequestParams) => Promise>; + membersDetail: ( + teamId: number, + params?: RequestParams, + ) => Promise>; /** * @description The "Remove team member" API is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Remove team membership API instead. It allows you to remove both active and pending memberships. Remove team member. In order to remove a user from a team, the authenticated user must have 'admin' permissions to the team or be an owner of the org that the team is associated with. NOTE This does not delete the user, it just remove them from the team. * @@ -4136,7 +4450,11 @@ export declare class Api extends HttpClient Promise>; + membersDelete: ( + teamId: number, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description The "Get team member" API is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Get team membership API instead. It allows you to get both active and pending memberships. Get team member. In order to get if a user is a member of a team, the authenticated user mus be a member of the team. * @@ -4146,7 +4464,11 @@ export declare class Api extends HttpClient Promise>; + membersDetail2: ( + teamId: number, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description The API (described below) is deprecated and is scheduled for removal in the next major version of the API. We recommend using the Add team membership API instead. It allows you to invite new organization members to your teams. Add team member. In order to add a user to a team, the authenticated user must have 'admin' permissions to the team or be an owner of the org that the team is associated with. * @@ -4154,14 +4476,22 @@ export declare class Api extends HttpClient Promise>; + membersUpdate: ( + teamId: number, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Remove team membership. In order to remove a membership between a user and a team, the authenticated user must have 'admin' permissions to the team or be an owner of the organization that the team is associated with. NOTE: This does not delete the user, it just removes their membership from the team. * * @name MembershipsDelete * @request DELETE:/teams/{teamId}/memberships/{username} */ - membershipsDelete: (teamId: number, username: string, params?: RequestParams) => Promise>; + membershipsDelete: ( + teamId: number, + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Get team membership. In order to get a user's membership with a team, the authenticated user must be a member of the team or an owner of the team's organization. * @@ -4190,14 +4520,22 @@ export declare class Api extends HttpClient Promise>; + reposDetail: ( + teamId: number, + params?: RequestParams, + ) => Promise>; /** * @description In order to remove a repository from a team, the authenticated user must be an owner of the org that the team is associated with. NOTE: This does not delete the repository, it just removes it from the team. * * @name ReposDelete * @request DELETE:/teams/{teamId}/repos/{owner}/{repo} */ - reposDelete: (teamId: number, owner: string, repo: string, params?: RequestParams) => Promise>; + reposDelete: ( + teamId: number, + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if a team manages a repository * @@ -4206,14 +4544,24 @@ export declare class Api extends HttpClient Promise>; + reposDetail2: ( + teamId: number, + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description In order to add a repository to a team, the authenticated user must be an owner of the org that the team is associated with. Also, the repository must be owned by the organization, or a direct fork of a repository owned by the organization. * * @name ReposUpdate * @request PUT:/teams/{teamId}/repos/{owner}/{repo} */ - reposUpdate: (teamId: number, owner: string, repo: string, params?: RequestParams) => Promise>; + reposUpdate: ( + teamId: number, + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; }; user: { /** @@ -4229,14 +4577,20 @@ export declare class Api extends HttpClient Promise>; + userPartialUpdate: ( + body: UserUpdate, + params?: RequestParams, + ) => Promise>; /** * @description Delete email address(es). You can include a single email address or an array of addresses. * * @name EmailsDelete * @request DELETE:/user/emails */ - emailsDelete: (body: UserEmails, params?: RequestParams) => Promise>; + emailsDelete: ( + body: UserEmails, + params?: RequestParams, + ) => Promise>; /** * @description List email addresses for a user. In the final version of the API, this method will return an array of hashes with extended information for each email address indicating if the address has been verified and if it's primary email address for GitHub. Until API v3 is finalized, use the application/vnd.github.v3 media type to get other response format. * @@ -4250,7 +4604,10 @@ export declare class Api extends HttpClient Promise>; + emailsCreate: ( + body: EmailsPost, + params?: RequestParams, + ) => Promise>; /** * @description List the authenticated user's followers * @@ -4271,21 +4628,30 @@ export declare class Api extends HttpClient Promise>; + followingDelete: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if you are following a user. * * @name FollowingDetail * @request GET:/user/following/{username} */ - followingDetail: (username: string, params?: RequestParams) => Promise>; + followingDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Follow a user. Following a user requires the user to be logged in and authenticated with basic auth or OAuth with the user:follow scope. * * @name FollowingUpdate * @request PUT:/user/following/{username} */ - followingUpdate: (username: string, params?: RequestParams) => Promise>; + followingUpdate: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List issues. List all issues across owned and member repositories for the authenticated user. * @@ -4329,21 +4695,30 @@ export declare class Api extends HttpClient Promise>; + keysCreate: ( + body: UserKeysPost, + params?: RequestParams, + ) => Promise>; /** * @description Delete a public key. Removes a public key. Requires that you are authenticated via Basic Auth or via OAuth with at least admin:public_key scope. * * @name KeysDelete * @request DELETE:/user/keys/{keyId} */ - keysDelete: (keyId: number, params?: RequestParams) => Promise>; + keysDelete: ( + keyId: number, + params?: RequestParams, + ) => Promise>; /** * @description Get a single public key. * * @name KeysDetail * @request GET:/user/keys/{keyId} */ - keysDetail: (keyId: number, params?: RequestParams) => Promise>; + keysDetail: ( + keyId: number, + params?: RequestParams, + ) => Promise>; /** * @description List public and private organizations for the authenticated user. * @@ -4370,7 +4745,10 @@ export declare class Api extends HttpClient Promise>; + reposCreate: ( + body: PostRepo, + params?: RequestParams, + ) => Promise>; /** * @description List repositories being starred by the authenticated user. * @@ -4392,28 +4770,42 @@ export declare class Api extends HttpClient Promise>; + starredDelete: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if you are starring a repository. * * @name StarredDetail * @request GET:/user/starred/{owner}/{repo} */ - starredDetail: (owner: string, repo: string, params?: RequestParams) => Promise>; + starredDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Star a repository. * * @name StarredUpdate * @request PUT:/user/starred/{owner}/{repo} */ - starredUpdate: (owner: string, repo: string, params?: RequestParams) => Promise>; + starredUpdate: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description List repositories being watched by the authenticated user. * * @name SubscriptionsList * @request GET:/user/subscriptions */ - subscriptionsList: (params?: RequestParams) => Promise>; + subscriptionsList: ( + params?: RequestParams, + ) => Promise>; /** * @description Stop watching a repository * @@ -4421,7 +4813,11 @@ export declare class Api extends HttpClient Promise>; + subscriptionsDelete: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if you are watching a repository. * @@ -4429,7 +4825,11 @@ export declare class Api extends HttpClient Promise>; + subscriptionsDetail: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description Watch a repository. * @@ -4437,7 +4837,11 @@ export declare class Api extends HttpClient Promise>; + subscriptionsUpdate: ( + owner: string, + repo: string, + params?: RequestParams, + ) => Promise>; /** * @description List all of the teams across all of the organizations to which the authenticated user belongs. This method requires user or repo scope when authenticating via OAuth. * @@ -4466,35 +4870,52 @@ export declare class Api extends HttpClient Promise>; + usersDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description If you are authenticated as the given user, you will see your private events. Otherwise, you'll only see public events. * * @name EventsDetail * @request GET:/users/{username}/events */ - eventsDetail: (username: string, params?: RequestParams) => Promise>; + eventsDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description This is the user's organization dashboard. You must be authenticated as the user to view this. * * @name EventsOrgsDetail * @request GET:/users/{username}/events/orgs/{org} */ - eventsOrgsDetail: (username: string, org: string, params?: RequestParams) => Promise>; + eventsOrgsDetail: ( + username: string, + org: string, + params?: RequestParams, + ) => Promise>; /** * @description List a user's followers * * @name FollowersDetail * @request GET:/users/{username}/followers */ - followersDetail: (username: string, params?: RequestParams) => Promise>; + followersDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description Check if one user follows another. * * @name FollowingDetail * @request GET:/users/{username}/following/{targetUser} */ - followingDetail: (username: string, targetUser: string, params?: RequestParams) => Promise>; + followingDetail: ( + username: string, + targetUser: string, + params?: RequestParams, + ) => Promise>; /** * @description List a users gists. * @@ -4518,28 +4939,40 @@ export declare class Api extends HttpClient Promise>; + keysDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List all public organizations for a user. * * @name OrgsDetail * @request GET:/users/{username}/orgs */ - orgsDetail: (username: string, params?: RequestParams) => Promise>; + orgsDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description These are events that you'll only see public events. * * @name ReceivedEventsDetail * @request GET:/users/{username}/received_events */ - receivedEventsDetail: (username: string, params?: RequestParams) => Promise>; + receivedEventsDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List public events that a user has received * * @name ReceivedEventsPublicDetail * @request GET:/users/{username}/received_events/public */ - receivedEventsPublicDetail: (username: string, params?: RequestParams) => Promise>; + receivedEventsPublicDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List public repositories for the specified user. * @@ -4560,13 +4993,19 @@ export declare class Api extends HttpClient Promise>; + starredDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; /** * @description List repositories being watched by a user. * * @name SubscriptionsDetail * @request GET:/users/{username}/subscriptions */ - subscriptionsDetail: (username: string, params?: RequestParams) => Promise>; + subscriptionsDetail: ( + username: string, + params?: RequestParams, + ) => Promise>; }; } diff --git a/tests/spec/jsAxios/schema.js b/tests/spec/jsAxios/schema.js index 2bccff36..9be4d5c5 100644 --- a/tests/spec/jsAxios/schema.js +++ b/tests/spec/jsAxios/schema.js @@ -10,8 +10,8 @@ */ import axios from "axios"; -export var ContentType; -(function (ContentType) { +export let ContentType; +((ContentType) => { ContentType["Json"] = "application/json"; ContentType["FormData"] = "multipart/form-data"; ContentType["UrlEncoded"] = "application/x-www-form-urlencoded"; @@ -24,7 +24,10 @@ export class HttpClient { secure; format; constructor({ securityWorker, secure, format, ...axiosConfig } = {}) { - this.instance = axios.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "https://api.github.com" }); + this.instance = axios.create({ + ...axiosConfig, + baseURL: axiosConfig.baseURL || "https://api.github.com", + }); this.secure = secure; this.format = format; this.securityWorker = securityWorker; @@ -39,7 +42,8 @@ export class HttpClient { ...params1, ...(params2 || {}), headers: { - ...((method && this.instance.defaults.headers[method.toLowerCase()]) || {}), + ...((method && this.instance.defaults.headers[method.toLowerCase()]) || + {}), ...(params1.headers || {}), ...((params2 && params2.headers) || {}), }, @@ -55,10 +59,13 @@ export class HttpClient { createFormData(input) { return Object.keys(input || {}).reduce((formData, key) => { const property = input[key]; - const propertyContent = property instanceof Array ? property : [property]; + const propertyContent = Array.isArray(property) ? property : [property]; for (const formItem of propertyContent) { const isFileType = formItem instanceof Blob || formItem instanceof File; - formData.append(key, isFileType ? formItem : this.stringifyFormItem(formItem)); + formData.append( + key, + isFileType ? formItem : this.stringifyFormItem(formItem), + ); } return formData; }, new FormData()); @@ -71,17 +78,29 @@ export class HttpClient { {}; const requestParams = this.mergeRequestParams(params, secureParams); const responseFormat = format || this.format || undefined; - if (type === ContentType.FormData && body && body !== null && typeof body === "object") { + if ( + type === ContentType.FormData && + body && + body !== null && + typeof body === "object" + ) { body = this.createFormData(body); } - if (type === ContentType.Text && body && body !== null && typeof body !== "string") { + if ( + type === ContentType.Text && + body && + body !== null && + typeof body !== "string" + ) { body = JSON.stringify(body); } return this.instance.request({ ...requestParams, headers: { ...(requestParams.headers || {}), - ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}), + ...(type && type !== ContentType.FormData + ? { "Content-Type": type } + : {}), }, params: query, responseType: responseFormat, @@ -109,7 +128,7 @@ export class Api extends HttpClient { */ emojisList: (params = {}) => this.request({ - path: `/emojis`, + path: "/emojis", method: "GET", format: "json", ...params, @@ -124,7 +143,7 @@ export class Api extends HttpClient { */ eventsList: (params = {}) => this.request({ - path: `/events`, + path: "/events", method: "GET", format: "json", ...params, @@ -139,7 +158,7 @@ export class Api extends HttpClient { */ feedsList: (params = {}) => this.request({ - path: `/feeds`, + path: "/feeds", method: "GET", format: "json", ...params, @@ -154,7 +173,7 @@ export class Api extends HttpClient { */ gistsList: (query, params = {}) => this.request({ - path: `/gists`, + path: "/gists", method: "GET", query: query, format: "json", @@ -168,7 +187,7 @@ export class Api extends HttpClient { */ gistsCreate: (body, params = {}) => this.request({ - path: `/gists`, + path: "/gists", method: "POST", body: body, type: ContentType.Json, @@ -183,7 +202,7 @@ export class Api extends HttpClient { */ publicList: (query, params = {}) => this.request({ - path: `/gists/public`, + path: "/gists/public", method: "GET", query: query, format: "json", @@ -197,7 +216,7 @@ export class Api extends HttpClient { */ starredList: (query, params = {}) => this.request({ - path: `/gists/starred`, + path: "/gists/starred", method: "GET", query: query, format: "json", @@ -370,7 +389,7 @@ export class Api extends HttpClient { */ templatesList: (params = {}) => this.request({ - path: `/gitignore/templates`, + path: "/gitignore/templates", method: "GET", format: "json", ...params, @@ -398,7 +417,7 @@ export class Api extends HttpClient { */ issuesList: (query, params = {}) => this.request({ - path: `/issues`, + path: "/issues", method: "GET", query: query, format: "json", @@ -474,7 +493,7 @@ export class Api extends HttpClient { */ markdownCreate: (body, params = {}) => this.request({ - path: `/markdown`, + path: "/markdown", method: "POST", body: body, type: ContentType.Json, @@ -488,7 +507,7 @@ export class Api extends HttpClient { */ postMarkdown: (params = {}) => this.request({ - path: `/markdown/raw`, + path: "/markdown/raw", method: "POST", type: ContentType.Text, ...params, @@ -503,7 +522,7 @@ export class Api extends HttpClient { */ metaList: (params = {}) => this.request({ - path: `/meta`, + path: "/meta", method: "GET", format: "json", ...params, @@ -533,7 +552,7 @@ export class Api extends HttpClient { */ notificationsList: (query, params = {}) => this.request({ - path: `/notifications`, + path: "/notifications", method: "GET", query: query, format: "json", @@ -547,7 +566,7 @@ export class Api extends HttpClient { */ notificationsUpdate: (body, params = {}) => this.request({ - path: `/notifications`, + path: "/notifications", method: "PUT", body: body, ...params, @@ -830,7 +849,7 @@ export class Api extends HttpClient { */ rateLimitList: (params = {}) => this.request({ - path: `/rate_limit`, + path: "/rate_limit", method: "GET", format: "json", ...params, @@ -2647,7 +2666,7 @@ export class Api extends HttpClient { */ repositoriesList: (query, params = {}) => this.request({ - path: `/repositories`, + path: "/repositories", method: "GET", query: query, format: "json", @@ -2663,7 +2682,7 @@ export class Api extends HttpClient { */ codeList: (query, params = {}) => this.request({ - path: `/search/code`, + path: "/search/code", method: "GET", query: query, format: "json", @@ -2677,7 +2696,7 @@ export class Api extends HttpClient { */ issuesList: (query, params = {}) => this.request({ - path: `/search/issues`, + path: "/search/issues", method: "GET", query: query, format: "json", @@ -2691,7 +2710,7 @@ export class Api extends HttpClient { */ repositoriesList: (query, params = {}) => this.request({ - path: `/search/repositories`, + path: "/search/repositories", method: "GET", query: query, format: "json", @@ -2705,7 +2724,7 @@ export class Api extends HttpClient { */ usersList: (query, params = {}) => this.request({ - path: `/search/users`, + path: "/search/users", method: "GET", query: query, format: "json", @@ -2906,7 +2925,7 @@ export class Api extends HttpClient { */ userList: (params = {}) => this.request({ - path: `/user`, + path: "/user", method: "GET", format: "json", ...params, @@ -2919,7 +2938,7 @@ export class Api extends HttpClient { */ userPartialUpdate: (body, params = {}) => this.request({ - path: `/user`, + path: "/user", method: "PATCH", body: body, type: ContentType.Json, @@ -2934,7 +2953,7 @@ export class Api extends HttpClient { */ emailsDelete: (body, params = {}) => this.request({ - path: `/user/emails`, + path: "/user/emails", method: "DELETE", body: body, type: ContentType.Json, @@ -2948,7 +2967,7 @@ export class Api extends HttpClient { */ emailsList: (params = {}) => this.request({ - path: `/user/emails`, + path: "/user/emails", method: "GET", ...params, }), @@ -2960,7 +2979,7 @@ export class Api extends HttpClient { */ emailsCreate: (body, params = {}) => this.request({ - path: `/user/emails`, + path: "/user/emails", method: "POST", body: body, ...params, @@ -2973,7 +2992,7 @@ export class Api extends HttpClient { */ followersList: (params = {}) => this.request({ - path: `/user/followers`, + path: "/user/followers", method: "GET", format: "json", ...params, @@ -2986,7 +3005,7 @@ export class Api extends HttpClient { */ followingList: (params = {}) => this.request({ - path: `/user/following`, + path: "/user/following", method: "GET", format: "json", ...params, @@ -3035,7 +3054,7 @@ export class Api extends HttpClient { */ issuesList: (query, params = {}) => this.request({ - path: `/user/issues`, + path: "/user/issues", method: "GET", query: query, format: "json", @@ -3049,7 +3068,7 @@ export class Api extends HttpClient { */ keysList: (params = {}) => this.request({ - path: `/user/keys`, + path: "/user/keys", method: "GET", format: "json", ...params, @@ -3062,7 +3081,7 @@ export class Api extends HttpClient { */ keysCreate: (body, params = {}) => this.request({ - path: `/user/keys`, + path: "/user/keys", method: "POST", body: body, format: "json", @@ -3101,7 +3120,7 @@ export class Api extends HttpClient { */ orgsList: (params = {}) => this.request({ - path: `/user/orgs`, + path: "/user/orgs", method: "GET", format: "json", ...params, @@ -3114,7 +3133,7 @@ export class Api extends HttpClient { */ reposList: (query, params = {}) => this.request({ - path: `/user/repos`, + path: "/user/repos", method: "GET", query: query, format: "json", @@ -3128,7 +3147,7 @@ export class Api extends HttpClient { */ reposCreate: (body, params = {}) => this.request({ - path: `/user/repos`, + path: "/user/repos", method: "POST", body: body, format: "json", @@ -3142,7 +3161,7 @@ export class Api extends HttpClient { */ starredList: (query, params = {}) => this.request({ - path: `/user/starred`, + path: "/user/starred", method: "GET", query: query, format: "json", @@ -3192,7 +3211,7 @@ export class Api extends HttpClient { */ subscriptionsList: (params = {}) => this.request({ - path: `/user/subscriptions`, + path: "/user/subscriptions", method: "GET", format: "json", ...params, @@ -3244,7 +3263,7 @@ export class Api extends HttpClient { */ teamsList: (params = {}) => this.request({ - path: `/user/teams`, + path: "/user/teams", method: "GET", format: "json", ...params, @@ -3259,7 +3278,7 @@ export class Api extends HttpClient { */ usersList: (query, params = {}) => this.request({ - path: `/users`, + path: "/users", method: "GET", query: query, format: "json", diff --git a/tests/spec/jsAxios/test.js b/tests/spec/jsAxios/test.js index f51d30bb..21d8f855 100644 --- a/tests/spec/jsAxios/test.js +++ b/tests/spec/jsAxios/test.js @@ -1,9 +1,11 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ diff --git a/tests/spec/jsSingleHttpClientModular/test.js b/tests/spec/jsSingleHttpClientModular/test.js index 5d94c124..0b1d6abb 100644 --- a/tests/spec/jsSingleHttpClientModular/test.js +++ b/tests/spec/jsSingleHttpClientModular/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, Exception }) => { generateApiForTest({ diff --git a/tests/spec/modular/test.js b/tests/spec/modular/test.js index f9962d78..033ff249 100644 --- a/tests/spec/modular/test.js +++ b/tests/spec/modular/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, Exception }) => { generateApiForTest({ diff --git a/tests/spec/moduleNameFirstTag/test.js b/tests/spec/moduleNameFirstTag/test.js index f12d693a..4870e6c0 100644 --- a/tests/spec/moduleNameFirstTag/test.js +++ b/tests/spec/moduleNameFirstTag/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { moduleNameFirstTag: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/moduleNameIndex/test.js b/tests/spec/moduleNameIndex/test.js index 3a1d8bc2..58a3c476 100644 --- a/tests/spec/moduleNameIndex/test.js +++ b/tests/spec/moduleNameIndex/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { moduleNameIndex: 2, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/noClient/test.js b/tests/spec/noClient/test.js index 44f56d21..8c6da417 100644 --- a/tests/spec/noClient/test.js +++ b/tests/spec/noClient/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/nullable-2.0/test.js b/tests/spec/nullable-2.0/test.js index 61ffdf2c..89bd3f2a 100644 --- a/tests/spec/nullable-2.0/test.js +++ b/tests/spec/nullable-2.0/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/nullable-3.0/test.js b/tests/spec/nullable-3.0/test.js index dff0261d..542434b6 100644 --- a/tests/spec/nullable-3.0/test.js +++ b/tests/spec/nullable-3.0/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/object-types/test.js b/tests/spec/object-types/test.js index f2d7e2a9..f3dd720c 100644 --- a/tests/spec/object-types/test.js +++ b/tests/spec/object-types/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/on-insert-path-param/test.js b/tests/spec/on-insert-path-param/test.js index 70bb777a..e8173a97 100644 --- a/tests/spec/on-insert-path-param/test.js +++ b/tests/spec/on-insert-path-param/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -19,6 +21,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { }, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/partialBaseTemplate/test.js b/tests/spec/partialBaseTemplate/test.js index 47e3bdd2..3c1ed685 100644 --- a/tests/spec/partialBaseTemplate/test.js +++ b/tests/spec/partialBaseTemplate/test.js @@ -1,11 +1,13 @@ const _ = require("lodash"); const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName, Exception }) => { generateApiForTest({ @@ -17,11 +19,19 @@ schemas.forEach(({ absolutePath, apiFileName, Exception }) => { // because this script was called from package.json folder templates: "./tests/spec/partialBaseTemplate/spec_templates", }).then((output) => { - if (!_.includes(_.get(output.files, "[0].fileContent"), "/** PARTIAL TEMPLATES */")) { + if ( + !_.includes( + _.get(output.files, "[0].fileContent"), + "/** PARTIAL TEMPLATES */", + ) + ) { throw new Exception("Failed, spec templates are not applied"); } validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/partialDefaultTemplate/test.js b/tests/spec/partialDefaultTemplate/test.js index db301bb7..33325a91 100644 --- a/tests/spec/partialDefaultTemplate/test.js +++ b/tests/spec/partialDefaultTemplate/test.js @@ -1,11 +1,13 @@ const _ = require("lodash"); const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName, Exception }) => { generateApiForTest({ @@ -17,11 +19,19 @@ schemas.forEach(({ absolutePath, apiFileName, Exception }) => { // because this script was called from package.json folder templates: "./tests/spec/partialDefaultTemplate/spec_templates", }).then((output) => { - if (!_.includes(_.get(output.files, "[0].fileContent"), "/** PARTIAL TEMPLATES */")) { + if ( + !_.includes( + _.get(output.files, "[0].fileContent"), + "/** PARTIAL TEMPLATES */", + ) + ) { throw new Exception("Failed, spec templates are not applied"); } validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/patch/test.js b/tests/spec/patch/test.js index 2c2c4858..bf18b20e 100644 --- a/tests/spec/patch/test.js +++ b/tests/spec/patch/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { patch: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/primitive-type-constructs/test.js b/tests/spec/primitive-type-constructs/test.js index 70e7ef85..069a8efc 100644 --- a/tests/spec/primitive-type-constructs/test.js +++ b/tests/spec/primitive-type-constructs/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { const primitiveTypeConstructs = (constructs) => ({ @@ -45,13 +47,18 @@ schemas.forEach(({ absolutePath, apiFileName }) => { codeGenConstructs, }), ]).then((...args) => { - validateGeneratedModule(resolve(__dirname, `./another-array-type/${apiFileName}`)); + validateGeneratedModule( + resolve(__dirname, `./another-array-type/${apiFileName}`), + ); assertGeneratedModule( resolve(__dirname, `./another-array-type/${apiFileName}`), - resolve(__dirname, `./another-array-type/expected.ts`), + resolve(__dirname, "./another-array-type/expected.ts"), ); validateGeneratedModule(resolve(__dirname, `./base/${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./base/${apiFileName}`), resolve(__dirname, `./base/expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./base/${apiFileName}`), + resolve(__dirname, "./base/expected.ts"), + ); }); }); diff --git a/tests/spec/readonly/test.js b/tests/spec/readonly/test.js index 25986c73..1807c264 100644 --- a/tests/spec/readonly/test.js +++ b/tests/spec/readonly/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/responses/test.js b/tests/spec/responses/test.js index ff67ee80..8d4a7416 100644 --- a/tests/spec/responses/test.js +++ b/tests/spec/responses/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,7 +18,10 @@ schemas.forEach(({ absolutePath, apiFileName }) => { }) .then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }) .catch((e) => { console.error("responses option test failed."); diff --git a/tests/spec/routeTypes/test.js b/tests/spec/routeTypes/test.js index 58aae114..2cd01b0b 100644 --- a/tests/spec/routeTypes/test.js +++ b/tests/spec/routeTypes/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/singleHttpClient/test.js b/tests/spec/singleHttpClient/test.js index e50f0e05..42f71165 100644 --- a/tests/spec/singleHttpClient/test.js +++ b/tests/spec/singleHttpClient/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { singleHttpClient: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/sortTypes-false/test.js b/tests/spec/sortTypes-false/test.js index c3df414c..46a6e81b 100644 --- a/tests/spec/sortTypes-false/test.js +++ b/tests/spec/sortTypes-false/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { sortTypes: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/sortTypes/test.js b/tests/spec/sortTypes/test.js index d3acca01..77b3a16b 100644 --- a/tests/spec/sortTypes/test.js +++ b/tests/spec/sortTypes/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { sortTypes: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/specProperty/test.js b/tests/spec/specProperty/test.js index f514018a..9e28de0d 100644 --- a/tests/spec/specProperty/test.js +++ b/tests/spec/specProperty/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -17,6 +19,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateClient: false, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/templates/test.js b/tests/spec/templates/test.js index ff4ab6a6..0a1be656 100644 --- a/tests/spec/templates/test.js +++ b/tests/spec/templates/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName, Exception }) => { generateApiForTest({ @@ -15,9 +17,11 @@ schemas.forEach(({ absolutePath, apiFileName, Exception }) => { output: resolve(__dirname, "./"), // because this script was called from package.json folder templates: "./tests/spec/templates/spec_templates", - }) - .then(() => { - validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); - }); + }).then(() => { + validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); + }); }); diff --git a/tests/spec/typeSuffixPrefix/test.js b/tests/spec/typeSuffixPrefix/test.js index ccf5eb12..9b016725 100644 --- a/tests/spec/typeSuffixPrefix/test.js +++ b/tests/spec/typeSuffixPrefix/test.js @@ -1,6 +1,6 @@ const _ = require("lodash"); const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); @@ -23,6 +23,9 @@ schemas.forEach(({ absolutePath, apiFileName, Exception }) => { generateResponses: true, }).then((output) => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/spec/unionEnums/test.js b/tests/spec/unionEnums/test.js index 8f11b56c..504a5814 100644 --- a/tests/spec/unionEnums/test.js +++ b/tests/spec/unionEnums/test.js @@ -1,10 +1,12 @@ const { generateApiForTest } = require("../../helpers/generateApiForTest"); -const { resolve } = require("path"); +const { resolve } = require("node:path"); const validateGeneratedModule = require("../../helpers/validateGeneratedModule"); const createSchemaInfos = require("../../helpers/createSchemaInfos"); const assertGeneratedModule = require("../../helpers/assertGeneratedModule"); -const schemas = createSchemaInfos({ absolutePathToSchemas: resolve(__dirname, "./") }); +const schemas = createSchemaInfos({ + absolutePathToSchemas: resolve(__dirname, "./"), +}); schemas.forEach(({ absolutePath, apiFileName }) => { generateApiForTest({ @@ -16,6 +18,9 @@ schemas.forEach(({ absolutePath, apiFileName }) => { generateUnionEnums: true, }).then(() => { validateGeneratedModule(resolve(__dirname, `./${apiFileName}`)); - assertGeneratedModule(resolve(__dirname, `./${apiFileName}`), resolve(__dirname, `./expected.ts`)); + assertGeneratedModule( + resolve(__dirname, `./${apiFileName}`), + resolve(__dirname, "./expected.ts"), + ); }); }); diff --git a/tests/validate.js b/tests/validate.js index 3495ec29..53f188b2 100644 --- a/tests/validate.js +++ b/tests/validate.js @@ -1,4 +1,4 @@ -const { resolve } = require("path"); +const { resolve } = require("node:path"); const allSchemas = require("./allSchemas"); const validateGeneratedModule = require("./helpers/validateGeneratedModule");