@7nohe/openapi-react-query-codegen 3.1.0 → 4.0.0-beta.2

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 (55) hide show
  1. package/AGENTS.md +207 -0
  2. package/README.md +7 -3
  3. package/dist/check.d.mts +59 -0
  4. package/dist/check.mjs +162 -0
  5. package/dist/cli.d.mts +6 -1
  6. package/dist/cli.mjs +4 -31
  7. package/dist/client/emitSchemas.d.mts +9 -0
  8. package/dist/client/emitSchemas.mjs +130 -0
  9. package/dist/client/emitSdk.d.mts +18 -0
  10. package/dist/client/emitSdk.mjs +253 -0
  11. package/dist/client/emitTransformers.d.mts +19 -0
  12. package/dist/client/emitTransformers.mjs +556 -0
  13. package/dist/client/emitTypes.d.mts +16 -0
  14. package/dist/client/emitTypes.mjs +204 -0
  15. package/dist/client/index.d.mts +44 -0
  16. package/dist/client/index.mjs +126 -0
  17. package/dist/client/naming.d.mts +41 -0
  18. package/dist/client/naming.mjs +175 -0
  19. package/dist/client/operations.d.mts +103 -0
  20. package/dist/client/operations.mjs +352 -0
  21. package/dist/client/runtime/axios.runtime.ts +706 -0
  22. package/dist/client/runtime/fetch.runtime.ts +795 -0
  23. package/dist/client/schema.d.mts +50 -0
  24. package/dist/client/schema.mjs +648 -0
  25. package/dist/client/spec.d.mts +40 -0
  26. package/dist/client/spec.mjs +387 -0
  27. package/dist/client/tsconfig.d.mts +13 -0
  28. package/dist/client/tsconfig.mjs +56 -0
  29. package/dist/common.d.mts +0 -38
  30. package/dist/common.mjs +0 -87
  31. package/dist/constants.d.mts +0 -2
  32. package/dist/constants.mjs +0 -2
  33. package/dist/createSource.d.mts +8 -7
  34. package/dist/createSource.mjs +14 -17
  35. package/dist/errors.d.mts +43 -0
  36. package/dist/errors.mjs +61 -0
  37. package/dist/format.mjs +0 -1
  38. package/dist/generate.d.mts +25 -3
  39. package/dist/generate.mjs +83 -83
  40. package/dist/runCli.d.mts +20 -0
  41. package/dist/runCli.mjs +105 -0
  42. package/dist/tsmorph/buildQueryHooks.mjs +19 -11
  43. package/dist/tsmorph/generateFiles.mjs +105 -161
  44. package/dist/tsmorph/operationNames.d.mts +2 -13
  45. package/dist/tsmorph/operationNames.mjs +4 -24
  46. package/dist/tsmorph/projectFactory.d.mts +7 -2
  47. package/dist/tsmorph/projectFactory.mjs +16 -9
  48. package/dist/types.d.mts +14 -26
  49. package/package.json +8 -8
  50. package/dist/parseOperations.d.mts +0 -10
  51. package/dist/parseOperations.mjs +0 -164
  52. package/dist/service.d.mts +0 -8
  53. package/dist/service.mjs +0 -98
  54. package/dist/util.d.mts +0 -2
  55. package/dist/util.mjs +0 -16
@@ -1,15 +1,16 @@
1
+ import type { ClientKind, GeneratedClient } from "./client/index.mjs";
1
2
  import type { GeneratedFile } from "./types.mjs";
2
- type ClientType = "@hey-api/client-fetch" | "@hey-api/client-axios";
3
3
  /**
4
- * Create source files using ts-morph based generation.
4
+ * Create the React Query source files for a generated client.
5
5
  */
