Skip to content
This repository was archived by the owner on Jul 15, 2026. It is now read-only.
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
29 changes: 23 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
},
"homepage": "https://github.com/MapColonies/openapi-helpers#readme",
"dependencies": {
"@apidevtools/json-schema-ref-parser": "^14.1.1",
"change-case": "^5.4.4",
"oas-normalize": "^14.1.2",
"ts-essentials": "^10.1.1",
"yaml": "^2.8.0"
Expand Down
129 changes: 129 additions & 0 deletions src/generator/generateErrors.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import fs from 'node:fs/promises';
import { parseArgs } from 'node:util';
import path from 'node:path';
import { dereference } from '@apidevtools/json-schema-ref-parser';
import { format, resolveConfig } from 'prettier';
import * as changeCase from 'change-case';
import type { OpenAPI3, OperationObject, ResponseObject, SchemaObject } from 'openapi-typescript';

const ARGS_SLICE = 2;

const {
values: { format: shouldFormat },
positionals,
} = parseArgs({
args: process.argv.slice(ARGS_SLICE),
options: {
format: { type: 'boolean', alias: 'f' },
},
allowPositionals: true,
});

const [openapiPath, destinationPath] = positionals;

if (openapiPath === undefined || destinationPath === undefined) {
console.error('Usage: generateErrors <openapiPath> <destinationPath>');
process.exit(1);
}

const openapi = await dereference<OpenAPI3>(openapiPath);

if (openapi.paths === undefined) {
console.error('No paths found in the OpenAPI document.');
process.exit(1);
}

const errorCodes = new Set<string>();

function extractCodeFromSchema(schema: SchemaObject): void {
// Handle direct code property
if (schema.type === 'object' && schema.properties?.code) {
const codeProperty = schema.properties.code as SchemaObject;

// Handle enum values
if (codeProperty.enum) {
codeProperty.enum.map(String).forEach((code) => {
Comment on lines +41 to +45

Copilot AI Aug 4, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type assertion without validation could cause runtime errors. Consider checking if schema.properties.code is actually a SchemaObject before casting.

Suggested change
const codeProperty = schema.properties.code as SchemaObject;
// Handle enum values
if (codeProperty.enum) {
codeProperty.enum.map(String).forEach((code) => {
const codeProperty = schema.properties.code;
// Validate that codeProperty is a SchemaObject-like object with enum
if (
typeof codeProperty === 'object' &&
codeProperty !== null &&
Array.isArray((codeProperty as SchemaObject).enum)
) {
// Handle enum values
(codeProperty as SchemaObject).enum.map(String).forEach((code) => {

Copilot uses AI. Check for mistakes.
errorCodes.add(code);
});
}
}

// Handle allOf combinations
if (schema.allOf) {
for (const subSchema of schema.allOf) {
extractCodeFromSchema(subSchema as SchemaObject);
}
}

// Handle oneOf combinations
if (schema.oneOf) {
for (const subSchema of schema.oneOf) {
extractCodeFromSchema(subSchema as SchemaObject);
}
}

// Handle anyOf combinations
if (schema.anyOf) {
for (const subSchema of schema.anyOf) {
extractCodeFromSchema(subSchema as SchemaObject);
}
}
}

function createError(code: string): string {
let className = changeCase.pascalCase(code);

if (!className.endsWith('Error')) {
className += 'Error';
}

return `export class ${className} extends Error {
public readonly code = '${code}';
/**
* Creates an instance of ${className}.
* @param message - The error message.
* @param cause - Optional original error or server response data.
*/
public constructor(message: string, cause?: unknown) {
super(message, { cause });
Object.setPrototypeOf(this, new.target.prototype);
}
};\n`;
}

for (const [, methods] of Object.entries(openapi.paths)) {
for (const [key, operation] of Object.entries(methods) as [string, OperationObject][]) {
if (['servers', 'parameters'].includes(key)) {
continue;
}

for (const [statusCode, response] of Object.entries(operation.responses ?? {}) as [string, ResponseObject][]) {
if (statusCode.startsWith('2') || statusCode.startsWith('3')) {
continue; // Skip successful and redirection responses
}

const schema = response.content?.['application/json']?.schema as SchemaObject | undefined;
if (schema) {
extractCodeFromSchema(schema);
}
}
}
}

if (errorCodes.size === 0) {
console.warn('No error codes found in the OpenAPI document.');
process.exit(0);
}

let errorFile = errorCodes.values().map(createError).toArray().join('\n');

Copilot AI Aug 4, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method toArray() does not exist on Set iterators. Use Array.from(errorCodes) instead of errorCodes.values().map(createError).toArray().

Suggested change
let errorFile = errorCodes.values().map(createError).toArray().join('\n');
let errorFile = Array.from(errorCodes).map(createError).join('\n');

Copilot uses AI. Check for mistakes.

if (shouldFormat === true) {
const prettierOptions = await resolveConfig('./src/index.ts');

Copilot AI Aug 4, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The hardcoded path './src/index.ts' for Prettier config resolution is inflexible. Consider using the current working directory or making this configurable.

Suggested change
const prettierOptions = await resolveConfig('./src/index.ts');
const prettierOptions = await resolveConfig(destinationPath);

Copilot uses AI. Check for mistakes.

errorFile = await format(errorFile, { ...prettierOptions, parser: 'typescript' });
}

const directory = path.dirname(destinationPath);
await fs.mkdir(directory, { recursive: true });

await fs.writeFile(destinationPath, errorFile);
3 changes: 3 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"extends": "@map-colonies/tsconfig/tsconfig-library",
"compilerOptions": {
"lib": ["ESNext"]
},
"include": ["src", "tests"],
"exclude": ["dist", "node_modules"]
}
Loading