Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[IDP-1766] Improve configuration #10

Merged
merged 11 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .changeset/old-impalas-tie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
"@workleap/create-schemas": minor
---

[BREAKING] Major overhaul to configurations.

The following command line arguments are no longer supported:

- `--additionalProperties`
- `--alphabetize`
- `--arrayLength`
- `--defaultNonNullable`
- `--propertiesRequiredByDefault`
- `--emptyObjectsUnknown`
- `--enum`
- `--enumValues`
- `--excludeDeprecated`
- `--exportType`
- `--help`
- `--immutable`
- `--pathParamsAsTypes`

These options now need to be declared in the `create-schemas.config.ts` file using the `openApiTsOptions` property.
11 changes: 9 additions & 2 deletions packages/create-schemas/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@
},
"type": "module",
"bin": "./dist/bin.js",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"scripts": {
"dev": "tsup --config tsup.dev.ts",
"test": "vitest",
Expand All @@ -35,9 +41,10 @@
"node": ">=18.0.0"
},
"dependencies": {
"@types/yargs-parser": "21.0.3",
"c12": "1.11.1",
"commander": "12.1.0",
"openapi-typescript": "7.0.0-rc.0",
"typescript": "5.4.5",
"yargs-parser": "21.1.1"
"zod": "3.23.8"
tjosepo marked this conversation as resolved.
Show resolved Hide resolved
}
}
52 changes: 0 additions & 52 deletions packages/create-schemas/src/argsHelper.ts

This file was deleted.

53 changes: 28 additions & 25 deletions packages/create-schemas/src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
import fs from "node:fs";
import path from "path";
import { getOpenApiTsOptionForArgs, getOutputPath } from "./argsHelper.ts";
import { ZodError } from "zod";
import { parseArgs, resolveConfig } from "./config.ts";
import { generateSchemas } from "./openapiTypescriptHelper.ts";

console.log("Received command: ", process.argv);

// Access command-line arguments
const args = process.argv.slice(2);

const openApiTsOptions = getOpenApiTsOptionForArgs(args);

const openApiPath = args[0];
const outputPath = getOutputPath(args);

if (!openApiPath || !outputPath) {
throw new Error("Both openApiPath and outputPath must be provided");
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";

try {
// Access command-line arguments
const config = await resolveConfig(parseArgs());

const contents = await generateSchemas(config);

// Write the content to a file
mkdirSync(dirname(fileURLToPath(config.output)), { recursive: true });
writeFileSync(fileURLToPath(config.output), contents);
} catch (error) {
if (error instanceof ZodError) {
printConfigurationErrors(error);
} else {
throw error;
}
}

console.log("Starting OpenAPI TypeScript types generation...");
console.log(`\t-openApiPath: ${openApiPath}`);
console.log(`\t-outputPath: ${outputPath}`);

const contents = await generateSchemas(openApiPath, outputPath, openApiTsOptions);

// Write the content to a file
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, contents);
function printConfigurationErrors(error: ZodError) {
console.log("Invalid configuration:");
error.errors.forEach(issue => {
console.log(` - ${issue.path.join(".")}: ${issue.message}`);
});
console.log("Use --help to see available options.");
}
89 changes: 89 additions & 0 deletions packages/create-schemas/src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { Command } from "commander";
import { loadConfig } from "c12";
import * as z from "zod";
import packageJson from "../package.json" with { type: "json" };
import type { OpenAPITSOptions as OriginalOpenAPITSOptions } from "openapi-typescript";
import { toFullyQualifiedURL } from "./utils.ts";

const CONFIG_FILE_DEFAULT = "create-schemas.config";
const OUTPUT_FILE_DEFAULT = "openapi-types.ts";
const ROOT_DEFAULT = process.cwd();

type OpenApiTsOptions = Omit<OriginalOpenAPITSOptions, "transform" | "postTransform" | "silent" | "version">;

export interface UserConfig {
root?: string;
input?: string;
output?: string;
openApiTsOptions?: OpenApiTsOptions;
}

export interface InlineConfig extends UserConfig {
configFile?: string;
}

const resolvedConfigSchema = z.object({
configFile: z.string(),
root: z.string(),
input: z.string(),
output: z.string(),
watch: z.boolean().optional().default(false),
openApiTsOptions: z.custom<OpenApiTsOptions>().optional().default({})
});

export type ResolvedConfig = z.infer<typeof resolvedConfigSchema>;

export function parseArgs(argv?: string[]): InlineConfig {
const program = new Command();

program
.name("create-schemas")
.version(packageJson.version, "-v, --version", "display version number")
.argument("[input]")
.option("-c, --config <file>", "use specified config file")
.option("-i, --input <path>", "path to the OpenAPI schema file")
.option("-o, --output <path>", "output file path")
.option("--watch", "watch for changes")
.option("--cwd <path>", "path to working directory")
.helpOption("-h, --help", "display available CLI options")
.parse(argv);

const opts = program.opts();
const args = program.args;

return {
configFile: opts.config,
root: opts.cwd,
input: opts.input || args[0],
output: opts.output
};
}

