@7nohe/openapi-react-query-codegen 4.0.0-beta.3 → 4.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/AGENTS.md +8 -4
  2. package/README.md +2 -2
  3. package/dist/client/emitSchemas.mjs +12 -9
  4. package/dist/client/emitSdk.d.mts +2 -0
  5. package/dist/client/emitSdk.mjs +24 -27
  6. package/dist/client/emitTransformers.mjs +21 -72
  7. package/dist/client/emitTypes.d.mts +2 -1
  8. package/dist/client/emitTypes.mjs +5 -5
  9. package/dist/client/index.mjs +13 -5
  10. package/dist/client/naming.d.mts +5 -2
  11. package/dist/client/naming.mjs +7 -3
  12. package/dist/client/operations.d.mts +3 -2
  13. package/dist/client/operations.mjs +16 -48
  14. package/dist/client/runtime/axios.runtime.ts +15 -10
  15. package/dist/client/schema.d.mts +24 -2
  16. package/dist/client/schema.mjs +135 -33
  17. package/dist/client/spec.d.mts +6 -0
  18. package/dist/client/spec.mjs +15 -5
  19. package/dist/common.d.mts +0 -2
  20. package/dist/common.mjs +0 -10
  21. package/dist/createSource.d.mts +1 -1
  22. package/dist/createSource.mjs +1 -3
  23. package/dist/format.d.mts +0 -1
  24. package/dist/format.mjs +0 -20
  25. package/dist/generate.mjs +2 -4
  26. package/dist/{tsmorph → hooks}/buildCommon.d.mts +13 -17
  27. package/dist/hooks/buildCommon.mjs +132 -0
  28. package/dist/{tsmorph → hooks}/buildMutationHooks.d.mts +4 -3
  29. package/dist/hooks/buildMutationHooks.mjs +24 -0
  30. package/dist/{tsmorph → hooks}/buildQueryHooks.d.mts +22 -16
  31. package/dist/{tsmorph → hooks}/buildQueryHooks.mjs +35 -106
  32. package/dist/{tsmorph → hooks}/buildQueryOptions.d.mts +5 -4
  33. package/dist/{tsmorph → hooks}/buildQueryOptions.mjs +9 -35
  34. package/dist/{tsmorph → hooks}/generateFiles.d.mts +1 -1
  35. package/dist/hooks/generateFiles.mjs +122 -0
  36. package/dist/hooks/hookNames.d.mts +69 -0
  37. package/dist/hooks/hookNames.mjs +82 -0
  38. package/dist/hooks/imports.d.mts +46 -0
  39. package/dist/hooks/imports.mjs +115 -0
  40. package/dist/hooks/operationNames.d.mts +15 -0
  41. package/dist/hooks/operationNames.mjs +31 -0
  42. package/dist/hooks/statement.d.mts +43 -0
  43. package/dist/hooks/statement.mjs +63 -0
  44. package/dist/types.d.mts +5 -7
  45. package/package.json +3 -5
  46. package/dist/print.d.mts +0 -5
  47. package/dist/print.mjs +0 -22
  48. package/dist/tsmorph/buildCommon.mjs +0 -183
  49. package/dist/tsmorph/buildMutationHooks.mjs +0 -36
  50. package/dist/tsmorph/generateFiles.mjs +0 -153
  51. package/dist/tsmorph/index.d.mts +0 -5
  52. package/dist/tsmorph/index.mjs +0 -5
  53. package/dist/tsmorph/operationNames.d.mts +0 -5
  54. package/dist/tsmorph/operationNames.mjs +0 -9
  55. package/dist/tsmorph/projectFactory.d.mts +0 -58
  56. package/dist/tsmorph/projectFactory.mjs +0 -169