6
- export declare const createSource: ({ outputPath, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, }: {
7
- outputPath: string;
8
- client: ClientType;
6
+ export declare const createSource: ({ generated, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, importExtension, }: {
7
+ generated: Pick<GeneratedClient, "operations" | "modelNames" | "serviceNames">;
8
+ client: ClientKind;
9
9
  version: string;
10
10
  pageParam: string;
11
11
  nextPageParam: string;
12
12
  initialPageParam: string;
13
13
  omitInitialPageParam: boolean;
14
- }) => Promise<GeneratedFile[]>;
15
- export {};
14
+ /** Extension of the relative imports; see `detectImportExtension`. */
15
+ importExtension?: "" | ".js";
16
+ }) => GeneratedFile[];
@@ -1,21 +1,18 @@
1
- import { join } from "node:path";
2
- import { Project } from "ts-morph";
3
- import { buildGenerationContext, parseOperations } from "./parseOperations.mjs";
4
1
  import { generateAllFiles } from "./tsmorph/index.mjs";
5
2
  /**
6
- * Create source files using ts-morph based generation.
3
+ * Create the React Query source files for a generated client.
7
4
  */
8
- export const createSource = async ({ outputPath, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, }) => {
9
- // Initialize ts-morph project to read the generated OpenAPI client
10
- const project = new Project({
11
- skipAddingFilesFromTsConfig: true,
12
- });
13
- const sourceFiles = join(process.cwd(), outputPath);
14
- project.addSourceFilesAtPaths(`${sourceFiles}/**/*`);
15
- // Parse operations from the service file
16
- const operations = await parseOperations(project, pageParam);
17
- // Build generation context
18
- const ctx = buildGenerationContext(project, client, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, version);
19
- // Generate all files using ts-morph
20
- return generateAllFiles(operations, ctx);
5
+ export const createSource = ({ generated, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, importExtension = "", }) => {
6
+ const ctx = {
7
+ client,
8
+ modelNames: generated.modelNames,
9
+ serviceNames: generated.serviceNames,
10
+ pageParam,
11
+ nextPageParam,
12
+ initialPageParam,
13
+ omitInitialPageParam,
14
+ version,
15
+ importExtension,
16
+ };
17
+ return generateAllFiles(generated.operations, ctx);
21
18
  };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Stable, machine-readable error codes printed by `--json`.
3
+ * Changing or removing a code is a breaking change.
4
+ */
5
+ export declare const ErrorCodes: {
6
+ readonly invalidArgument: "INVALID_ARGUMENT";
7
+ readonly inputNotFound: "INPUT_NOT_FOUND";
8
+ readonly inputParseError: "INPUT_PARSE_ERROR";
9
+ readonly clientGenerationFailed: "CLIENT_GENERATION_FAILED";
10
+ readonly generationFailed: "GENERATION_FAILED";
11
+ readonly outputOutOfDate: "OUTPUT_OUT_OF_DATE";
12
+ };
13
+ export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
14
+ export declare const ExitCodes: {
15
+ readonly success: 0;
16
+ readonly outOfDate: 1;
17
+ readonly error: 2;
18
+ };
19
+ export type ErrorDetails = Record<string, unknown>;
20
+ export declare class CodegenError extends Error {
21
+ readonly code: ErrorCode;
22
+ readonly details: ErrorDetails;
23
+ constructor(code: ErrorCode, message: string, details?: ErrorDetails, options?: {
24
+ cause?: unknown;
25
+ });
26
+ }
27
+ /**
28
+ * Anything that is not already a {@link CodegenError} is an unexpected
29
+ * failure in our own pipeline.
30
+ */
31
+ export declare function toCodegenError(error: unknown): CodegenError;
32
+ export type JsonError = {
33
+ code: ErrorCode;
34
+ message: string;
35
+ details: ErrorDetails;
36
+ };
37
+ export declare function toJsonError(error: CodegenError): JsonError;
38
+ export declare function formatErrorJson(error: CodegenError): string;
39
+ /**
40
+ * Human-readable rendering for the default (non-JSON) mode.
41
+ * Unexpected failures keep their stack trace so they stay debuggable.
42
+ */
43
+ export declare function formatErrorText(error: CodegenError): string;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Stable, machine-readable error codes printed by `--json`.
3
+ * Changing or removing a code is a breaking change.
4
+ */
5
+ export const ErrorCodes = {
6
+ invalidArgument: "INVALID_ARGUMENT",
7
+ inputNotFound: "INPUT_NOT_FOUND",
8
+ inputParseError: "INPUT_PARSE_ERROR",
9
+ clientGenerationFailed: "CLIENT_GENERATION_FAILED",
10
+ generationFailed: "GENERATION_FAILED",
11
+ outputOutOfDate: "OUTPUT_OUT_OF_DATE",
12
+ };
13
+ export const ExitCodes = {
14
+ success: 0,
15
+ outOfDate: 1,
16
+ error: 2,
17
+ };
18
+ export class CodegenError extends Error {
19
+ code;
20
+ details;
21
+ constructor(code, message, details = {}, options) {
22
+ super(message, options);
23
+ this.name = "CodegenError";
24
+ this.code = code;
25
+ this.details = details;
26
+ }
27
+ }
28
+ /**
29
+ * Anything that is not already a {@link CodegenError} is an unexpected
30
+ * failure in our own pipeline.
31
+ */
32
+ export function toCodegenError(error) {
33
+ if (error instanceof CodegenError) {
34
+ return error;
35
+ }
36
+ if (error instanceof Error) {
37
+ return new CodegenError(ErrorCodes.generationFailed, error.message, { name: error.name }, { cause: error });
38
+ }
39
+ return new CodegenError(ErrorCodes.generationFailed, String(error));
40
+ }
41
+ export function toJsonError(error) {
42
+ return {
43
+ code: error.code,
44
+ message: error.message,
45
+ details: error.details,
46
+ };
47
+ }
48
+ export function formatErrorJson(error) {
49
+ return JSON.stringify(toJsonError(error));
50
+ }
51
+ /**
52
+ * Human-readable rendering for the default (non-JSON) mode.
53
+ * Unexpected failures keep their stack trace so they stay debuggable.
54
+ */
55
+ export function formatErrorText(error) {
56
+ const cause = error.cause;
57
+ if (error.code === ErrorCodes.generationFailed && cause instanceof Error) {
58
+ return `error [${error.code}]: ${cause.stack ?? cause.message}`;
59
+ }
60
+ return `error [${error.code}]: ${error.message}`;
61
+ }
package/dist/format.mjs CHANGED
@@ -14,7 +14,6 @@ export const formatOutput = async (outputPath) => {
14
14
  const sourceFiles = project.addSourceFilesAtPaths(`${outputPath}/**/*`);
15
15
  const tasks = sourceFiles.map((sourceFile) => {
16
16
  sourceFile.formatText();
17
- sourceFile.fixMissingImports();
18
17
  sourceFile.organizeImports();
19
18
  return sourceFile.save();
20
19
  });
@@ -1,3 +1,25 @@
1
- import type { LimitedUserConfig } from "./cli.mjs";
2
- export declare function findNearestTsConfigPath(startDir: string): string | undefined;
3
- export declare function generate(options: LimitedUserConfig, version: string): Promise<void>;
1
+ import type { ClientChoice, LimitedUserConfig } from "./cli.mjs";
2
+ import { type ClientKind, findNearestTsConfigPath } from "./client/index.mjs";
3
+ import { CodegenError } from "./errors.mjs";
4
+ export { findNearestTsConfigPath };
5
+ /** Map a `--client` value (including the v3 `@hey-api/*` aliases) to a kind. */
6
+ export declare function resolveClientKind(client: ClientChoice | undefined): ClientKind;
7
+ export type GenerateRuntimeOptions = {
8
+ /**
9
+ * Keep the generator's warnings off stderr. Used by `--json` (stderr must
10
+ * carry only our JSON) and by `--check`.
11
+ */
12
+ silent?: boolean;
13
+ };
14
+ /**
15
+ * Translate a failure of the client generator into our stable error codes.
16
+ * This is the only place that knows how `src/client/` reports them.
17
+ */
18
+ export declare function mapClientError(error: unknown, input: unknown): CodegenError;
19
+ /**
20
+ * Generate the client and the React Query hooks into `options.output`.
21
+ * Rejects only with {@link CodegenError}, so callers can branch on `code`.
22
+ */
23
+ export declare function generate(options: LimitedUserConfig, version: string, runtime?: GenerateRuntimeOptions): Promise<void>;
24
+ export { type CheckResult, check, type FileChange, type FileChangeStatus, } from "./check.mjs";
25
+ export { CodegenError, type ErrorCode, ErrorCodes, ExitCodes, } from "./errors.mjs";
package/dist/generate.mjs CHANGED
@@ -1,103 +1,86 @@
1
- import { readdirSync } from "node:fs";
2
- import { readFile, writeFile } from "node:fs/promises";
3
- import path from "node:path";
4
- import { createClient } from "@hey-api/openapi-ts";
1
+ import { detectImportExtension, findNearestTsConfigPath, generateClient, SpecError, writeGeneratedFiles, } from "./client/index.mjs";
5
2
  import { buildQueriesOutputPath, buildRequestsOutputPath, formatOptions, } from "./common.mjs";
6
3
  import { createSource } from "./createSource.mjs";
4
+ import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs";
7
5
  import { formatOutput, processOutput } from "./format.mjs";
8
6
  import { print } from "./print.mjs";
9
- // openapi-ts's own tsconfig auto-detection walks up from its *install*
10
- // location, which in this monorepo reaches this repo's own root tsconfig
11
- // (NodeNext) instead of the caller's project config. Anchoring the search
12
- // at cwd instead finds the tsconfig that actually applies to the generated
13
- // output, matching the resolution the caller's own `tsc` will use.
14
- export function findNearestTsConfigPath(startDir) {
15
- let dir = startDir;
16
- while (true) {
17
- const candidates = readdirSync(dir).filter((file) => file.startsWith("tsconfig") && file.endsWith(".json"));
18
- if (candidates.length > 0) {
19
- candidates.sort((a) => (a === "tsconfig.json" ? -1 : 1));
20
- return path.join(dir, candidates[0]);
21
- }
22
- const parent = path.dirname(dir);
23
- if (parent === dir)
24
- return undefined;
25
- dir = parent;
7
+ export { findNearestTsConfigPath };
8
+ /** Map a `--client` value (including the v3 `@hey-api/*` aliases) to a kind. */
9
+ export function resolveClientKind(client) {
10
+ switch (client) {
11
+ case "axios":
12
+ case "@hey-api/client-axios":
13
+ return "axios";
14
+ default:
15
+ return "fetch";
26
16
  }
27
17
  }
28
- export async function generate(options, version) {
18
+ /** Keep inline spec content out of error details; it can be huge. */
19
+ function describeInput(input) {
20
+ if (typeof input === "string" && !input.includes("\n")) {
21
+ return input;
22
+ }
23
+ return "(inline specification)";
24
+ }
25
+ /**
26
+ * Translate a failure of the client generator into our stable error codes.
27
+ * This is the only place that knows how `src/client/` reports them.
28
+ */
29
+ export function mapClientError(error, input) {
30
+ if (error instanceof CodegenError) {
31
+ return error;
32
+ }
33
+ const inputDescription = describeInput(input);
34
+ const reason = error instanceof Error ? error.message : String(error);
35
+ if (error instanceof SpecError) {
36
+ return error.reason === "not-found"
37
+ ? new CodegenError(ErrorCodes.inputNotFound, `OpenAPI input could not be read: ${inputDescription}`, { input: inputDescription, reason }, { cause: error })
38
+ : new CodegenError(ErrorCodes.inputParseError, `OpenAPI input could not be parsed: ${inputDescription}`, { input: inputDescription, reason }, { cause: error });
39
+ }
40
+ return new CodegenError(ErrorCodes.clientGenerationFailed, `The client could not be generated: ${reason}`, {
41
+ input: inputDescription,
42
+ reason,
43
+ name: error instanceof Error ? error.name : "Error",
44
+ }, { cause: error });
45
+ }
46
+ async function runGenerate(options, version, runtime) {
29
47
  const openApiOutputPath = buildRequestsOutputPath(options.output);
30
48
  const formattedOptions = formatOptions(options);
31
- // Map CLI options to new plugins system
32
- const clientPlugin = formattedOptions.client === "@hey-api/client-axios"
33
- ? "@hey-api/client-axios"
34
- : "@hey-api/client-fetch";
35
- const typescriptPlugin = formattedOptions.enums
36
- ? {
37
- name: "@hey-api/typescript",
49
+ const client = resolveClientKind(formattedOptions.client);
50
+ // One answer for both directories: the queries import the requests.
51
+ const importExtension = detectImportExtension(process.cwd());
52
+ let generated;
53
+ try {
54
+ generated = await generateClient({
55
+ input: formattedOptions.input,
56
+ client,
38
57
  enums: formattedOptions.enums,
39
- }
40
- : "@hey-api/typescript";
41
- const sdkPlugin = {
42
- name: "@hey-api/sdk",
43
- ...(formattedOptions.noOperationId
44
- ? {
45
- // `operationId: false` was deprecated in favor of `operations.nesting`
46
- operations: {
47
- nesting: "id",
48
- },
49
- }
50
- : {}),
51
- ...(formattedOptions.useDateType
52
- ? { transformer: "@hey-api/transformers" }
53
- : {}),
54
- };
55
- const plugins = [
56
- clientPlugin,
57
- typescriptPlugin,
58
- sdkPlugin,
59
- ];
60
- if (formattedOptions.useDateType) {
61
- plugins.push({
62
- name: "@hey-api/transformers",
63
- dates: "date",
58
+ importExtension,
59
+ noOperationId: formattedOptions.noOperationId,
60
+ pageParam: formattedOptions.pageParam,
61
+ schemas: formattedOptions.noSchemas
62
+ ? false
63
+ : (formattedOptions.schemaType ?? "json"),
64
+ useDateType: formattedOptions.useDateType,
64
65
  });
65
66
  }
66
- // Conditionally add schemas plugin
67
- if (!formattedOptions.noSchemas) {
68
- plugins.push(formattedOptions.schemaType
69
- ? {
70
- name: "@hey-api/schemas",
71
- type: formattedOptions.schemaType,
72
- }
73
- : "@hey-api/schemas");
67
+ catch (error) {
68
+ throw mapClientError(error, formattedOptions.input);
74
69
  }
75
- const config = {
76
- dryRun: false,
77
- input: formattedOptions.input,
78
- output: {
79
- path: openApiOutputPath,
80
- tsConfigPath: findNearestTsConfigPath(process.cwd()) ?? null,
81
- },
82
- plugins,
83
- };
84
- await createClient(config);
85
- // Generate backward-compatible services.gen.ts shim
86
- // client.gen.ts has the `client` instance; sdk.gen.ts has SDK functions.
87
- // Mirror whatever extension convention openapi-ts used for its own
88
- // cross-file imports (e.g. `.js` for NodeNext, none for bundler resolution).
89
- const sdkGenContent = await readFile(path.join(openApiOutputPath, "sdk.gen.ts"), "utf-8");
90
- const importExtension = sdkGenContent.match(/from ['"]\.\/client\.gen(\.\S*)?['"]/)?.[1] ?? "";
91
- const shimContent = `// This file is auto-generated for backward compatibility\nexport * from './client.gen${importExtension}';\nexport * from './sdk.gen${importExtension}';\n`;
92
- await writeFile(path.join(openApiOutputPath, "services.gen.ts"), shimContent);
93
- const source = await createSource({
94
- outputPath: openApiOutputPath,
95
- client: clientPlugin,
70
+ if (!runtime.silent) {
71
+ for (const warning of generated.warnings)
72
+ console.warn(warning);
73
+ }
74
+ await writeGeneratedFiles(openApiOutputPath, generated.files);
75
+ const source = createSource({
76
+ generated,
77
+ client,
96
78
  version,
97
79
  pageParam: formattedOptions.pageParam,
98
80
  nextPageParam: formattedOptions.nextPageParam,
99
81
  initialPageParam: formattedOptions.initialPageParam.toString(),
100
82
  omitInitialPageParam: formattedOptions.omitInitialPageParam ?? false,
83
+ importExtension,
101
84
  });
102
85
  await print(source, formattedOptions);
103
86
  const queriesOutputPath = buildQueriesOutputPath(options.output);
@@ -108,3 +91,20 @@ export async function generate(options, version) {
108
91
  lint: formattedOptions.lint,
109
92
  });
110
93
  }
94
+ /**
95
+ * Generate the client and the React Query hooks into `options.output`.
96
+ * Rejects only with {@link CodegenError}, so callers can branch on `code`.
97
+ */
98
+ export async function generate(options, version, runtime = {}) {
99
+ try {
100
+ await runGenerate(options, version, runtime);
101
+ }
102
+ catch (error) {
103
+ throw toCodegenError(error);
104
+ }
105
+ }
106
+ // Public library surface for the agent-facing features. `check` imports
107
+ // `generate` from this module; the cycle is safe because both are hoisted
108
+ // function declarations.
109
+ export { check, } from "./check.mjs";
110
+ export { CodegenError, ErrorCodes, ExitCodes, } from "./errors.mjs";
@@ -0,0 +1,20 @@
1
+ import { Command } from "commander";
2
+ import { type CheckResult } from "./check.mjs";
3
+ import type { LimitedUserConfig } from "./cli.mjs";
4
+ import { type GenerateRuntimeOptions } from "./generate.mjs";
5
+ export type CliIO = {
6
+ stdout: (text: string) => void;
7
+ stderr: (text: string) => void;
8
+ };
9
+ export type CliDependencies = {
10
+ generate: (options: LimitedUserConfig, version: string, runtime?: GenerateRuntimeOptions) => Promise<void>;
11
+ check: (options: LimitedUserConfig, version: string) => Promise<CheckResult>;
12
+ };
13
+ export declare function buildProgram(version: string, io: CliIO, { json }: {
14
+ json: boolean;
15
+ }): Command;
16
+ /**
17
+ * Run the CLI and resolve with the process exit code:
18
+ * 0 = success / up to date, 1 = `--check` found drift, 2 = error.
19
+ */
20
+ export declare function runCli(argv: readonly string[], version: string, io?: CliIO, dependencies?: CliDependencies): Promise<number>;
@@ -0,0 +1,105 @@
1
+ import { Command, CommanderError, Option } from "commander";
2
+ import { check, outOfDateError } from "./check.mjs";
3
+ import { defaultOutputPath } from "./constants.mjs";
4
+ import { CodegenError, ErrorCodes, ExitCodes, formatErrorJson, formatErrorText, toCodegenError, } from "./errors.mjs";
5
+ import { generate } from "./generate.mjs";
6
+ const defaultIO = {
7
+ stdout: (text) => process.stdout.write(text),
8
+ stderr: (text) => process.stderr.write(text),
9
+ };
10
+ const defaultDependencies = { generate, check };
11
+ export function buildProgram(version, io, { json }) {
12
+ return new Command()
13
+ .name("openapi-rq")
14
+ .version(version)
15
+ .description("Generate React Query code based on OpenAPI")
16
+ .exitOverride()
17
+ .configureOutput({
18
+ writeOut: io.stdout,
19
+ writeErr: io.stderr,
20
+ // With --json the error is reported once, as JSON, by runCli.
21
+ outputError: (text, write) => {
22
+ if (!json)
23
+ write(text);
24
+ },
25
+ })
26
+ .requiredOption("-i, --input <value>", "OpenAPI specification, can be a path, url or string content (required)")
27
+ .option("-o, --output <value>", "Output directory", defaultOutputPath)
28
+ .addOption(new Option("-c, --client <value>", "HTTP client to generate")
29
+ .choices([
30
+ "fetch",
31
+ "axios",
32
+ "@hey-api/client-fetch",
33
+ "@hey-api/client-axios",
34
+ ])
35
+ .default("fetch"))
36
+ .addOption(new Option("--format <value>", "Process output folder with formatter?").choices(["biome", "prettier"]))
37
+ .addOption(new Option("--lint <value>", "Process output folder with linter?").choices(["biome", "eslint"]))
38
+ .option("--noOperationId", "Do not use operationId to generate operation names")
39
+ .addOption(new Option("--enums <value>", "Generate JavaScript objects from enum definitions?").choices(["javascript", "typescript"]))
40
+ .option("--useDateType", "Use Date for date/date-time model properties and convert response values to Date objects")
41
+ .option("--debug", "Run in debug mode?")
42
+ .option("--noSchemas", "Disable generating JSON schemas")
43
+ .addOption(new Option("--schemaType <value>", "Type of JSON schema [Default: 'json']").choices(["form", "json"]))
44
+ .option("--pageParam <value>", "Name of the query parameter used for pagination", "page")
45
+ .option("--nextPageParam <value>", "Name of the response parameter used for next page", "nextPage")
46
+ .option("--initialPageParam <value>", "Initial page value to query", "1")
47
+ .option("--omitInitialPageParam", "Send no initial page parameter at all (overrides --initialPageParam)")
48
+ .option("--check", "Do not update the output; exit 1 and list the files that differ if the existing output is out of date")
49
+ .option("--json", "Print errors to stderr as a single line of JSON ({ code, message, details })");
50
+ }
51
+ function reportError(error, io, json) {
52
+ if (json) {
53
+ io.stderr(`${formatErrorJson(error)}\n`);
54
+ return;
55
+ }
56
+ io.stderr(`${formatErrorText(error)}\n`);
57
+ if (error.code === ErrorCodes.outputOutOfDate) {
58
+ const files = error.details.files;
59
+ for (const file of files) {
60
+ io.stderr(` ${file.status.padEnd(8)} ${file.path}\n`);
61
+ }
62
+ }
63
+ }
64
+ /**
65
+ * Run the CLI and resolve with the process exit code:
66
+ * 0 = success / up to date, 1 = `--check` found drift, 2 = error.
67
+ */
68
+ export async function runCli(argv, version, io = defaultIO, dependencies = defaultDependencies) {
69
+ // Decided before parsing so that argument errors can be JSON too.
70
+ const json = argv.includes("--json");
71
+ const program = buildProgram(version, io, { json });
72
+ try {
73
+ program.parse([...argv]);
74
+ }
75
+ catch (error) {
76
+ if (!(error instanceof CommanderError))
77
+ throw error;
78
+ // --help and --version also exit through exitOverride.
79
+ if (error.exitCode === 0)
80
+ return ExitCodes.success;
81
+ const codegenError = new CodegenError(ErrorCodes.invalidArgument, error.message.replace(/^error: /, ""), { commanderCode: error.code });
82
+ // Commander already printed its own message in text mode.
83
+ if (json)
84
+ reportError(codegenError, io, json);
85
+ return ExitCodes.error;
86
+ }
87
+ const { check: checkMode, json: _json, ...options } = program.opts();
88
+ try {
89
+ if (checkMode) {
90
+ const result = await dependencies.check(options, version);
91
+ if (result.upToDate) {
92
+ io.stdout("✔ Generated output is up to date.\n");
93
+ return ExitCodes.success;
94
+ }
95
+ reportError(outOfDateError(result.files), io, json);
96
+ return ExitCodes.outOfDate;
97
+ }
98
+ await dependencies.generate(options, version, { silent: json });
99
+ return ExitCodes.success;
100
+ }
101
+ catch (error) {
102
+ reportError(toCodegenError(error), io, json);
103
+ return ExitCodes.error;
104
+ }
105
+ }
@@ -1,4 +1,5 @@
1
1
  import { StructureKind, VariableDeclarationKind, } from "ts-morph";
2
+ import { isValidIdentifier, propertyKey } from "../client/naming.mjs";
2
3
  import { getDataTypeName, getErrorType } from "./operationNames.mjs";
3
4
  /**
4
5
  * SDK call arguments shared by every generated queryFn/mutationFn.
@@ -17,13 +18,8 @@ export function getPageParamType(op) {
17
18
  * Build the client options parameter string.
18
19
  */
19
20
  export function buildClientOptionsParam(op) {
20
- const dataTypeName = getDataTypeName(op);
21
- const hasParams = op.parameters.length > 0;
22
- if (!hasParams) {
23
- return `clientOptions: Options<${dataTypeName}, true> = {}`;
24
- }
25
21
  const defaultValue = op.allParamsOptional ? " = {}" : "";
26
- return `clientOptions: Options<${dataTypeName}, true>${defaultValue}`;
22
+ return `clientOptions: Options<${getDataTypeName(op)}, true>${defaultValue}`;
27
23
  }
28
24
  /**
29
25
  * Build the clientOptions parameter typed with the page-less infinite
@@ -56,9 +52,10 @@ export function buildPagedQueryFn(op, ctx) {
56
52
  const pageParamType = getPageParamType(op);
57
53
  // When the initial page param is omitted, the first request must send no
58
54
  // page param at all, so spread it in only once TanStack Query provides one.
55
+ const pageKey = propertyKey(ctx.pageParam);
59
56
  const pageQuery = ctx.omitInitialPageParam
60
- ? `...(pageParam === undefined ? {} : { ${ctx.pageParam}: pageParam as ${pageParamType} })`
61
- : `${ctx.pageParam}: pageParam as ${pageParamType}`;
57
+ ? `...(pageParam === undefined ? {} : { ${pageKey}: pageParam as ${pageParamType} })`
58
+ : `${pageKey}: pageParam as ${pageParamType}`;
62
59
  return `({ pageParam, signal }) => ${op.methodName}({ ...clientOptions, query: { ...clientOptions.query, ${pageQuery} }, signal, throwOnError: true } as Options<${dataTypeName}, true>)${thenClause}`;
63
60
  }
64
61
  /**
@@ -78,7 +75,8 @@ export function formatInitialPageParam(ctx, op) {
78
75
  if (isStringPageParam) {
79
76
  return JSON.stringify(ctx.initialPageParam);
80
77
  }
81
- return /^-?\d+$/.test(ctx.initialPageParam)
78
+ // `001` would be an octal literal, which TypeScript rejects.
79
+ return /^-?(0|[1-9]\d*)$/.test(ctx.initialPageParam)
82
80
  ? ctx.initialPageParam
83
81
  : JSON.stringify(ctx.initialPageParam);
84
82
  }
@@ -89,7 +87,7 @@ export function formatInitialPageParam(ctx, op) {
89
87
  export function buildNestedNextPageType(nextPageParam, pageParamType = "number") {
90
88
  const segments = nextPageParam.split(".");
91
89
  return segments.reduceRight((acc, segment) => {
92
- return `{ ${segment}: ${acc} }`;
90
+ return `{ ${propertyKey(segment)}: ${acc} }`;
93
91
  }, pageParamType);
94
92
  }
95
93
  /**
@@ -99,7 +97,17 @@ export function buildNestedNextPageType(nextPageParam, pageParamType = "number")
99
97
  */
100
98
  export function buildGetNextPageParamExpr(ctx, op) {
101
99
  const nestedType = buildNestedNextPageType(ctx.nextPageParam, op ? getPageParamType(op) : "number");
102
- return `(response: unknown) => (response as ${nestedType}).${ctx.nextPageParam}`;
100
+ const access = ctx.nextPageParam
101
+ .split(".")
102
+ .map((segment, index) => {
103
+ // The last page can leave out what holds the next one, or set it to null.
104
+ const optional = index > 0 ? "?." : "";
105
+ return isValidIdentifier(segment)
106
+ ? `${optional || "."}${segment}`
107
+ : `${optional}[${JSON.stringify(segment)}]`;
108
+ })
109
+ .join("");
110
+ return `(response: unknown) => (response as ${nestedType})${access}`;
103
111
  }
104
112
  /**
105
113
  * Build an options type where the pagination fields TanStack Query marks as