in src/type-generator.ts [434:477]
private emitEnum(typeName: string, def: JSONSchema4, structFqn: string): EmittedType {
const emitted: EmittedType = {
type: typeName,
toJson: x => x,
};
this.emitCustomType(typeName, code => {
if (!def.enum || def.enum.length === 0) {
throw new Error(`definition is not an enum: ${JSON.stringify(def)}`);
}
if (def.type && def.type !== 'string') {
throw new Error('can only generate string enums');
}
this.emitDescription(code, structFqn, def.description);
code.openBlock(`export enum ${typeName}`);
for (const value of def.enum) {
if (typeof(value) !== 'string') {
throw new Error('can only generate enums for string values');
}
// sluggify and turn to UPPER_SNAKE_CASE
let memberName = snakeCase(value.replace(/[^a-z0-9]/gi, '_')).split('_').filter(x => x).join('_').toUpperCase();
// if member name starts with a non-alpha character, add a prefix so it becomes a symbol
if (!/^[A-Z].*/i.test(memberName)) {
memberName = 'VALUE_' + memberName;
}
code.line(`/** ${value} */`);
code.line(`${memberName} = '${value}',`);
}
code.closeBlock();
return emitted;
});
return emitted;
}