Skip to content

Commit 7f98a70

Browse files
committed
chore: prettier fmt
1 parent 0440b2b commit 7f98a70

File tree

11 files changed

+129
-96
lines changed

11 files changed

+129
-96
lines changed

packages/typed-openapi/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
"dev": "tsup --watch",
2222
"build": "tsup",
2323
"test": "vitest",
24+
"fmt": "prettier --write src",
2425
"typecheck": "tsc -b ./tsconfig.build.json"
2526
},
2627
"dependencies": {

packages/typed-openapi/src/cli.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,14 @@ cli
1515
`Runtime to use for validation; defaults to \`none\`; available: ${allowedRuntimes.toString()}`,
1616
{ default: "none" },
1717
)
18-
.option("--tanstack [name]", "Generate tanstack client, defaults to false, can optionally specify a name for the generated file")
1918
.option(
2019
"--schemas-only",
2120
"Only generate schemas, skipping client generation (defaults to false)",
22-
{ default : false },
21+
{ default: false },
22+
)
23+
.option(
24+
"--tanstack [name]",
25+
"Generate tanstack client, defaults to false, can optionally specify a name for the generated file",
2326
)
2427
.action(async (input, _options) => {
2528
return generateClientFiles(input, _options);

packages/typed-openapi/src/generator.ts

Lines changed: 89 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,17 @@ const replacerByRuntime = {
4646
yup: (line: string) =>
4747
line
4848
.replace(/y\.InferType<\s*?typeof (.*?)\s*?>/g, "typeof $1")
49-
.replace(new RegExp(`(${endpointExport.source})` + new RegExp(/([\s\S]*? )(y\.object)(\()/).source, "g"), "$1$2("),
49+
.replace(
50+
new RegExp(`(${endpointExport.source})` + new RegExp(/([\s\S]*? )(y\.object)(\()/).source, "g"),
51+
"$1$2(",
52+
),
5053
zod: (line: string) =>
5154
line
5255
.replace(/z\.infer<\s*?typeof (.*?)\s*?>/g, "typeof $1")
53-
.replace(new RegExp(`(${endpointExport.source})` + new RegExp(/([\s\S]*? )(z\.object)(\()/).source, "g"), "$1$2("),
56+
.replace(
57+
new RegExp(`(${endpointExport.source})` + new RegExp(/([\s\S]*? )(z\.object)(\()/).source, "g"),
58+
"$1$2(",
59+
),
5460
};
5561

5662
export const generateFile = (options: GeneratorOptions) => {
@@ -64,36 +70,36 @@ export const generateFile = (options: GeneratorOptions) => {
6470
ctx.runtime === "none"
6571
? (file: string) => file
6672
: (file: string) => {
67-
const model = Codegen.TypeScriptToModel.Generate(file);
68-
const transformer = runtimeValidationGenerator[ctx.runtime as Exclude<typeof ctx.runtime, "none">];
69-
// tmp fix for typebox, there's currently a "// todo" only with Codegen.ModelToTypeBox.Generate
70-
// https://github.com/sinclairzx81/typebox-codegen/blob/44d44d55932371b69f349331b1c8a60f5d760d9e/src/model/model-to-typebox.ts#L31
71-
const generated = ctx.runtime === "typebox" ? Codegen.TypeScriptToTypeBox.Generate(file) : transformer(model);
72-
73-
let converted = "";
74-
const match = generated.match(/(const __ENDPOINTS_START__ =)([\s\S]*?)(export type __ENDPOINTS_END__)/);
75-
const content = match?.[2];
76-
77-
if (content && ctx.runtime in replacerByRuntime) {
78-
const before = generated.slice(0, generated.indexOf("export type __ENDPOINTS_START"));
79-
converted =
80-
before +
81-
replacerByRuntime[ctx.runtime as keyof typeof replacerByRuntime](
82-
content.slice(content.indexOf("export")),
83-
);
84-
} else {
85-
converted = generated;
86-
}
73+
const model = Codegen.TypeScriptToModel.Generate(file);
74+
const transformer = runtimeValidationGenerator[ctx.runtime as Exclude<typeof ctx.runtime, "none">];
75+
// tmp fix for typebox, there's currently a "// todo" only with Codegen.ModelToTypeBox.Generate
76+
// https://github.com/sinclairzx81/typebox-codegen/blob/44d44d55932371b69f349331b1c8a60f5d760d9e/src/model/model-to-typebox.ts#L31
77+
const generated = ctx.runtime === "typebox" ? Codegen.TypeScriptToTypeBox.Generate(file) : transformer(model);
78+
79+
let converted = "";
80+
const match = generated.match(/(const __ENDPOINTS_START__ =)([\s\S]*?)(export type __ENDPOINTS_END__)/);
81+
const content = match?.[2];
82+
83+
if (content && ctx.runtime in replacerByRuntime) {
84+
const before = generated.slice(0, generated.indexOf("export type __ENDPOINTS_START"));
85+
converted =
86+
before +
87+
replacerByRuntime[ctx.runtime as keyof typeof replacerByRuntime](
88+
content.slice(content.indexOf("export")),
89+
);
90+
} else {
91+
converted = generated;
92+
}
8793

88-
return converted;
89-
};
94+
return converted;
95+
};
9096

9197
const file = `
9298
${transform(schemaList + endpointSchemaList)}
9399
${apiClient}
94100
`;
95101

96-
return (file);
102+
return file;
97103
};
98104

99105
const generateSchemaList = ({ refs, runtime }: GeneratorContext) => {
@@ -138,36 +144,39 @@ const generateEndpointSchemaList = (ctx: GeneratorContext) => {
138144
method: "${endpoint.method.toUpperCase()}",
139145
path: "${endpoint.path}",
140146
requestFormat: "${endpoint.requestFormat}",
141-
${endpoint.meta.hasParameters
142-
? `parameters: {
147+
${
148+
endpoint.meta.hasParameters
149+
? `parameters: {
143150
${parameters.query ? `query: ${parameterObjectToString(parameters.query)},` : ""}
144151
${parameters.path ? `path: ${parameterObjectToString(parameters.path)},` : ""}
145152
${parameters.header ? `header: ${parameterObjectToString(parameters.header)},` : ""}
146-
${parameters.body
147-
? `body: ${parameterObjectToString(
148-
ctx.runtime === "none"
149-
? parameters.body.recompute((box) => {
150-
if (Box.isReference(box) && !box.params.generics) {
151-
box.value = `Schemas.${box.value}`;
152-
}
153-
return box;
154-
})
155-
: parameters.body,
156-
)},`
157-
: ""
153+
${
154+
parameters.body
155+
? `body: ${parameterObjectToString(
156+
ctx.runtime === "none"
157+
? parameters.body.recompute((box) => {
158+
if (Box.isReference(box) && !box.params.generics) {
159+
box.value = `Schemas.${box.value}`;
160+
}
161+
return box;
162+
})
163+
: parameters.body,
164+
)},`
165+
: ""
158166
}
159167
}`
160-
: "parameters: never,"
168+
: "parameters: never,"
161169
}
162-
response: ${ctx.runtime === "none"
163-
? endpoint.response.recompute((box) => {
164-
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
165-
box.value = `Schemas.${box.value}`;
166-
}
167-
168-
return box;
169-
}).value
170-
: endpoint.response.value
170+
response: ${
171+
ctx.runtime === "none"
172+
? endpoint.response.recompute((box) => {
173+
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
174+
box.value = `Schemas.${box.value}`;
175+
}
176+
177+
return box;
178+
}).value
179+
: endpoint.response.value
171180
},
172181
}\n`;
173182
});
@@ -190,14 +199,14 @@ const generateEndpointByMethod = (ctx: GeneratorContext) => {
190199
// <EndpointByMethod>
191200
export ${ctx.runtime === "none" ? "type" : "const"} EndpointByMethod = {
192201
${Object.entries(byMethods)
193-
.map(([method, list]) => {
194-
return `${method}: {
202+
.map(([method, list]) => {
203+
return `${method}: {
195204
${list.map(
196-
(endpoint) => `"${endpoint.path}": ${ctx.runtime === "none" ? "Endpoints." : ""}${endpoint.meta.alias}`,
197-
)}
205+
(endpoint) => `"${endpoint.path}": ${ctx.runtime === "none" ? "Endpoints." : ""}${endpoint.meta.alias}`,
206+
)}
198207
}`;
199-
})
200-
.join(",\n")}
208+
})
209+
.join(",\n")}
201210
}
202211
${ctx.runtime === "none" ? "" : "export type EndpointByMethod = typeof EndpointByMethod;"}
203212
// </EndpointByMethod>
@@ -264,7 +273,6 @@ type MaybeOptionalArg<T> = RequiredKeys<T> extends never ? [config?: T] : [confi
264273
// </ApiClientTypes>
265274
`;
266275

267-
268276
const apiClient = `
269277
// <ApiClient>
270278
export class ApiClient {
@@ -286,22 +294,22 @@ export class ApiClient {
286294
}
287295
288296
${Object.entries(byMethods)
289-
.map(([method, endpointByMethod]) => {
290-
const capitalizedMethod = capitalize(method);
291-
const infer = inferByRuntime[ctx.runtime];
297+
.map(([method, endpointByMethod]) => {
298+
const capitalizedMethod = capitalize(method);
299+
const infer = inferByRuntime[ctx.runtime];
292300
293-
return endpointByMethod.length
294-
? `// <ApiClient.${method}>
301+
return endpointByMethod.length
302+
? `// <ApiClient.${method}>
295303
${method}<Path extends keyof ${capitalizedMethod}Endpoints, TEndpoint extends ${capitalizedMethod}Endpoints[Path]>(
296304
path: Path,
297305
...params: MaybeOptionalArg<${match(ctx.runtime)
298-
.with("zod", "yup", () => infer(`TEndpoint["parameters"]`))
299-
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["parameters"]`)
300-
.otherwise(() => `TEndpoint["parameters"]`)}>
306+
.with("zod", "yup", () => infer(`TEndpoint["parameters"]`))
307+
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["parameters"]`)
308+
.otherwise(() => `TEndpoint["parameters"]`)}>
301309
): Promise<${match(ctx.runtime)
302-
.with("zod", "yup", () => infer(`TEndpoint["response"]`))
303-
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["response"]`)
304-
.otherwise(() => `TEndpoint["response"]`)}> {
310+
.with("zod", "yup", () => infer(`TEndpoint["response"]`))
311+
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["response"]`)
312+
.otherwise(() => `TEndpoint["response"]`)}> {
305313
return this.fetcher("${method}", this.baseUrl + path, params[0])
306314
.then(response => this.parseResponse(response))${match(ctx.runtime)
307315
.with("zod", "yup", () => `as Promise<${infer(`TEndpoint["response"]`)}>`)
@@ -310,9 +318,9 @@ export class ApiClient {
310318
}
311319
// </ApiClient.${method}>
312320
`
313-
: "";
314-
})
315-
.join("\n")}
321+
: "";
322+
})
323+
.join("\n")}
316324
317325
// <ApiClient.request>
318326
/**
@@ -326,9 +334,17 @@ export class ApiClient {
326334
method: TMethod,
327335
path: TPath,
328336
...params: MaybeOptionalArg<${match(ctx.runtime)
329-
.with("zod", "yup", () => inferByRuntime[ctx.runtime](`TEndpoint extends { parameters: infer Params } ? Params : never`))
330-
.with("arktype", "io-ts", "typebox", "valibot", () => inferByRuntime[ctx.runtime](`TEndpoint`) + `["parameters"]`)
331-
.otherwise(() => `TEndpoint extends { parameters: infer Params } ? Params : never`)}>)
337+
.with("zod", "yup", () =>
338+
inferByRuntime[ctx.runtime](`TEndpoint extends { parameters: infer Params } ? Params : never`),
339+
)
340+
.with(
341+
"arktype",
342+
"io-ts",
343+
"typebox",
344+
"valibot",
345+
() => inferByRuntime[ctx.runtime](`TEndpoint`) + `["parameters"]`,
346+
)
347+
.otherwise(() => `TEndpoint extends { parameters: infer Params } ? Params : never`)}>)
332348
: Promise<Omit<Response, "json"> & {
333349
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */
334350
json: () => Promise<TEndpoint extends { response: infer Res } ? Res : never>;

packages/typed-openapi/src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export * from "./box-factory.ts";
22
export { generateFile, type OutputRuntime } from "./generator.ts";
3-
export * from "./tanstack-query.generator.ts"
3+
export * from "./tanstack-query.generator.ts";
44
export * from "./map-openapi-endpoints.ts";
55
export * from "./openapi-schema-to-ts.ts";
66
export * from "./ref-resolver.ts";

packages/typed-openapi/src/map-openapi-endpoints.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,16 @@ export const mapOpenApiEndpoints = (doc: OpenAPIObject) => {
6464
);
6565

6666
// Filter out empty objects
67-
const params = Object.entries(paramObjects).reduce((acc, [key, value]) => {
68-
if (Object.keys(value).length) {
69-
// @ts-expect-error
70-
acc[key] = value;
71-
}
72-
return acc;
73-
}, {} as { query?: Record<string, Box>; path?: Record<string, Box>; header?: Record<string, Box>; body?: Box });
67+
const params = Object.entries(paramObjects).reduce(
68+
(acc, [key, value]) => {
69+
if (Object.keys(value).length) {
70+
// @ts-expect-error
71+
acc[key] = value;
72+
}
73+
return acc;
74+
},
75+
{} as { query?: Record<string, Box>; path?: Record<string, Box>; header?: Record<string, Box>; body?: Box },
76+
);
7477

7578
// Body
7679
if (operation.requestBody) {
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
export { prettify } from "./format.ts";
2-
export { generateClientFiles } from "./generate-client-files.ts"
2+
export { generateClientFiles } from "./generate-client-files.ts";

packages/typed-openapi/src/openapi-schema-to-ts.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,12 @@ export const openApiSchemaToTs = ({ schema, meta: _inheritedMeta, ctx }: Openapi
100100

101101
if (schemaType === "object" || schema.properties || schema.additionalProperties) {
102102
if (!schema.properties) {
103-
if (schema.additionalProperties && !isReferenceObject(schema.additionalProperties) && typeof schema.additionalProperties !== "boolean" && schema.additionalProperties.type) {
103+
if (
104+
schema.additionalProperties &&
105+
!isReferenceObject(schema.additionalProperties) &&
106+
typeof schema.additionalProperties !== "boolean" &&
107+
schema.additionalProperties.type
108+
) {
104109
const valueSchema = openApiSchemaToTs({ schema: schema.additionalProperties, ctx, meta });
105110
return t.literal(`Record<string, ${valueSchema.value}>`);
106111
}

packages/typed-openapi/src/ref-resolver.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ export const createRefResolver = (doc: OpenAPIObject, factory: GenericFactory) =
119119
};
120120
};
121121

122-
export interface RefResolver extends ReturnType<typeof createRefResolver> { }
122+
export interface RefResolver extends ReturnType<typeof createRefResolver> {}
123123

124124
const setSchemaDependencies = (schema: LibSchemaObject, deps: Set<string>) => {
125125
const visit = (schema: LibSchemaObject | ReferenceObject): void => {

packages/typed-openapi/src/string-utils.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,8 @@ const prefixStringStartingWithNumberIfNeeded = (str: string) => {
3535
const pathParamWithBracketsRegex = /({\w+})/g;
3636
const wordPrecededByNonWordCharacter = /[^\w\-]+/g;
3737

38-
3938
/** @example turns `/media-objects/{id}` into `MediaObjectsId` */
4039
export const pathToVariableName = (path: string) =>
41-
capitalize(kebabToCamel((path)).replaceAll("/", "_")) // /media-objects/{id} -> MediaObjects{id}
40+
capitalize(kebabToCamel(path).replaceAll("/", "_")) // /media-objects/{id} -> MediaObjects{id}
4241
.replace(pathParamWithBracketsRegex, (group) => capitalize(group.slice(1, -1))) // {id} -> Id
4342
.replace(wordPrecededByNonWordCharacter, "_"); // "/robots.txt" -> "/robots_txt"

packages/typed-openapi/src/tanstack-query.generator.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ import { capitalize } from "pastable/server";
22
import { prettify } from "./format.ts";
33
import type { mapOpenApiEndpoints } from "./map-openapi-endpoints.ts";
44

5-
type GeneratorOptions = ReturnType<typeof mapOpenApiEndpoints>
5+
type GeneratorOptions = ReturnType<typeof mapOpenApiEndpoints>;
66
type GeneratorContext = Required<GeneratorOptions>;
77

88
export const generateTanstackQueryFile = async (ctx: GeneratorContext & { relativeApiClientPath: string }) => {
9-
const endpointMethods = (new Set(ctx.endpointList.map((endpoint) => endpoint.method.toLowerCase())));
9+
const endpointMethods = new Set(ctx.endpointList.map((endpoint) => endpoint.method.toLowerCase()));
1010

11-
const file = `
11+
const file = `
1212
import { queryOptions } from "@tanstack/react-query"
1313
import type { EndpointByMethod, ApiClient } from "${ctx.relativeApiClientPath}"
1414
@@ -44,7 +44,9 @@ export const generateTanstackQueryFile = async (ctx: GeneratorContext & { relati
4444
};
4545
4646
// <EndpointByMethod.Shorthands>
47-
${Array.from(endpointMethods).map((method) => `export type ${capitalize(method)}Endpoints = EndpointByMethod["${method}"];`).join("\n")}
47+
${Array.from(endpointMethods)
48+
.map((method) => `export type ${capitalize(method)}Endpoints = EndpointByMethod["${method}"];`)
49+
.join("\n")}
4850
// </EndpointByMethod.Shorthands>
4951
5052
// <ApiClientTypes>
@@ -67,7 +69,9 @@ export const generateTanstackQueryFile = async (ctx: GeneratorContext & { relati
6769
export class TanstackQueryApiClient {
6870
constructor(public client: ApiClient) { }
6971
70-
${Array.from(endpointMethods).map((method) => `
72+
${Array.from(endpointMethods)
73+
.map(
74+
(method) => `
7175
// <ApiClient.${method}>
7276
${method}<Path extends keyof ${capitalize(method)}Endpoints, TEndpoint extends ${capitalize(method)}Endpoints[Path]>(
7377
path: Path,
@@ -105,7 +109,9 @@ export const generateTanstackQueryFile = async (ctx: GeneratorContext & { relati
105109
return query
106110
}
107111
// </ApiClient.${method}>
108-
`).join("\n")}
112+
`,
113+
)
114+
.join("\n")}
109115
110116
// <ApiClient.request>
111117
/**
@@ -139,5 +145,5 @@ export const generateTanstackQueryFile = async (ctx: GeneratorContext & { relati
139145
}
140146
`;
141147

142-
return prettify(file);
148+
return prettify(file);
143149
};

0 commit comments

Comments
 (0)