package/dist/print.mjs DELETED
@@ -1,22 +0,0 @@
1
- import { mkdir, writeFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import { buildQueriesOutputPath, exists } from "./common.mjs";
4
- async function printGeneratedTS(result, options) {
5
- const dir = buildQueriesOutputPath(options.output);
6
- const dirExists = await exists(dir);
7
- if (!dirExists) {
8
- await mkdir(dir, { recursive: true });
9
- }
10
- await writeFile(path.join(dir, result.name), result.content);
11
- }
12
- export async function print(results, options) {
13
- const outputPath = options.output;
14
- const dirExists = await exists(outputPath);
15
- if (!dirExists) {
16
- await mkdir(outputPath);
17
- }
18
- const promises = results.map(async (result) => {
19
- await printGeneratedTS(result, options);
20
- });
21
- await Promise.all(promises);
22
- }
@@ -1,183 +0,0 @@
1
- import { StructureKind, VariableDeclarationKind, } from "ts-morph";
2
- import { getDataTypeName } from "./operationNames.mjs";
3
- /**
4
- * Build the default response type alias.
5
- * Example: export type FindPetsDefaultResponse = Awaited<ReturnType<typeof findPets>>["data"];
6
- */
7
- export function buildDefaultResponseType(op) {
8
- return {
9
- kind: StructureKind.TypeAlias,
10
- isExported: true,
11
- name: `${op.capitalizedMethodName}DefaultResponse`,
12
- type: `Awaited<ReturnType<typeof ${op.methodName}>>["data"]`,
13
- };
14
- }
15
- /**
16
- * Build the query result type alias.
17
- * Example: export type FindPetsQueryResult<TData = FindPetsDefaultResponse, TError = unknown> = UseQueryResult<TData, TError>;
18
- */
19
- export function buildQueryResultType(op) {
20
- return {
21
- kind: StructureKind.TypeAlias,
22
- isExported: true,
23
- name: `${op.capitalizedMethodName}QueryResult`,
24
- typeParameters: [
25
- { name: "TData", default: `${op.capitalizedMethodName}DefaultResponse` },
26
- { name: "TError", default: "unknown" },
27
- ],
28
- type: "UseQueryResult<TData, TError>",
29
- };
30
- }
31
- /**
32
- * Build the mutation result type alias.
33
- * Example: export type AddPetMutationResult = Awaited<ReturnType<typeof addPet>>;
34
- */
35
- export function buildMutationResultType(op) {
36
- return {
37
- kind: StructureKind.TypeAlias,
38
- isExported: true,
39
- name: `${op.capitalizedMethodName}MutationResult`,
40
- type: `Awaited<ReturnType<typeof ${op.methodName}>>`,
41
- };
42
- }
43
- /**
44
- * Build query key constant.
45
- * Example: export const useFindPetsKey = "FindPets";
46
- */
47
- export function buildQueryKeyConst(op) {
48
- return {
49
- kind: StructureKind.VariableStatement,
50
- isExported: true,
51
- declarationKind: VariableDeclarationKind.Const,
52
- declarations: [
53
- {
54
- name: `use${op.capitalizedMethodName}Key`,
55
- initializer: `"${op.capitalizedMethodName}"`,
56
- },
57
- ],
58
- };
59
- }
60
- /**
61
- * Build mutation key constant.
62
- * Example: export const useAddPetKey = "AddPet";
63
- */
64
- export function buildMutationKeyConst(op) {
65
- return {
66
- kind: StructureKind.VariableStatement,
67
- isExported: true,
68
- declarationKind: VariableDeclarationKind.Const,
69
- declarations: [
70
- {
71
- name: `use${op.capitalizedMethodName}Key`,
72
- initializer: `"${op.capitalizedMethodName}"`,
73
- },
74
- ],
75
- };
76
- }
77
- /**
78
- * Build query key function.
79
- * Example: export const UseFindPetsKeyFn = (clientOptions: Options<FindPetsData, true> = {}, queryKey?: Array<unknown>) =>
80
- * [useFindPetsKey, ...(queryKey ?? [clientOptions])];
81
- */
82
- export function buildQueryKeyFn(op) {
83
- const dataTypeName = getDataTypeName(op);
84
- const params = [];
85
- const defaultValue = op.allParamsOptional ? " = {}" : "";
86
- params.push(`clientOptions: Options<${dataTypeName}, true>${defaultValue}`);
87
- params.push("queryKey?: Array<unknown>");
88
- const fallbackArray = "[clientOptions]";
89
- return {
90
- kind: StructureKind.VariableStatement,
91
- isExported: true,
92
- declarationKind: VariableDeclarationKind.Const,
93
- declarations: [
94
- {
95
- name: `Use${op.capitalizedMethodName}KeyFn`,
96
- initializer: `(${params.join(", ")}) => [use${op.capitalizedMethodName}Key, ...(queryKey ?? ${fallbackArray})]`,
97
- },
98
- ],
99
- };
100
- }
101
- /**
102
- * Build mutation key function.
103
- * Example: export const UseAddPetKeyFn = (mutationKey?: Array<unknown>) =>
104
- * [useAddPetKey, ...(mutationKey ?? [])];
105
- */
106
- export function buildMutationKeyFn(op) {
107
- return {
108
- kind: StructureKind.VariableStatement,
109
- isExported: true,
110
- declarationKind: VariableDeclarationKind.Const,
111
- declarations: [
112
- {
113
- name: `Use${op.capitalizedMethodName}KeyFn`,
114
- initializer: `(mutationKey?: Array<unknown>) => [use${op.capitalizedMethodName}Key, ...(mutationKey ?? [])]`,
115
- },
116
- ],
117
- };
118
- }
119
- /**
120
- * Build the client options type for infinite queries.
121
- * The page parameter is excluded because TanStack Query supplies it via the
122
- * pageParam mechanism (#140).
123
- * Example:
124
- * export type FindPaginatedPetsInfiniteClientOptions = Omit<Options<FindPaginatedPetsData, true>, "query"> &
125
- * { query?: Omit<NonNullable<FindPaginatedPetsData["query"]>, "page"> };
126
- */
127
- export function buildInfiniteClientOptionsType(op, ctx) {
128
- const dataTypeName = getDataTypeName(op);
129
- const type = `Omit<Options<${dataTypeName}, true>, "query"> & { query?: Omit<NonNullable<${dataTypeName}["query"]>, "${ctx.pageParam}"> }`;
130
- return {
131
- kind: StructureKind.TypeAlias,
132
- isExported: true,
133
- name: `${op.capitalizedMethodName}InfiniteClientOptions`,
134
- type,
135
- };
136
- }
137
- /**
138
- * Build the infinite query key constant.
139
- * Shares the plain query key as its first segment so a single
140
- * `invalidateQueries({ queryKey: [useXKey] })` matches both the plain and the
141
- * infinite cache entries of an operation (#174), while the extra "infinite"
142
- * segment keeps cached InfiniteData from colliding with plain query data (#140).
143
- * Example: export const useFindPaginatedPetsInfiniteKey = [useFindPaginatedPetsKey, "infinite"] as const;
144
- */
145
- export function buildInfiniteQueryKeyConst(op) {
146
- return {
147
- kind: StructureKind.VariableStatement,
148
- isExported: true,
149
- declarationKind: VariableDeclarationKind.Const,
150
- declarations: [
151
- {
152
- name: `use${op.capitalizedMethodName}InfiniteKey`,
153
- initializer: `[use${op.capitalizedMethodName}Key, "infinite"] as const`,
154
- },
155
- ],
156
- };
157
- }
158
- /**
159
- * Build the infinite query key function.
160
- * The custom queryKey argument only replaces the params segment — the
161
- * hierarchical [opKey, "infinite"] prefix is always preserved so
162
- * prefix-based invalidation keeps working.
163
- * Example: export const UseFindPaginatedPetsInfiniteKeyFn = (clientOptions: FindPaginatedPetsInfiniteClientOptions = {}, queryKey?: Array<unknown>) =>
164
- * [...useFindPaginatedPetsInfiniteKey, ...(queryKey ?? [clientOptions])];
165
- */
166
- export function buildInfiniteQueryKeyFn(op) {
167
- const defaultValue = op.allParamsOptional ? " = {}" : "";
168
- const params = [
169
- `clientOptions: ${op.capitalizedMethodName}InfiniteClientOptions${defaultValue}`,
170
- "queryKey?: Array<unknown>",
171
- ];
172
- return {
173
- kind: StructureKind.VariableStatement,
174
- isExported: true,
175
- declarationKind: VariableDeclarationKind.Const,
176
- declarations: [
177
- {
178
- name: `Use${op.capitalizedMethodName}InfiniteKeyFn`,
179
- initializer: `(${params.join(", ")}) => [...use${op.capitalizedMethodName}InfiniteKey, ...(queryKey ?? [clientOptions])]`,
180
- },
181
- ],
182
- };
183
- }
@@ -1,36 +0,0 @@
1
- import { StructureKind, VariableDeclarationKind, } from "ts-morph";
2
- import { SDK_CALL_ARGS } from "./buildQueryHooks.mjs";
3
- import { getDataTypeName, getErrorType } from "./operationNames.mjs";
4
- /**
5
- * Build useMutation hook.
6
- * Example:
7
- * export const useAddPet = <TData = Common.AddPetMutationResult, TError = AddPetError, TQueryKey extends Array<unknown> = unknown[], TContext = unknown>(
8
- * mutationKey?: TQueryKey,
9
- * options?: Omit<UseMutationOptions<TData, TError, Options<AddPetData, true>, TContext>, "mutationKey" | "mutationFn">
10
- * ) => useMutation<TData, TError, Options<AddPetData, true>, TContext>({
11
- * mutationKey: Common.UseAddPetKeyFn(mutationKey),
12
- * mutationFn: clientOptions => addPet(clientOptions) as unknown as Promise<TData>,
13
- * ...options
14
- * });
15
- */
16
- export function buildUseMutationHook(op, ctx) {
17
- const hookName = `use${op.capitalizedMethodName}`;
18
- const errorType = getErrorType(op, ctx);
19
- const dataTypeDefault = `Common.${op.capitalizedMethodName}MutationResult`;
20
- const optionsType = `Options<${getDataTypeName(op)}, true>`;
21
- const mutationFn = `clientOptions => ${op.methodName}(${SDK_CALL_ARGS}) as unknown as Promise<TData>`;
22
- const body = `useMutation<TData, TError, ${optionsType}, TContext>({ mutationKey: Common.Use${op.capitalizedMethodName}KeyFn(mutationKey), mutationFn: ${mutationFn}, ...options })`;
23
- return {
24
- kind: StructureKind.VariableStatement,
25
- // Copy the operation's JSDoc (description and @deprecated) from the SDK function
26
- leadingTrivia: op.jsDoc ? `${op.jsDoc}\n` : undefined,
27
- isExported: true,
28
- declarationKind: VariableDeclarationKind.Const,
29
- declarations: [
30
- {
31
- name: hookName,
32
- initializer: `<TData = ${dataTypeDefault}, TError = ${errorType}, TQueryKey extends Array<unknown> = unknown[], TContext = unknown>(mutationKey?: TQueryKey, options?: Omit<UseMutationOptions<TData, TError, ${optionsType}, TContext>, "mutationKey" | "mutationFn">) => ${body}`,
33
- },
34
- ],
35
- };
36
- }
@@ -1,153 +0,0 @@
1
- import { OpenApiRqFiles } from "../constants.mjs";
2
- import { buildDefaultResponseType, buildInfiniteClientOptionsType, buildInfiniteQueryKeyConst, buildInfiniteQueryKeyFn, buildMutationKeyConst, buildMutationKeyFn, buildMutationResultType, buildQueryKeyConst, buildQueryKeyFn, buildQueryResultType, } from "./buildCommon.mjs";
3
- import { buildUseMutationHook } from "./buildMutationHooks.mjs";
4
- import { buildEnsureQueryDataFn, buildPrefetchFn, buildPrefetchInfiniteQueryFn, buildUseInfiniteQueryHook, buildUseQueryHook, buildUseSuspenseInfiniteQueryHook, buildUseSuspenseQueryHook, } from "./buildQueryHooks.mjs";
5
- import { buildInfiniteQueryOptionsFn, buildQueryOptionsFn, } from "./buildQueryOptions.mjs";
6
- import { buildCommonFileImports, buildHookFileImports, buildQueryOptionsFileImports, createGenerationProject, relativeModule, } from "./projectFactory.mjs";
7
- /**
8
- * Build one variable statement per operation, skipping the ones the builder
9
- * declines. A builder returns null when the operation is out of its scope —
10
- * every infinite-query builder returns null for non-paginatable operations,
11
- * which is how the paginatable subset gets selected.
12
- */
13
- function collectStatements(operations, build) {
14
- const statements = [];
15
- for (const op of operations) {
16
- const statement = build(op);
17
- if (statement) {
18
- statements.push(statement);
19
- }
20
- }
21
- return statements;
22
- }
23
- /**
24
- * ts-morph separates statements of different kinds with a blank line when
25
- * they are added one at a time but not when they are added as a batch, so
26
- * restore the separator where the kind changes.
27
- */
28
- function separateKinds(statements) {
29
- return statements.map((statement, index) => index > 0 && statements[index - 1].kind !== statement.kind
30
- ? { ...statement, leadingTrivia: `\n${statement.leadingTrivia ?? ""}` }
31
- : statement);
32
- }
33
- const IDENTIFIER_RE = /[\p{ID_Start}_$][\p{ID_Continue}$]*/gu;
34
- /**
35
- * Create a generated file. Statements go in as one batch so ts-morph reparses
36
- * the file once, and only the model and service names the body actually
37
- * mentions are imported: importing thousands of unused names forced every
38
- * edit to rescan a huge import list and made the later import organising pass
39
- * slow on large specifications.
40
- */
41
- function createFile(name, ctx, buildImports, statements) {
42
- const project = createGenerationProject();
43
- const sourceFile = project.createSourceFile(`${name}.ts`, undefined, {
44
- overwrite: true,
45
- });
46
- sourceFile.addStatements(statements);
47
- const used = new Set(sourceFile.getFullText().match(IDENTIFIER_RE));
48
- sourceFile.insertImportDeclarations(0, buildImports({
49
- ...ctx,
50
- modelNames: ctx.modelNames.filter((model) => used.has(model)),
51
- serviceNames: ctx.serviceNames.filter((service) => used.has(service)),
52
- }));
53
- return sourceFile.getFullText();
54
- }
55
- /**
56
- * The content of index.ts, which needs no ts-morph project.
57
- */
58
- function indexFile(ctx) {
59
- return [
60
- OpenApiRqFiles.common,
61
- OpenApiRqFiles.queries,
62
- OpenApiRqFiles.queryOptions,
63
- ]
64
- .map((name) => `export * from "${relativeModule(`./${name}`, ctx)}";\n`)
65
- .join("");
66
- }
67
- function commonStatements(queries, mutations, ctx) {
68
- const statements = [];
69
- for (const op of queries) {
70
- statements.push(buildDefaultResponseType(op), buildQueryResultType(op), buildQueryKeyConst(op), buildQueryKeyFn(op));
71
- }
72
- // Dedicated infinite query types and keys for paginatable operations
73
- for (const op of queries.filter((query) => query.isPaginatable)) {
74
- statements.push(buildInfiniteClientOptionsType(op, ctx), buildInfiniteQueryKeyConst(op), buildInfiniteQueryKeyFn(op));
75
- }
76
- for (const op of mutations) {
77
- statements.push(buildMutationResultType(op), buildMutationKeyConst(op), buildMutationKeyFn(op));
78
- }
79
- return separateKinds(statements);
80
- }
81
- /**
82
- * Add the generated header comment to file content.
83
- */
84
- function addHeaderComment(content, version) {
85
- const comment = `// generated with @7nohe/openapi-react-query-codegen@${version} \n\n`;
86
- return comment + content;
87
- }
88
- /**
89
- * Generate all files using ts-morph.
90
- */
91
- export function generateAllFiles(operations, ctx) {
92
- const queries = operations.filter((op) => op.httpMethod === "GET");
93
- const mutations = operations.filter((op) => ["POST", "PUT", "PATCH", "DELETE"].includes(op.httpMethod));
94
- const files = [
95
- [
96
- OpenApiRqFiles.common,
97
- buildCommonFileImports,
98
- commonStatements(queries, mutations, ctx),
99
- ],
100
- [
101
- OpenApiRqFiles.queries,
102
- buildHookFileImports,
103
- [
104
- ...queries.map((op) => buildUseQueryHook(op, ctx)),
105
- ...mutations.map((op) => buildUseMutationHook(op, ctx)),
106
- ],
107
- ],
108
- [
109
- OpenApiRqFiles.queryOptions,
110
- buildQueryOptionsFileImports,
111
- [
112
- ...queries.map((op) => buildQueryOptionsFn(op)),
113
- ...collectStatements(queries, (op) => buildInfiniteQueryOptionsFn(op, ctx)),
114
- ],
115
- ],
116
- [
117
- OpenApiRqFiles.suspense,
118
- buildHookFileImports,
119
- [
120
- ...queries.map((op) => buildUseSuspenseQueryHook(op, ctx)),
121
- ...collectStatements(queries, (op) => buildUseSuspenseInfiniteQueryHook(op, ctx)),
122
- ],
123
- ],
124
- [
125
- OpenApiRqFiles.infiniteQueries,
126
- buildHookFileImports,
127
- collectStatements(queries, (op) => buildUseInfiniteQueryHook(op, ctx)),
128
- ],
129
- [
130
- OpenApiRqFiles.prefetch,
131
- buildHookFileImports,
132
- [
133
- ...queries.map((op) => buildPrefetchFn(op)),
134
- ...collectStatements(queries, (op) => buildPrefetchInfiniteQueryFn(op, ctx)),
135
- ],
136
- ],
137
- [
138
- OpenApiRqFiles.ensureQueryData,
139
- buildHookFileImports,
140
- queries.map((op) => buildEnsureQueryDataFn(op)),
141
- ],
142
- ];
143
- return [
144
- {
145
- name: `${OpenApiRqFiles.index}.ts`,
146
- content: addHeaderComment(indexFile(ctx), ctx.version),
147
- },
148
- ...files.map(([name, imports, statements]) => ({
149
- name: `${name}.ts`,
150
- content: addHeaderComment(createFile(name, ctx, imports, statements), ctx.version),
151
- })),
152
- ];
153
- }
@@ -1,5 +0,0 @@
1
- export * from "./buildCommon.mjs";
2
- export * from "./buildMutationHooks.mjs";
3
- export * from "./buildQueryHooks.mjs";
4
- export { generateAllFiles } from "./generateFiles.mjs";
5
- export { createGenerationProject } from "./projectFactory.mjs";
@@ -1,5 +0,0 @@
1
- export * from "./buildCommon.mjs";
2
- export * from "./buildMutationHooks.mjs";
3
- export * from "./buildQueryHooks.mjs";
4
- export { generateAllFiles } from "./generateFiles.mjs";
5
- export { createGenerationProject } from "./projectFactory.mjs";
@@ -1,5 +0,0 @@
1
- import type { GenerationContext, OperationInfo } from "../types.mjs";
2
- /** The generated Data type name, or unknown when there is none. */
3
- export declare function getDataTypeName(op: OperationInfo): string;
4
- /** The error type of an operation's hooks, wrapped for axios. */
5
- export declare function getErrorType(op: OperationInfo, ctx: GenerationContext): string;
@@ -1,9 +0,0 @@
1
- /** The generated Data type name, or unknown when there is none. */
2
- export function getDataTypeName(op) {
3
- return op.dataTypeName ?? "unknown";
4
- }
5
- /** The error type of an operation's hooks, wrapped for axios. */
6
- export function getErrorType(op, ctx) {
7
- const errorType = op.errorTypeName ?? "unknown";
8
- return ctx.client === "axios" ? `AxiosError<${errorType}>` : errorType;
9
- }
@@ -1,58 +0,0 @@
1
- import { type ImportDeclarationStructure, Project } from "ts-morph";
2
- import type { GenerationContext } from "../types.mjs";
3
- /**
4
- * Create a shared ts-morph Project for code generation.
5
- * Uses consistent formatting settings to match existing output.
6
- */
7
- export declare function createGenerationProject(): Project;
8
- /**
9
- * A relative module specifier, with the extension the consuming project's
10
- * module resolution asks for.
11
- */
12
- export declare function relativeModule(path: string, ctx?: Pick<GenerationContext, "importExtension">): string;
13
- /**
14
- * Build import structure for the Options type.
15
- * sdk.gen re-exports Options extended with `client` and `meta`, which the
16
- * base client Options lacks; hooks must accept those properties.
17
- */
18
- export declare function buildClientImport(ctx: GenerationContext): ImportDeclarationStructure;
19
- /**
20
- * Build import structure for TanStack Query.
21
- */
22
- export declare function buildQueryImport(): ImportDeclarationStructure;
23
- /**
24
- * Build import structure for the queryOptions/infiniteQueryOptions helpers.
25
- */
26
- export declare function buildQueryOptionsImport(): ImportDeclarationStructure;
27
- /**
28
- * Build import structure for services.
29
- */
30
- export declare function buildServiceImport(ctx: GenerationContext): ImportDeclarationStructure;
31
- /**
32
- * Build import structure for models.
33
- * Emitted as a type-only import so generated code compiles under
34
- * `verbatimModuleSyntax` (enabled by default in recent Vite templates).
35
- */
36
- export declare function buildModelImport(ctx: GenerationContext): ImportDeclarationStructure | null;
37
- /**
38
- * Build import structure for axios error type.
39
- */
40
- export declare function buildAxiosErrorImport(): ImportDeclarationStructure;
41
- /**
42
- * Build import for Common namespace.
43
- */
44
- export declare function buildCommonImport(ctx?: Pick<GenerationContext, "importExtension">): ImportDeclarationStructure;
45
- /**
46
- * Build all imports needed for the common file.
47
- */
48
- export declare function buildCommonFileImports(ctx: GenerationContext): ImportDeclarationStructure[];
49
- /**
50
- * Build all imports needed for hook files (queries, suspense, infinite).
51
- */
52
- export declare function buildHookFileImports(ctx: GenerationContext): ImportDeclarationStructure[];
53
- /**
54
- * Build all imports needed for the queryOptions file.
55
- * Narrower than the hook file imports: queryOptions only needs the
56
- * queryOptions/infiniteQueryOptions helpers, not the TanStack hooks.
57
- */
58
- export declare function buildQueryOptionsFileImports(ctx: GenerationContext): ImportDeclarationStructure[];
@@ -1,169 +0,0 @@
1
- import { IndentationText, NewLineKind, Project, QuoteKind, StructureKind, } from "ts-morph";
2
- /**
3
- * Create a shared ts-morph Project for code generation.
4
- * Uses consistent formatting settings to match existing output.
5
- */
6
- export function createGenerationProject() {
7
- return new Project({
8
- useInMemoryFileSystem: true,
9
- compilerOptions: {
10
- strict: true,
11
- },
12
- manipulationSettings: {
13
- indentationText: IndentationText.TwoSpaces,
14
- newLineKind: NewLineKind.LineFeed,
15
- quoteKind: QuoteKind.Double,
16
- useTrailingCommas: true,
17
- },
18
- });
19
- }
20
- /**
21
- * A relative module specifier, with the extension the consuming project's
22
- * module resolution asks for.
23
- */
24
- export function relativeModule(path, ctx) {
25
- return `${path}${ctx?.importExtension ?? ""}`;
26
- }
27
- /**
28
- * Build import structure for the Options type.
29
- * sdk.gen re-exports Options extended with `client` and `meta`, which the
30
- * base client Options lacks; hooks must accept those properties.
31
- */
32
- export function buildClientImport(ctx) {
33
- return {
34
- kind: StructureKind.ImportDeclaration,
35
- moduleSpecifier: relativeModule("../requests/sdk.gen", ctx),
36
- namedImports: [{ name: "Options", isTypeOnly: true }],
37
- };
38
- }
39
- /**
40
- * Build import structure for TanStack Query.
41
- */
42
- export function buildQueryImport() {
43
- return {
44
- kind: StructureKind.ImportDeclaration,
45
- moduleSpecifier: "@tanstack/react-query",
46
- namedImports: [
47
- { name: "QueryClient", isTypeOnly: true },
48
- { name: "useQuery" },
49
- { name: "useSuspenseQuery" },
50
- { name: "useInfiniteQuery" },
51
- { name: "useSuspenseInfiniteQuery" },
52
- { name: "useMutation" },
53
- { name: "UseQueryResult", isTypeOnly: true },
54
- { name: "UseQueryOptions", isTypeOnly: true },
55
- { name: "UseInfiniteQueryOptions", isTypeOnly: true },
56
- { name: "UseSuspenseInfiniteQueryOptions", isTypeOnly: true },
57
- { name: "UseMutationOptions", isTypeOnly: true },
58
- { name: "UseMutationResult", isTypeOnly: true },
59
- { name: "UseSuspenseQueryOptions", isTypeOnly: true },
60
- { name: "InfiniteData", isTypeOnly: true },
61
- { name: "FetchQueryOptions", isTypeOnly: true },
62
- { name: "FetchInfiniteQueryOptions", isTypeOnly: true },
63
- { name: "GetNextPageParamFunction", isTypeOnly: true },
64
- { name: "EnsureQueryDataOptions", isTypeOnly: true },
65
- ],
66
- };
67
- }
68
- /**
69
- * Build import structure for the queryOptions/infiniteQueryOptions helpers.
70
- */
71
- export function buildQueryOptionsImport() {
72
- return {
73
- kind: StructureKind.ImportDeclaration,
74
- moduleSpecifier: "@tanstack/react-query",
75
- namedImports: [
76
- { name: "queryOptions" },
77
- { name: "infiniteQueryOptions" },
78
- { name: "UseInfiniteQueryOptions", isTypeOnly: true },
79
- ],
80
- };
81
- }
82
- /**
83
- * Build import structure for services.
84
- */
85
- export function buildServiceImport(ctx) {
86
- return {
87
- kind: StructureKind.ImportDeclaration,
88
- moduleSpecifier: relativeModule("../requests/sdk.gen", ctx),
89
- namedImports: ctx.serviceNames.map((name) => ({ name })),
90
- };
91
- }
92
- /**
93
- * Build import structure for models.
94
- * Emitted as a type-only import so generated code compiles under
95
- * `verbatimModuleSyntax` (enabled by default in recent Vite templates).
96
- */
97
- export function buildModelImport(ctx) {
98
- if (ctx.modelNames.length === 0) {
99
- return null;
100
- }
101
- return {
102
- kind: StructureKind.ImportDeclaration,
103
- moduleSpecifier: relativeModule("../requests/types.gen", ctx),
104
- isTypeOnly: true,
105
- namedImports: ctx.modelNames.map((name) => ({ name })),
106
- };
107
- }
108
- /**
109
- * Build import structure for axios error type.
110
- */
111
- export function buildAxiosErrorImport() {
112
- return {
113
- kind: StructureKind.ImportDeclaration,
114
- moduleSpecifier: "axios",
115
- namedImports: [{ name: "AxiosError" }],
116
- };
117
- }
118
- /**
119
- * Build import for Common namespace.
120
- */
121
- export function buildCommonImport(ctx) {
122
- return {
123
- kind: StructureKind.ImportDeclaration,
124
- moduleSpecifier: relativeModule("./common", ctx),
125
- namespaceImport: "Common",
126
- };
127
- }
128
- /**
129
- * Build all imports needed for the common file.
130
- */
131
- export function buildCommonFileImports(ctx) {
132
- const imports = [
133
- buildClientImport(ctx),
134
- buildQueryImport(),
135
- buildServiceImport(ctx),
136
- ];
137
- const modelImport = buildModelImport(ctx);
138
- if (modelImport) {
139
- imports.push(modelImport);
140
- }
141
- if (ctx.client === "axios") {
142
- imports.push(buildAxiosErrorImport());
143
- }
144
- return imports;
145
- }
146
- /**
147
- * Build all imports needed for hook files (queries, suspense, infinite).
148
- */
149
- export function buildHookFileImports(ctx) {
150
- return [buildCommonImport(ctx), ...buildCommonFileImports(ctx)];
151
- }
152
- /**
153
- * Build all imports needed for the queryOptions file.
154
- * Narrower than the hook file imports: queryOptions only needs the
155
- * queryOptions/infiniteQueryOptions helpers, not the TanStack hooks.
156
- */
157
- export function buildQueryOptionsFileImports(ctx) {
158
- const imports = [
159
- buildCommonImport(ctx),
160
- buildQueryOptionsImport(),
161
- buildClientImport(ctx),
162
- buildServiceImport(ctx),
163
- ];
164
- const modelImport = buildModelImport(ctx);
165
- if (modelImport) {
166
- imports.push(modelImport);
167
- }
168
- return imports;
169
- }