export async function resolveConfig(inlineConfig: InlineConfig = {}): Promise<ResolvedConfig> {
const { configFile = CONFIG_FILE_DEFAULT, root = ROOT_DEFAULT } = inlineConfig;

const { config } = await loadConfig<InlineConfig>({
configFile,
cwd: root,
rcFile: false,
omit$Keys: true,
defaultConfig: {
configFile: CONFIG_FILE_DEFAULT,
root: ROOT_DEFAULT,
output: OUTPUT_FILE_DEFAULT
},
overrides: inlineConfig
});

const resolvedConfig = resolvedConfigSchema.parse(config);

resolvedConfig.root = toFullyQualifiedURL(root);
resolvedConfig.input = toFullyQualifiedURL(resolvedConfig.input, resolvedConfig.root);
resolvedConfig.output = toFullyQualifiedURL(resolvedConfig.output, resolvedConfig.root);

return resolvedConfig;
}

export function defineConfig(config: UserConfig): UserConfig {
return config;
}
7 changes: 7 additions & 0 deletions packages/create-schemas/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export {
defineConfig,
resolveConfig,
type UserConfig,
type InlineConfig,
type ResolvedConfig
} from "./config.ts";
28 changes: 19 additions & 9 deletions packages/create-schemas/src/openapiTypescriptHelper.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import openapiTS, { astToString, type OpenAPITSOptions } from "openapi-typescript";
import { generateExportEndpointsTypeDeclaration, generateExportSchemaTypeDeclaration, getSchemaNames } from "./astHelper.ts";

export async function generateSchemas(openApiPath: string, outputPath: string, openApiTsOptions: OpenAPITSOptions): Promise<string> {
const CWD = new URL(`file://${process.cwd()}/`);

import openapiTS, { astToString } from "openapi-typescript";
import {
generateExportEndpointsTypeDeclaration,
generateExportSchemaTypeDeclaration,
getSchemaNames
} from "./astHelper.ts";
import type { ResolvedConfig } from "./config.ts";

export async function generateSchemas(config: ResolvedConfig): Promise<string> {
// Create a TypeScript AST from the OpenAPI schema
const ast = await openapiTS(new URL(openApiPath, CWD), openApiTsOptions);
const ast = await openapiTS(new URL(config.input), {
...config.openApiTsOptions,
silent: true
});

// Find the node where all the DTOs are defined, and extract their names
const schemaNames = getSchemaNames(ast);
Expand All @@ -24,9 +30,13 @@ export async function generateSchemas(openApiPath: string, outputPath: string, o
contents += `\n${generateExportEndpointsTypeDeclaration()}\n`;

if (schemaNames.length === 0) {
console.warn(`⚠️ Suspiciously no schemas where found in the OpenAPI document at ${openApiPath}. It might due to a flag converting interface to type which is not supported at the moment. ⚠️`);
console.warn(
`⚠️ Suspiciously no schemas where found in the OpenAPI document at ${config.input}. It might due to a flag converting interface to type which is not supported at the moment. ⚠️`
);
} else {
console.log(`OpenAPI TypeScript types have been generated successfully at ${outputPath}! 🎉`);
console.log(
`OpenAPI TypeScript types have been generated successfully at ${config.output}! 🎉`
);
}

return contents;
Expand Down
69 changes: 69 additions & 0 deletions packages/create-schemas/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { isAbsolute, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

function isFileURLAsText(input: string | URL): input is `file://${string}` {
tjosepo marked this conversation as resolved.
Show resolved Hide resolved
return typeof input === "string" && input.startsWith("file://");
}

function isHttpURLAsText(
tjosepo marked this conversation as resolved.
Show resolved Hide resolved
input: string
): input is `http://${string}` | `https://${string}` {
if (!URL.canParse(input)) {
return false;
}

const url = new URL(input);

return url.protocol === "http:" || url.protocol === "https:";
}

/**
* Converts a path into a fully qualified path URL.
*
* - `foo` -> `file:///path/to/cwd/foo`
* - `https://example.com/foo` -> `https://example.com/foo`
*
* This format is works for both file path and HTTP URLs, but the result needs
* to be converted to a `URL` instance or into a file path depending on the
* usage.
*/
export function toFullyQualifiedURL(
tjosepo marked this conversation as resolved.
Show resolved Hide resolved
input: string | URL,
root: string | URL = process.cwd()
): string {
if (input instanceof URL) {
return input.toString();
}

if (isHttpURLAsText(input)) {
return input;
}

if (isFileURLAsText(input)) {
return input;
}

if (isAbsolute(input)) {
return pathToFileURL(input).toString();
}

if (root instanceof URL || isHttpURLAsText(root)) {
const rootAsURL = new URL(root);

const pathname = join(rootAsURL.pathname, input);

return new URL(pathname, root).toString();
}

if (isFileURLAsText(root)) {
const rootAsPath = fileURLToPath(root);

return pathToFileURL(join(rootAsPath, input)).toString();
}

if (isAbsolute(root)) {
return pathToFileURL(join(root, input)).toString();
}

return pathToFileURL(join(process.cwd(), root, input)).toString();
}
Loading