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

feat: Allow configurable prefix for definitions path #1604

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
26 changes: 17 additions & 9 deletions src/type-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ToJsonFunction } from './tojson';


const PRIMITIVE_TYPES = ['string', 'number', 'integer', 'boolean'];
const DEFINITIONS_PREFIX = '#/definitions/';
const DEFAULT_DEFINITIONS_PREFIX = '#/definitions/';
const DEFAULT_RENDER_TYPE_NAME = (s: string) => s.split('.').map(x => pascalCase(x)).join('');

export interface TypeGeneratorOptions {
Expand Down Expand Up @@ -62,6 +62,13 @@ export interface TypeGeneratorOptions {
* @default - Only dot namespacing is handled by default. Elements between dots are pascal cased and concatenated.
*/
readonly renderTypeName?: (def: string) => string;

/**
* Allow overriding default definitions path prefix: newer JSON Schema versions support `#/$defs/`
*
* @default #/definitions/
*/
readonly definitionsPrefix?: string;
}

/**
Expand Down Expand Up @@ -121,6 +128,7 @@ export class TypeGenerator {
private readonly toJson: boolean;
private readonly sanitizeEnums: boolean;
private readonly renderTypeName: (def: string) => string;
private readonly definitionsPrefix: string;

/**
*
Expand All @@ -133,6 +141,7 @@ export class TypeGenerator {
this.toJson = options.toJson ?? true;
this.sanitizeEnums = options.sanitizeEnums ?? false;
this.renderTypeName = options.renderTypeName ?? DEFAULT_RENDER_TYPE_NAME;
this.definitionsPrefix = options.definitionsPrefix ?? DEFAULT_DEFINITIONS_PREFIX;

for (const [typeName, def] of Object.entries(options.definitions ?? {})) {
this.addDefinition(typeName, def);
Expand All @@ -157,7 +166,7 @@ export class TypeGenerator {
* emitted as a custom type (`emitCustomType()`).
*/
public addAlias(from: string, to: string) {
this.addDefinition(from, { $ref: `#/definitions/${to}` });
this.addDefinition(from, { $ref: `${this.definitionsPrefix}${to}` });
}

/**
Expand Down Expand Up @@ -251,8 +260,8 @@ export class TypeGenerator {
throw new Error(`${typeName} must be normalized before calling emitType`);
}

if (structFqn.startsWith(DEFINITIONS_PREFIX)) {
structFqn = structFqn.substring(DEFINITIONS_PREFIX.length);
if (structFqn.startsWith(this.definitionsPrefix)) {
structFqn = structFqn.substring(this.definitionsPrefix.length);
}

if (this.isExcluded(structFqn)) {
Expand Down Expand Up @@ -605,16 +614,15 @@ export class TypeGenerator {
}

private typeForRef(def: JSONSchema4): EmittedType {
const prefix = '#/definitions/';
if (!def.$ref || !def.$ref.startsWith(prefix)) {
if (!def.$ref || !def.$ref.startsWith(this.definitionsPrefix)) {
throw new Error(`invalid $ref ${JSON.stringify(def)}`);
}

if (this.isExcluded(def.$ref)) {
return { type: 'any', toJson: x => x };
}

const typeName = TypeGenerator.normalizeTypeName(this.renderTypeName(def.$ref.substring(prefix.length)));
const typeName = TypeGenerator.normalizeTypeName(this.renderTypeName(def.$ref.substring(this.definitionsPrefix.length)));

// if we already emitted a type with this type name, just return it
const emitted = this.emittedTypes[typeName];
Expand All @@ -637,11 +645,11 @@ export class TypeGenerator {

private resolveReference(def: JSONSchema4): JSONSchema4 {
const ref = def.$ref;
if (!ref || !ref.startsWith(DEFINITIONS_PREFIX)) {
if (!ref || !ref.startsWith(this.definitionsPrefix)) {
throw new Error('expecting a local reference');
}

const lookup = ref.substr(DEFINITIONS_PREFIX.length);
const lookup = ref.substr(this.definitionsPrefix.length);
const found = this.definitions[lookup];
if (!found) {
throw new Error(`unable to find a definition for the $ref "${lookup}"`);
Expand Down
53 changes: 53 additions & 0 deletions test/__snapshots__/type-generator.test.ts.snap

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

20 changes: 20 additions & 0 deletions test/type-generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,26 @@ test('custom ref normalization', async () => {

});

test('custom definition prefix', async () => {

const foo = 'io.k8s.v1beta1.Foo';
const bar = 'Bar';

const gen = new TypeGenerator({
definitionsPrefix: '#/$defs/',
});

gen.addDefinition(foo, { properties: { props: { type: 'number' } } });

// two structs, each referencing a different version
gen.addDefinition(bar, { properties: { prop: { $ref: `#/$defs/${foo}` } } });
gen.emitType(bar);

const code = await generate(gen);
expect(code).toMatchSnapshot();

});

test('shared namespace references', async () => {

const foo1 = 'io.k8s.v1beta1.Foo';
Expand Down
Loading