@himenon/openapi-typescript-code-generator
Version:
OpenAPI Code Generator using TypeScript AST.
1,573 lines (1,548 loc) • 53.6 kB
JavaScript
import {
TsGenerator_exports
} from "./chunk-IRTN2Z2Z.js";
import "./chunk-PH24P4KQ.js";
import {
escapeText,
escapeText2,
isAvailableVariableName
} from "./chunk-R3KKVR43.js";
import {
__export
} from "./chunk-PZ5AY32C.js";
// src/code-templates/class-api-client/index.ts
var class_api_client_exports = {};
__export(class_api_client_exports, {
generator: () => generator
});
// src/code-templates/_shared/ApiClientArgument.ts
var createRequestContentTypeReference = (factory, { convertedParams }) => {
return factory.TypeAliasDeclaration.create({
export: true,
name: convertedParams.requestContentTypeName,
type: factory.TypeOperatorNode.create({
syntaxKind: "keyof",
type: factory.TypeReferenceNode.create({
name: convertedParams.requestBodyName
})
})
});
};
var createResponseContentTypeReference = (factory, { convertedParams }) => {
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
return factory.TypeAliasDeclaration.create({
export: true,
name: convertedParams.responseContentTypeName,
type: factory.UnionTypeNode.create({
typeNodes: convertedParams.responseSuccessNames.map((item) => {
return factory.TypeOperatorNode.create({
syntaxKind: "keyof",
type: factory.TypeReferenceNode.create({
name: item
})
});
})
})
});
}
return factory.TypeAliasDeclaration.create({
export: true,
name: convertedParams.responseContentTypeName,
type: factory.TypeOperatorNode.create({
syntaxKind: "keyof",
type: factory.TypeReferenceNode.create({
name: convertedParams.responseSuccessNames[0]
})
})
});
};
var createHeaders = (factory, { convertedParams }) => {
const members = [];
if (convertedParams.has2OrMoreRequestContentTypes) {
members.push(
factory.PropertySignature.create({
readOnly: false,
name: `"Content-Type"`,
optional: false,
type: factory.TypeReferenceNode.create({ name: "T" })
})
);
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
members.push(
factory.PropertySignature.create({
readOnly: false,
name: "Accept",
optional: false,
type: factory.TypeReferenceNode.create({ name: "U" })
})
);
}
if (members.length === 0) {
return void 0;
}
return factory.TypeLiteralNode.create({ members });
};
var create = (factory, params) => {
const { convertedParams } = params;
const typeParameters = [];
const members = [];
if (convertedParams.hasRequestBody && convertedParams.has2OrMoreRequestContentTypes) {
typeParameters.push(
factory.TypeParameterDeclaration.create({
name: "T",
constraint: factory.TypeReferenceNode.create({
name: convertedParams.requestContentTypeName
})
})
);
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
typeParameters.push(
factory.TypeParameterDeclaration.create({
name: "U",
constraint: factory.TypeReferenceNode.create({
name: convertedParams.responseContentTypeName
})
})
);
}
const headerDeclaration = createHeaders(factory, params);
if (headerDeclaration) {
const extraHeader = factory.PropertySignature.create({
readOnly: false,
name: "headers",
optional: false,
type: headerDeclaration
});
members.push(extraHeader);
}
if (convertedParams.hasParameter) {
const parameter = factory.PropertySignature.create({
readOnly: false,
name: "parameter",
optional: false,
type: factory.TypeReferenceNode.create({
name: convertedParams.parameterName
})
});
members.push(parameter);
}
if (convertedParams.hasRequestBody) {
const requestBody = factory.PropertySignature.create({
readOnly: false,
name: "requestBody",
optional: false,
type: factory.IndexedAccessTypeNode.create({
objectType: factory.TypeReferenceNode.create({
name: convertedParams.requestBodyName
}),
indexType: factory.TypeReferenceNode.create({
name: convertedParams.requestFirstContentType ? `"${convertedParams.requestFirstContentType}"` : "T"
})
})
});
members.push(requestBody);
}
if (members.length === 0) {
return;
}
return factory.InterfaceDeclaration.create({
export: true,
name: convertedParams.argumentParamsTypeDeclaration,
members,
typeParameters
});
};
// src/code-templates/_shared/ApiClientInterface.ts
import ts from "typescript";
var httpMethodList = ["GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"];
var createErrorResponsesTypeAlias = (typeName, factory, errorResponseNames) => {
if (errorResponseNames.length === 0) {
return factory.TypeAliasDeclaration.create({
export: true,
name: typeName,
type: ts.factory.createToken(ts.SyntaxKind.VoidKeyword)
});
}
return factory.TypeAliasDeclaration.create({
export: true,
name: typeName,
type: factory.UnionTypeNode.create({
typeNodes: errorResponseNames.map((name) => {
return factory.TypeReferenceNode.create({
name
});
})
})
});
};
var createSuccessResponseTypeAlias = (typeName, factory, successResponseNames) => {
if (successResponseNames.length === 0) {
return factory.TypeAliasDeclaration.create({
export: true,
name: typeName,
type: ts.factory.createToken(ts.SyntaxKind.VoidKeyword)
});
}
return factory.TypeAliasDeclaration.create({
export: true,
name: typeName,
type: factory.UnionTypeNode.create({
typeNodes: successResponseNames.map((name) => {
return factory.TypeReferenceNode.create({
name
});
})
})
});
};
var createHttpMethod = (factory) => {
return factory.TypeAliasDeclaration.create({
export: true,
name: "HttpMethod",
type: factory.TypeNode.create({ type: "string", enum: httpMethodList })
});
};
var createQueryParamsDeclarations = (factory) => {
const queryParameterDeclaration = factory.InterfaceDeclaration.create({
export: true,
name: "QueryParameter",
members: [
factory.PropertySignature.create({
readOnly: false,
name: "value",
optional: false,
type: factory.TypeNode.create({ type: "any" })
}),
factory.PropertySignature.create({
readOnly: false,
name: "style",
optional: true,
type: factory.TypeNode.create({ type: "string", enum: ["form", "spaceDelimited", "pipeDelimited", "deepObject"] })
}),
factory.PropertySignature.create({
readOnly: false,
name: "explode",
optional: false,
type: factory.TypeNode.create({ type: "boolean" })
})
]
});
const queryParametersDeclaration = factory.InterfaceDeclaration.create({
export: true,
name: "QueryParameters",
members: [
factory.IndexSignatureDeclaration.create({
name: "key",
type: factory.TypeReferenceNode.create({ name: "QueryParameter" })
})
]
});
return [queryParameterDeclaration, queryParametersDeclaration];
};
var createObjectLikeInterface = (factory) => {
return factory.InterfaceDeclaration.create({
export: true,
name: "ObjectLike",
members: [
factory.IndexSignatureDeclaration.create({
name: "key",
type: factory.TypeNode.create({ type: "any" })
})
]
});
};
var createEncodingInterface = (factory) => {
return factory.InterfaceDeclaration.create({
export: true,
name: "Encoding",
members: [
factory.PropertySignature.create({
name: "contentType",
readOnly: true,
optional: true,
type: factory.TypeReferenceNode.create({
name: "string"
})
}),
factory.PropertySignature.create({
name: "headers",
readOnly: false,
optional: true,
type: factory.TypeReferenceNode.create({
name: "Record<string, any>"
})
}),
factory.PropertySignature.create({
name: "style",
readOnly: true,
optional: true,
type: factory.TypeNode.create({ type: "string", enum: ["form", "spaceDelimited", "pipeDelimited", "deepObject"] })
}),
factory.PropertySignature.create({
name: "explode",
readOnly: true,
optional: true,
type: factory.TypeReferenceNode.create({
name: "boolean"
})
}),
factory.PropertySignature.create({
name: "allowReserved",
readOnly: true,
optional: true,
type: factory.TypeReferenceNode.create({
name: "boolean"
})
})
]
});
};
var create2 = (factory, list, methodType, option) => {
const objectLikeOrAnyType = factory.UnionTypeNode.create({
typeNodes: [
factory.TypeReferenceNode.create({
name: "ObjectLike"
}),
factory.TypeNode.create({
type: "any"
})
]
});
const encodingInterface = createEncodingInterface(factory);
const requestArgs = factory.ParameterDeclaration.create({
name: "requestArgs",
type: factory.TypeReferenceNode.create({
name: "RequestArgs"
})
});
const options = factory.ParameterDeclaration.create({
name: "options",
optional: true,
type: factory.TypeReferenceNode.create({
name: "RequestOption"
})
});
const successResponseNames = list.flatMap((item) => item.convertedParams.responseSuccessNames);
const errorResponseNamespace = factory.Namespace.create({
export: true,
name: "ErrorResponse",
statements: list.map((item) => {
return createErrorResponsesTypeAlias(`${item.convertedParams.escapedOperationId}`, factory, item.convertedParams.responseErrorNames);
})
});
const returnType = option.sync ? factory.TypeReferenceNode.create({
name: "T"
}) : factory.TypeReferenceNode.create({
name: "Promise",
typeArguments: [
factory.TypeReferenceNode.create({
name: "T"
})
]
});
const functionType = factory.FunctionTypeNode.create({
typeParameters: [
factory.TypeParameterDeclaration.create({
name: "T",
defaultType: factory.TypeReferenceNode.create({
name: "SuccessResponses"
})
})
],
parameters: [requestArgs, options],
type: returnType
});
const requestFunction = factory.PropertySignature.create({
readOnly: false,
name: "request",
optional: false,
type: functionType
});
const requestArgsInterfaceDeclaration = factory.InterfaceDeclaration.create({
export: true,
name: "RequestArgs",
members: [
factory.PropertySignature.create({
name: "httpMethod",
readOnly: true,
optional: false,
type: factory.TypeReferenceNode.create({ name: "HttpMethod" })
}),
factory.PropertySignature.create({
name: methodType === "currying-function" ? "uri" : "url",
readOnly: true,
optional: false,
type: factory.TypeReferenceNode.create({ name: "string" })
}),
factory.PropertySignature.create({
name: "headers",
readOnly: false,
optional: false,
type: objectLikeOrAnyType
}),
factory.PropertySignature.create({
name: "requestBody",
readOnly: false,
optional: true,
type: objectLikeOrAnyType
}),
factory.PropertySignature.create({
name: "requestBodyEncoding",
readOnly: false,
optional: true,
type: factory.TypeReferenceNode.create({ name: "Record<string, Encoding>" })
}),
factory.PropertySignature.create({
name: "queryParameters",
optional: true,
readOnly: false,
type: factory.UnionTypeNode.create({
typeNodes: [
factory.TypeReferenceNode.create({
name: "QueryParameters"
}),
factory.TypeNode.create({ type: "undefined" })
]
})
})
],
typeParameters: []
});
return [
createHttpMethod(factory),
createObjectLikeInterface(factory),
...createQueryParamsDeclarations(factory),
createSuccessResponseTypeAlias("SuccessResponses", factory, successResponseNames),
errorResponseNamespace,
encodingInterface,
requestArgsInterfaceDeclaration,
factory.InterfaceDeclaration.create({
export: true,
name: "ApiClient",
members: [requestFunction],
typeParameters: [
factory.TypeParameterDeclaration.create({
name: "RequestOption"
})
]
})
];
};
// src/code-templates/class-api-client/ApiClientClass/Class.ts
import ts2 from "typescript";
var create3 = (factory, members) => {
return factory.ClassDeclaration.create({
name: "Client",
export: true,
members: [
factory.PropertyDeclaration.create({
modifiers: [ts2.factory.createModifier(ts2.SyntaxKind.PrivateKeyword)],
name: "baseUrl",
type: ts2.factory.createKeywordTypeNode(ts2.SyntaxKind.StringKeyword)
}),
...members
],
typeParameterDeclaration: [
factory.TypeParameterDeclaration.create({
name: "RequestOption"
})
]
});
};
// src/code-templates/class-api-client/ApiClientClass/Constructor.ts
var create4 = (factory) => {
const parameter1 = factory.ParameterDeclaration.create({
modifiers: "private",
name: "apiClient",
type: factory.TypeReferenceNode.create({
name: "ApiClient",
typeArguments: [
factory.TypeReferenceNode.create({
name: "RequestOption"
})
]
})
});
const parameter2 = factory.ParameterDeclaration.create({
name: "baseUrl",
type: factory.TypeNode.create({
type: "string"
})
});
return factory.ConstructorDeclaration.create({
parameters: [parameter1, parameter2],
body: factory.Block.create({
statements: [
factory.ExpressionStatement.create({
expression: factory.BinaryExpression.create({
left: factory.PropertyAccessExpression.create({
expression: "this",
name: "baseUrl"
}),
operator: "=",
right: factory.CallExpression.create({
expression: factory.PropertyAccessExpression.create({
expression: "baseUrl",
name: "replace"
}),
argumentsArray: [factory.RegularExpressionLiteral.create({ text: "/\\/$/" }), factory.StringLiteral.create({ text: "" })]
})
})
})
],
multiLine: false
})
});
};
// src/code-templates/class-api-client/ApiClientClass/Method.ts
import { EOL } from "os";
// src/code-templates/_shared/utils.ts
var getTemplateSpan = (factory, currentIndex, nextIndex, lastIndex, currentItem, nextItem) => {
if (!nextItem) {
return [
factory.TemplateSpan.create({
expression: currentItem.value,
literal: factory.TemplateTail.create({
text: ""
})
})
];
}
if (nextItem.type === "property") {
if (lastIndex === nextIndex) {
return [
factory.TemplateSpan.create({
expression: currentItem.value,
literal: factory.TemplateTail.create({
text: ""
})
}),
factory.TemplateSpan.create({
expression: nextItem.value,
literal: factory.TemplateTail.create({
text: ""
})
})
];
}
return [
factory.TemplateSpan.create({
expression: currentItem.value,
literal: factory.TemplateTail.create({
text: ""
})
}),
factory.TemplateSpan.create({
expression: nextItem.value,
literal: factory.TemplateMiddle.create({
text: ""
})
})
];
}
if (lastIndex === nextIndex) {
return [
factory.TemplateSpan.create({
expression: currentItem.value,
literal: factory.TemplateTail.create({
text: nextItem.value
})
})
];
}
return [
factory.TemplateSpan.create({
expression: currentItem.value,
literal: factory.TemplateMiddle.create({
text: nextItem.value
})
})
];
};
var generateTemplateExpression = (factory, list) => {
if (list.length === 0) {
return factory.NoSubstitutionTemplateLiteral.create({
text: ""
});
}
const templateHead = factory.TemplateHead.create({
text: list[0].type === "property" ? "" : list[0].value
});
const spanList = list.splice(1, list.length);
if (spanList.length === 0 && list[0].type === "string") {
return factory.NoSubstitutionTemplateLiteral.create({
text: list[0].value
});
}
const lastIndex = spanList.length - 1;
const restValue = lastIndex % 2;
let templateSpans = [];
for (let i = 0; i <= (lastIndex - restValue) / 2; i++) {
if (spanList.length === 0) {
continue;
}
const currentIndex = 2 * i;
const nextIndex = 2 * i + 1;
const currentItem = spanList[currentIndex];
const nextItem = spanList[nextIndex];
if (currentItem.type === "string") {
throw new Error("Logic Error");
}
templateSpans = templateSpans.concat(getTemplateSpan(factory, currentIndex, nextIndex, lastIndex, currentItem, nextItem));
}
return factory.TemplateExpression.create({
head: templateHead,
templateSpans
});
};
var splitVariableText = (text) => {
const pattern = '["[a-zA-Z_0-9.]+"]';
const splitTexts = text.split(/(\["[a-zA-Z_0-9\\.]+"\])/g);
return splitTexts.reduce((splitList, value) => {
if (value === "") {
return splitList;
}
if (new RegExp(pattern).test(value)) {
const matchedValue = value.match(/[a-zA-Z_0-9\\.]+/);
if (matchedValue) {
splitList.push({
kind: "element-access",
value: matchedValue[0]
});
}
return splitList;
}
const dotSplited = value.split(".");
const items = dotSplited.map((childValue) => ({ kind: "string", value: childValue }));
return splitList.concat(items);
}, []);
};
var generateVariableIdentifier = (factory, name) => {
if (name.startsWith("/")) {
throw new Error(`can't start '/'. name=${name}`);
}
const list = splitVariableText(name);
if (list.length === 1) {
return factory.Identifier.create({
name
});
}
const [n1, n2, ...rest] = list;
const first = factory.PropertyAccessExpression.create({
expression: n1.value,
name: n2.value
});
return rest.reduce((previous, current) => {
if (current.kind === "string" && isAvailableVariableName(current.value)) {
return factory.PropertyAccessExpression.create({
expression: previous,
name: current.value
});
}
return factory.ElementAccessExpression.create({
expression: previous,
index: current.value
});
}, first);
};
var generateObjectLiteralExpression = (factory, obj, extraProperties = []) => {
const properties = Object.entries(obj).map(([key, item]) => {
const initializer = item.type === "variable" ? generateVariableIdentifier(factory, item.value) : factory.StringLiteral.create({ text: item.value });
return factory.PropertyAssignment.create({
name: escapeText(key),
initializer
});
});
return factory.ObjectLiteralExpression.create({
properties: extraProperties.concat(properties),
multiLine: true
});
};
var stringToArray = (text, delimiter) => text.split(new RegExp(`(${delimiter})`));
var multiSplitStringToArray = (text, delimiters) => {
return delimiters.reduce(
(current, delimiter) => {
return current.reduce((result, currentText) => {
return result.concat(stringToArray(currentText, delimiter));
}, []);
},
[text]
);
};
// src/code-templates/_shared/MethodBody/createEncodingMap.ts
var createEncodingMap = (content) => {
return Object.keys(content).reduce((all, key) => {
const { encoding } = content[key];
if (!encoding) {
return all;
}
return { ...all, [key]: encoding };
}, {});
};
// src/code-templates/_shared/MethodBody/CallRequest.ts
var createEncodingParams = (factory, params) => {
const content = params.operationParams.requestBody?.content;
if (!content) {
return;
}
const encodingMap = createEncodingMap(content);
if (Object.keys(encodingMap).length === 0) {
return;
}
if (params.convertedParams.has2OrMoreRequestContentTypes) {
return factory.Identifier.create({ name: `requestEncodings[params.headers["Content-Type"]]` });
}
return factory.Identifier.create({ name: `requestEncodings["${params.convertedParams.requestFirstContentType}"]` });
};
var create5 = (factory, params, methodType) => {
const { convertedParams } = params;
const apiClientVariableIdentifier = {
class: "this.apiClient.request",
function: "apiClient.request",
"currying-function": "apiClient.request"
};
const expression = generateVariableIdentifier(factory, apiClientVariableIdentifier[methodType]);
const requestBodyEncoding = createEncodingParams(factory, params);
const requestArgs = factory.ObjectLiteralExpression.create({
properties: [
factory.PropertyAssignment.create({
name: "httpMethod",
initializer: factory.StringLiteral.create({ text: params.operationParams.httpMethod.toUpperCase() })
}),
factory.ShorthandPropertyAssignment.create({
name: methodType === "currying-function" ? "uri" : "url"
}),
factory.ShorthandPropertyAssignment.create({
name: "headers"
}),
convertedParams.hasRequestBody && factory.PropertyAssignment.create({
name: "requestBody",
initializer: generateVariableIdentifier(factory, "params.requestBody")
}),
requestBodyEncoding && factory.PropertyAssignment.create({
name: "requestBodyEncoding",
initializer: requestBodyEncoding
}),
convertedParams.hasQueryParameters && factory.PropertyAssignment.create({
name: "queryParameters",
initializer: factory.Identifier.create({ name: "queryParameters" })
})
].flatMap((v) => v ? [v] : []),
multiLine: true
});
const argumentsArray = [requestArgs, factory.Identifier.create({ name: "option" })];
return factory.CallExpression.create({
expression,
typeArguments: [],
argumentsArray
});
};
// src/code-templates/_shared/MethodBody/HeaderParameter.ts
var create6 = (factory, params) => {
return factory.VariableStatement.create({
declarationList: factory.VariableDeclarationList.create({
flag: "const",
declarations: [
factory.VariableDeclaration.create({
name: params.variableName,
initializer: generateObjectLiteralExpression(factory, params.object)
})
]
})
});
};
// src/code-templates/_shared/MethodBody/PathParameter.ts
var isPathParameter = (params) => {
return params.in === "path";
};
var generateUrlVariableStatement = (factory, urlTemplate, variableExpression) => {
return factory.VariableStatement.create({
declarationList: factory.VariableDeclarationList.create({
declarations: [
factory.VariableDeclaration.create({
name: "url",
initializer: factory.BinaryExpression.create({
left: variableExpression,
operator: "+",
right: generateTemplateExpression(factory, urlTemplate)
})
})
],
flag: "const"
})
});
};
var generateUriVariableStatement = (factory, urlTemplate) => {
return factory.VariableStatement.create({
declarationList: factory.VariableDeclarationList.create({
declarations: [
factory.VariableDeclaration.create({
name: "uri",
initializer: generateTemplateExpression(factory, urlTemplate)
})
],
flag: "const"
})
});
};
var generateUrlTemplateExpression = (factory, requestUri, pathParameters) => {
const patternMap = pathParameters.reduce((previous, item) => {
previous[`{${item.name}}`] = item.name;
return previous;
}, {});
const urlTemplate = [];
let temporaryStringList = [];
const replaceText = (text) => {
let replacedText = text;
for (const pathParameterName of Object.keys(patternMap)) {
if (new RegExp(pathParameterName).test(replacedText)) {
const { text: text2, escaped } = escapeText2(patternMap[pathParameterName]);
const variableDeclareText = escaped ? `params.parameter[${text2}]` : `params.parameter.${text2}`;
replacedText = replacedText.replace(new RegExp(pathParameterName, "g"), variableDeclareText);
}
}
return replacedText === text ? void 0 : replacedText;
};
const requestUrlTicks = multiSplitStringToArray(requestUri, Object.keys(patternMap));
requestUrlTicks.forEach((requestUriTick, index) => {
if (requestUri === "") {
temporaryStringList.push("");
return;
}
const replacedText = replaceText(requestUriTick);
if (replacedText) {
if (temporaryStringList.length > 0) {
const value = temporaryStringList.join("/");
urlTemplate.push({
type: "string",
value
});
temporaryStringList = [];
}
urlTemplate.push({
type: "property",
value: factory.CallExpression.create({
expression: factory.Identifier.create({
name: "encodeURIComponent"
}),
argumentsArray: [generateVariableIdentifier(factory, replacedText)]
})
});
} else {
temporaryStringList.push(requestUriTick);
}
if (index === requestUrlTicks.length - 1) {
const value = temporaryStringList.join("/");
if (value === "") {
urlTemplate.push({
type: "string",
value: requestUri.endsWith("/") ? "/" : ""
});
} else {
urlTemplate.push({
type: "string",
value
});
}
}
});
return urlTemplate;
};
var create7 = (factory, requestUri, pathParameters, methodType) => {
const urlTemplate = pathParameters.length > 0 ? generateUrlTemplateExpression(factory, requestUri, pathParameters) : [{ type: "string", value: requestUri }];
if (methodType === "currying-function") {
return generateUriVariableStatement(factory, urlTemplate);
}
if (methodType === "class") {
const variableExpression = factory.PropertyAccessExpression.create({
name: "baseUrl",
expression: "this"
});
return generateUrlVariableStatement(factory, urlTemplate, variableExpression);
}
if (methodType === "function") {
const variableExpression = factory.Identifier.create({
name: "_baseUrl"
});
return generateUrlVariableStatement(factory, urlTemplate, variableExpression);
}
throw new Error(`Invalid MethodType: ${methodType}`);
};
// src/code-templates/_shared/MethodBody/QueryParameter.ts
import ts3 from "typescript";
var create8 = (factory, params) => {
const properties = Object.entries(params.object).reduce((previous, [key, item]) => {
const childProperties = [
factory.PropertyAssignment.create({
name: "value",
initializer: item.type === "variable" ? generateVariableIdentifier(factory, item.value) : factory.StringLiteral.create({ text: item.value })
})
];
if (item.style) {
childProperties.push(
factory.PropertyAssignment.create({
name: "style",
initializer: factory.StringLiteral.create({ text: item.style })
})
);
}
childProperties.push(
factory.PropertyAssignment.create({
name: "explode",
initializer: item.explode ? ts3.factory.createTrue() : ts3.factory.createFalse()
})
);
const childObjectInitializer = factory.ObjectLiteralExpression.create({
properties: childProperties
});
const childObject = factory.PropertyAssignment.create({
name: escapeText(key),
initializer: childObjectInitializer
});
return previous.concat(childObject);
}, []);
return factory.VariableStatement.create({
declarationList: factory.VariableDeclarationList.create({
flag: "const",
declarations: [
factory.VariableDeclaration.create({
name: params.variableName,
type: factory.TypeReferenceNode.create({
name: "QueryParameters"
}),
initializer: factory.ObjectLiteralExpression.create({
properties,
multiLine: true
})
})
]
})
});
};
// src/code-templates/_shared/MethodBody/index.ts
var create9 = (factory, params, methodType) => {
const statements = [];
const { convertedParams, operationParams } = params;
const { pickedParameters } = convertedParams;
const pathParameters = pickedParameters.filter(isPathParameter);
statements.push(create7(factory, params.operationParams.requestUri, pathParameters, methodType));
const initialHeaderObject = {};
if (convertedParams.has2OrMoreRequestContentTypes) {
initialHeaderObject["Content-Type"] = {
type: "variable",
value: "params.headers.Content-Type"
};
} else if (convertedParams.requestFirstContentType) {
initialHeaderObject["Content-Type"] = {
type: "string",
value: convertedParams.requestFirstContentType
};
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
initialHeaderObject.Accept = {
type: "variable",
value: "params.headers.Accept"
};
} else if (convertedParams.successResponseFirstContentType) {
initialHeaderObject.Accept = {
type: "string",
value: convertedParams.successResponseFirstContentType
};
}
const headerParameter = pickedParameters.filter((item) => item.in === "header");
const headerObject = Object.values(headerParameter).reduce((previous, current) => {
return { ...previous, [current.name]: { type: "variable", value: `params.parameter.${current.name}` } };
}, initialHeaderObject);
statements.push(
create6(factory, {
variableName: "headers",
object: headerObject
})
);
const content = operationParams.requestBody?.content;
if (content) {
const encodingMap = createEncodingMap(content);
let identifier;
if (convertedParams.has2OrMoreRequestContentTypes) {
identifier = factory.Identifier.create({
name: JSON.stringify(encodingMap, null, 2)
});
} else if (convertedParams.requestFirstContentType) {
identifier = factory.Identifier.create({
name: JSON.stringify({ [convertedParams.requestFirstContentType]: encodingMap[convertedParams.requestFirstContentType] }, null, 2)
});
}
const requestEncodingsVariableStatement = factory.VariableStatement.create({
declarationList: factory.VariableDeclarationList.create({
flag: "const",
declarations: [
factory.VariableDeclaration.create({
name: "requestEncodings",
initializer: identifier,
type: factory.TypeReferenceNode.create({
name: "Record<string, Record<string, Encoding>>"
})
})
]
})
});
if (identifier && Object.keys(encodingMap).length > 0) {
statements.push(requestEncodingsVariableStatement);
}
}
if (convertedParams.hasQueryParameters) {
const queryParameter = pickedParameters.filter((item) => item.in === "query");
const queryObject = Object.values(queryParameter).reduce((previous, current) => {
const { text, escaped } = escapeText2(current.name);
const variableDeclareText = escaped ? `params.parameter[${text}]` : `params.parameter.${text}`;
return {
...previous,
[current.name]: { type: "variable", value: variableDeclareText, style: current.style, explode: !!current.explode }
};
}, {});
statements.push(create8(factory, { variableName: "queryParameters", object: queryObject }));
}
statements.push(
factory.ReturnStatement.create({
expression: create5(factory, params, methodType)
})
);
return statements.length === 0 ? [factory.ReturnStatement.create({})] : statements;
};
// src/code-templates/class-api-client/ApiClientClass/Method.ts
var generateParams = (factory, { convertedParams }) => {
const typeArguments = [];
if (convertedParams.has2OrMoreRequestContentTypes) {
typeArguments.push(
factory.TypeReferenceNode.create({
name: "RequestContentType"
})
);
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
typeArguments.push(
factory.TypeReferenceNode.create({
name: "ResponseContentType"
})
);
}
return factory.ParameterDeclaration.create({
name: "params",
modifiers: void 0,
type: factory.TypeReferenceNode.create({
name: convertedParams.argumentParamsTypeDeclaration,
typeArguments
})
});
};
var generateResponseReturnType = (factory, successResponseNameList, successResponseContentTypeList, option) => {
let objectType = factory.TypeNode.create({
type: "void"
});
if (successResponseNameList.length === 1) {
objectType = factory.TypeReferenceNode.create({
name: successResponseNameList[0]
});
} else if (successResponseNameList.length > 1) {
objectType = factory.UnionTypeNode.create({
typeNodes: successResponseNameList.map((item) => factory.TypeReferenceNode.create({ name: item }))
});
}
if (successResponseNameList.length === 0) {
if (option.sync) {
return objectType;
}
return factory.TypeReferenceNode.create({
name: "Promise",
typeArguments: [objectType]
});
}
const isOnlyOneResponseContentType = successResponseContentTypeList.length === 1;
let indexType = factory.TypeReferenceNode.create({
name: "ResponseContentType"
});
if (isOnlyOneResponseContentType) {
indexType = factory.TypeReferenceNode.create({
name: `"${successResponseContentTypeList[0]}"`
});
}
if (option.sync) {
return factory.IndexedAccessTypeNode.create({
objectType,
indexType
});
}
return factory.TypeReferenceNode.create({
name: "Promise",
typeArguments: [
factory.IndexedAccessTypeNode.create({
objectType,
indexType
})
]
});
};
var methodTypeParameters = (factory, { convertedParams }) => {
const typeParameters = [];
if (convertedParams.has2OrMoreRequestContentTypes) {
typeParameters.push(
factory.TypeParameterDeclaration.create({
name: "RequestContentType",
constraint: factory.TypeReferenceNode.create({
name: convertedParams.requestContentTypeName
})
})
);
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
typeParameters.push(
factory.TypeParameterDeclaration.create({
name: "ResponseContentType",
constraint: factory.TypeReferenceNode.create({
name: convertedParams.responseContentTypeName
})
})
);
}
return typeParameters;
};
var create10 = (factory, params, option) => {
const { convertedParams } = params;
const typeParameters = methodTypeParameters(factory, params);
const methodArguments = [];
const hasParamsArguments = convertedParams.hasParameter || convertedParams.hasRequestBody || convertedParams.has2OrMoreSuccessResponseContentTypes || convertedParams.has2OrMoreRequestContentTypes;
if (hasParamsArguments) {
methodArguments.push(generateParams(factory, params));
}
const returnType = generateResponseReturnType(
factory,
convertedParams.responseSuccessNames,
convertedParams.successResponseContentTypes,
option
);
methodArguments.push(
factory.ParameterDeclaration.create({
name: "option",
modifiers: void 0,
optional: true,
type: factory.TypeReferenceNode.create({
name: "RequestOption"
})
})
);
return factory.MethodDeclaration.create({
name: convertedParams.functionName,
async: !option.sync,
parameters: methodArguments,
comment: option.additionalMethodComment ? [params.operationParams.comment, `operationId: ${params.operationId}`, `Request URI: ${params.operationParams.requestUri}`].filter((t) => !!t).join(EOL) : params.operationParams.comment,
deprecated: params.operationParams.deprecated,
type: returnType,
typeParameters,
body: factory.Block.create({
statements: create9(factory, params, "class"),
multiLine: true
})
});
};
// src/code-templates/class-api-client/ApiClientClass/index.ts
var create11 = (factory, list, option) => {
const methodList = list.map((params) => {
return create10(factory, params, option);
});
const members = [create4(factory), ...methodList];
return [...create2(factory, list, "class", option), create3(factory, members)];
};
// src/code-templates/class-api-client/index.ts
var generator = (codeGeneratorParamsList, option) => {
const statements = [];
const factory = TsGenerator_exports.Factory.create();
codeGeneratorParamsList.forEach((codeGeneratorParams) => {
const { convertedParams } = codeGeneratorParams;
if (convertedParams.hasRequestBody) {
statements.push(createRequestContentTypeReference(factory, codeGeneratorParams));
}
if (convertedParams.responseSuccessNames.length > 0) {
statements.push(createResponseContentTypeReference(factory, codeGeneratorParams));
}
const typeDeclaration = create(factory, codeGeneratorParams);
if (typeDeclaration) {
statements.push(typeDeclaration);
}
});
create11(factory, codeGeneratorParamsList, option || {}).forEach((newStatement) => {
statements.push(newStatement);
});
return statements;
};
// src/code-templates/functional-api-client/index.ts
var functional_api_client_exports = {};
__export(functional_api_client_exports, {
generator: () => generator2
});
// src/code-templates/functional-api-client/FunctionalApiClient/index.ts
import { EOL as EOL2 } from "os";
import ts4 from "typescript";
// src/code-templates/functional-api-client/FunctionalApiClient/ArrowFunction.ts
var generateParams2 = (factory, { convertedParams }) => {
const typeArguments = [];
if (convertedParams.has2OrMoreRequestContentTypes) {
typeArguments.push(
factory.TypeReferenceNode.create({
name: "RequestContentType"
})
);
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
typeArguments.push(
factory.TypeReferenceNode.create({
name: "ResponseContentType"
})
);
}
return factory.ParameterDeclaration.create({
name: "params",
modifiers: void 0,
type: factory.TypeReferenceNode.create({
name: convertedParams.argumentParamsTypeDeclaration,
typeArguments
})
});
};
var generateResponseReturnType2 = (factory, successResponseNameList, successResponseContentTypeList, option) => {
let objectType = factory.TypeNode.create({
type: "void"
});
if (successResponseNameList.length === 1) {
objectType = factory.TypeReferenceNode.create({
name: successResponseNameList[0]
});
} else if (successResponseNameList.length > 1) {
objectType = factory.UnionTypeNode.create({
typeNodes: successResponseNameList.map((item) => factory.TypeReferenceNode.create({ name: item }))
});
}
if (successResponseNameList.length === 0) {
if (option.sync) {
return objectType;
}
return factory.TypeReferenceNode.create({
name: "Promise",
typeArguments: [objectType]
});
}
const isOnlyOneResponseContentType = successResponseContentTypeList.length === 1;
let indexType = factory.TypeReferenceNode.create({
name: "ResponseContentType"
});
if (isOnlyOneResponseContentType) {
indexType = factory.TypeReferenceNode.create({
name: `"${successResponseContentTypeList[0]}"`
});
}
if (option.sync) {
return factory.IndexedAccessTypeNode.create({
objectType,
indexType
});
}
return factory.TypeReferenceNode.create({
name: "Promise",
typeArguments: [
factory.IndexedAccessTypeNode.create({
objectType,
indexType
})
]
});
};
var methodTypeParameters2 = (factory, { convertedParams }) => {
const typeParameters = [];
if (convertedParams.has2OrMoreRequestContentTypes) {
typeParameters.push(
factory.TypeParameterDeclaration.create({
name: "RequestContentType",
constraint: factory.TypeReferenceNode.create({
name: convertedParams.requestContentTypeName
})
})
);
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
typeParameters.push(
factory.TypeParameterDeclaration.create({
name: "ResponseContentType",
constraint: factory.TypeReferenceNode.create({
name: convertedParams.responseContentTypeName
})
})
);
}
return typeParameters;
};
var create12 = (factory, params, option) => {
const { convertedParams } = params;
const typeParameters = methodTypeParameters2(factory, params);
const methodArguments = [];
const hasParamsArguments = convertedParams.hasParameter || convertedParams.hasRequestBody || convertedParams.has2OrMoreSuccessResponseContentTypes || convertedParams.has2OrMoreRequestContentTypes;
if (hasParamsArguments) {
methodArguments.push(generateParams2(factory, params));
}
const returnType = generateResponseReturnType2(
factory,
convertedParams.responseSuccessNames,
convertedParams.successResponseContentTypes,
option
);
methodArguments.push(
factory.ParameterDeclaration.create({
name: "option",
modifiers: void 0,
optional: true,
type: factory.TypeReferenceNode.create({
name: "RequestOption"
})
})
);
return factory.ArrowFunction.create({
typeParameters,
parameters: methodArguments,
type: returnType,
body: factory.Block.create({
statements: create9(factory, params, "function"),
multiLine: true
})
});
};
// src/code-templates/functional-api-client/FunctionalApiClient/index.ts
var create13 = (factory, list, option) => {
const properties = list.map((params) => {
return factory.PropertyAssignment.create({
name: params.convertedParams.functionName,
initializer: create12(factory, params, option),
comment: option.additionalMethodComment ? [params.operationParams.comment, `operationId: ${params.operationId}`, `Request URI: ${params.operationParams.requestUri}`].filter((t) => !!t).join(EOL2) : params.operationParams.comment
});
});
const returnValue = factory.ReturnStatement.create({
expression: factory.ObjectLiteralExpression.create({
properties,
multiLine: true
})
});
const arrowFunction = factory.ArrowFunction.create({
typeParameters: [
factory.TypeParameterDeclaration.create({
name: "RequestOption"
})
],
parameters: [
factory.ParameterDeclaration.create({
name: "apiClient",
type: factory.TypeReferenceNode.create({
name: "ApiClient",
typeArguments: [
factory.TypeReferenceNode.create({
name: "RequestOption"
})
]
})
}),
factory.ParameterDeclaration.create({
name: "baseUrl",
type: ts4.factory.createKeywordTypeNode(ts4.SyntaxKind.StringKeyword)
})
],
body: factory.Block.create({
statements: [
factory.VariableStatement.create({
declarationList: factory.VariableDeclarationList.create({
flag: "const",
declarations: [
factory.VariableDeclaration.create({
name: "_baseUrl",
initializer: factory.CallExpression.create({
expression: factory.PropertyAccessExpression.create({
expression: "baseUrl",
name: "replace"
}),
argumentsArray: [factory.RegularExpressionLiteral.create({ text: "/\\/$/" }), factory.StringLiteral.create({ text: "" })]
})
})
]
})
}),
returnValue
],
multiLine: true
})
});
return factory.VariableStatement.create({
modifiers: [ts4.factory.createToken(ts4.SyntaxKind.ExportKeyword)],
declarationList: factory.VariableDeclarationList.create({
declarations: [
factory.VariableDeclaration.create({
name: "createClient",
initializer: arrowFunction
})
],
flag: "const"
})
});
};
// src/code-templates/functional-api-client/FunctionalApiClient/ClientTypeDefinition.ts
var create14 = (factory) => {
return [
factory.TypeAliasDeclaration.create({
name: "ClientFunction<RequestOption>",
type: factory.TypeReferenceNode.create({
name: "typeof createClient<RequestOption>"
})
}),
factory.TypeAliasDeclaration.create({
export: true,
name: "Client<RequestOption>",
type: factory.TypeReferenceNode.create({
name: "ReturnType<ClientFunction<RequestOption>>"
})
})
];
};
// src/code-templates/functional-api-client/index.ts
var generator2 = (codeGeneratorParamsList, option) => {
const statements = [];
const factory = TsGenerator_exports.Factory.create();
codeGeneratorParamsList.forEach((codeGeneratorParams) => {
const { convertedParams } = codeGeneratorParams;
if (convertedParams.hasRequestBody) {
statements.push(createRequestContentTypeReference(factory, codeGeneratorParams));
}
if (convertedParams.responseSuccessNames.length > 0) {
statements.push(createResponseContentTypeReference(factory, codeGeneratorParams));
}
const typeDeclaration = create(factory, codeGeneratorParams);
if (typeDeclaration) {
statements.push(typeDeclaration);
}
});
create2(factory, codeGeneratorParamsList, "function", option || {}).forEach((statement) => {
statements.push(statement);
});
const apiClientStatement = create13(factory, codeGeneratorParamsList, option || {});
statements.push(apiClientStatement);
create14(factory).forEach((statement) => {
statements.push(statement);
});
return statements;
};
// src/code-templates/currying-functional-api-client/index.ts
var currying_functional_api_client_exports = {};
__export(currying_functional_api_client_exports, {
generator: () => generator3
});
// src/code-templates/currying-functional-api-client/FunctionalApiClient/index.ts
import { EOL as EOL3 } from "os";
import ts6 from "typescript";
// src/code-templates/currying-functional-api-client/FunctionalApiClient/CurryingArrowFunction.ts
import ts5 from "typescript";
var generateParams3 = (factory, { convertedParams }) => {
const typeArguments = [];
if (convertedParams.has2OrMoreRequestContentTypes) {
typeArguments.push(
factory.TypeReferenceNode.create({
name: "RequestContentType"
})
);
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
typeArguments.push(
factory.TypeReferenceNode.create({
name: "ResponseContentType"
})
);
}
return factory.ParameterDeclaration.create({
name: "params",
modifiers: void 0,
type: factory.TypeReferenceNode.create({
name: convertedParams.argumentParamsTypeDeclaration,
typeArguments
})
});
};
var generateResponseReturnType3 = (factory, successResponseNameList, successResponseContentTypeList, option) => {
let objectType = factory.TypeNode.create({
type: "void"
});
if (successResponseNameList.length === 1) {
objectType = factory.TypeReferenceNode.create({
name: successResponseNameList[0]
});
} else if (successResponseNameList.length > 1) {
objectType = factory.UnionTypeNode.create({
typeNodes: successResponseNameList.map((item) => factory.TypeReferenceNode.create({ name: item }))
});
}
if (successResponseNameList.length === 0) {
if (option.sync) {
return objectType;
}
return factory.TypeReferenceNode.create({
name: "Promise",
typeArguments: [objectType]
});
}
const isOnlyOneResponseContentType = successResponseContentTypeList.length === 1;
let indexType = factory.TypeReferenceNode.create({
name: "ResponseContentType"
});
if (isOnlyOneResponseContentType) {
indexType = factory.TypeReferenceNode.create({
name: `"${successResponseContentTypeList[0]}"`
});
}
if (option.sync) {
return factory.IndexedAccessTypeNode.create({
objectType,
indexType
});
}
return factory.TypeReferenceNode.create({
name: "Promise",
typeArguments: [
factory.IndexedAccessTypeNode.create({
objectType,
indexType
})
]
});
};
var methodTypeParameters3 = (factory, { convertedParams }) => {
const typeParameters = [];
if (convertedParams.has2OrMoreRequestContentTypes) {
typeParameters.push(
factory.TypeParameterDeclaration.create({
name: "RequestContentType",
constraint: factory.TypeReferenceNode.create({
name: convertedParams.requestContentTypeName
})
})
);
}
if (convertedParams.has2OrMoreSuccessResponseContentTypes) {
typeParameters.push(
factory.TypeParameterDeclaration.create({
name: "ResponseContentType",
constraint: factory.TypeReferenceNode.create({
name: convertedParams.responseContentTypeName
})
})
);
}
return typeParameters;
};
var create15 = (factory, params, option) => {
const { convertedParams } = params;
const typeParameters = methodTypeParameters3(factory, params);
const methodArguments = [];
const hasParamsArguments = conv