diff --git a/src/generators/android/android.ts b/src/generators/android/android.ts index 33bb7d0f..dc725893 100644 --- a/src/generators/android/android.ts +++ b/src/generators/android/android.ts @@ -2,6 +2,7 @@ import camelCase from 'lodash/camelCase.js'; import upperFirst from 'lodash/upperFirst.js'; import { Type, Schema, getPropertiesSchema } from '../ast.js'; import { Generator, GeneratorClient } from '../gen.js'; +import { sanitizeKey } from '../utils.js'; // These contexts are what will be passed to Handlebars to perform rendering. // Everything in these contexts should be properly sanitized. @@ -164,13 +165,13 @@ const convertToEnum = (values: any[], type: string) => { let key, formattedValue; if (type === 'String' || typeof value === 'string') { - key = 'S_' + value.toString().trim().toUpperCase().replace(/ /g, ''); + key = 'S_' + sanitizeKey(value); formattedValue = `"${value.toString().trim()}"`; // String values } else if (type === 'Long') { - key = 'L_' + value.toString(); - formattedValue = `${value}L`; // Long values + key = 'L_' + sanitizeKey(value); + formattedValue = Number(value) % 1 === 0 ? `${value}L` : value.toString(); // Long values } else if (type === 'Double') { - key = 'D_' + value.toString().replace('.', '_'); + key = 'D_' + sanitizeKey(value); formattedValue = `${value}D`; // Double values } diff --git a/src/generators/javascript/javascript.ts b/src/generators/javascript/javascript.ts index 78b2672c..ef49adf9 100644 --- a/src/generators/javascript/javascript.ts +++ b/src/generators/javascript/javascript.ts @@ -6,6 +6,7 @@ import { Generator, GeneratorClient, type File } from '../gen.js'; import { toTarget, toModule } from './targets.js'; import { registerPartial } from '../../templates.js'; import lodash from 'lodash'; +import { sanitizeKey } from '../utils.js'; const { camelCase, upperFirst } = lodash; @@ -213,10 +214,10 @@ const convertToEnum = (values: any[], type: string) => { let key, formattedValue; if (type === 'string' || typeof value === 'string') { - key = 'S_' + value.toString().trim().toUpperCase().replace(/ /g, '_'); + key = 'S_' + sanitizeKey(value); formattedValue = `'${value.toString().trim()}'`; } else if (type === 'number') { - key = 'N_' + value.toString().replace('.', '_'); + key = 'N_' + sanitizeKey(value); formattedValue = `${value}`; } diff --git a/src/generators/utils.ts b/src/generators/utils.ts new file mode 100644 index 00000000..c539c048 --- /dev/null +++ b/src/generators/utils.ts @@ -0,0 +1,7 @@ +export const sanitizeKey = (value: any) => + value + .toString() + .trim() + .toUpperCase() + .replace(/[^a-zA-Z0-9_]+|^_+|_+$/g, '_') + .replace(/_+/g, '_');