type-crafter 0.12.2 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -20548,23 +20548,29 @@ var YAML = /*#__PURE__*/Object.freeze({
20548
20548
  });
20549
20549
 
20550
20550
  function hasColorSupport() {
20551
- if (process.env.NO_COLOR !== undefined)
20551
+ if (typeof process.env.NO_COLOR !== 'undefined') {
20552
20552
  return false;
20553
- if (process.env.FORCE_COLOR !== undefined)
20553
+ }
20554
+ if (typeof process.env.FORCE_COLOR !== 'undefined') {
20554
20555
  return true;
20555
- if (process.env.COLORTERM === 'truecolor' || process.env.COLORTERM === '24bit')
20556
+ }
20557
+ if (process.env.COLORTERM === 'truecolor' || process.env.COLORTERM === '24bit') {
20556
20558
  return true;
20557
- if (process.env.CI)
20559
+ }
20560
+ if (typeof process.env.CI !== 'undefined') {
20558
20561
  return true;
20562
+ }
20559
20563
  const term = process.env.TERM ?? '';
20560
- if (term === 'dumb')
20564
+ if (term === 'dumb') {
20561
20565
  return false;
20566
+ }
20562
20567
  if (term.includes('256color') ||
20563
20568
  term.includes('color') ||
20564
20569
  term.includes('xterm') ||
20565
20570
  term.includes('screen') ||
20566
- term.includes('vt100'))
20571
+ term.includes('vt100')) {
20567
20572
  return true;
20573
+ }
20568
20574
  return process.stdout.isTTY ?? false;
20569
20575
  }
20570
20576
  const isColorSupported = hasColorSupport();
@@ -20579,8 +20585,9 @@ function bgRgb(r, g, b) {
20579
20585
  return `\x1b[48;2;${r};${g};${b}m`;
20580
20586
  }
20581
20587
  function colorize$2(text, ...codes) {
20582
- if (!isColorSupported)
20588
+ if (!isColorSupported) {
20583
20589
  return text;
20590
+ }
20584
20591
  return codes.join('') + text + RESET;
20585
20592
  }
20586
20593
  const BRAND$2 = {
@@ -20629,14 +20636,16 @@ function interpolateColor(start, end, t) {
20629
20636
  };
20630
20637
  }
20631
20638
  function gradientText(text, startColor, endColor) {
20632
- if (!isColorSupported)
20639
+ if (!isColorSupported) {
20633
20640
  return text;
20641
+ }
20634
20642
  // eslint-disable-next-line @typescript-eslint/no-misused-spread -- character-by-character gradient
20635
20643
  const chars = [...text];
20636
20644
  return chars
20637
20645
  .map((char, i) => {
20638
- if (char === ' ' || char === '\n')
20646
+ if (char === ' ' || char === '\n') {
20639
20647
  return char;
20648
+ }
20640
20649
  const t = chars.length > 1 ? i / (chars.length - 1) : 0;
20641
20650
  const color = interpolateColor(startColor, endColor, t);
20642
20651
  return rgb(color.r, color.g, color.b) + char;
@@ -20699,8 +20708,9 @@ function createSpinner(message) {
20699
20708
  spinnerFrame = 0;
20700
20709
  return {
20701
20710
  start: () => {
20702
- if (activeSpinner)
20711
+ if (activeSpinner) {
20703
20712
  clearInterval(activeSpinner);
20713
+ }
20704
20714
  const render = () => {
20705
20715
  clearSpinnerLine();
20706
20716
  const frame = isColorSupported
@@ -20749,8 +20759,9 @@ function createSpinner(message) {
20749
20759
  };
20750
20760
  }
20751
20761
  function badge(text, bgColor, fgColor = FG.white) {
20752
- if (!isColorSupported)
20762
+ if (!isColorSupported) {
20753
20763
  return `[${text}]`;
20764
+ }
20754
20765
  return `${bgColor}${fgColor}${BOLD} ${text} ${RESET}`;
20755
20766
  }
20756
20767
  function logError(header, message = null) {
@@ -20883,12 +20894,26 @@ async function getExpectedWrittenPath(basePath, fileName) {
20883
20894
  : path.join(process.cwd(), basePath, fileName);
20884
20895
  return filePath;
20885
20896
  }
20886
- async function writeFile(basePath, fileName, content) {
20897
+ async function safeReadContent(filePath) {
20898
+ try {
20899
+ return await fs.readFile(filePath, 'utf-8');
20900
+ }
20901
+ catch (e) {
20902
+ return '';
20903
+ }
20904
+ }
20905
+ async function writeFile(basePath, fileName, content, append = false) {
20887
20906
  const isAbsolutePath = path.isAbsolute(basePath);
20888
20907
  const filePath = isAbsolutePath
20889
20908
  ? path.join(basePath, fileName)
20890
20909
  : path.join(process.cwd(), basePath, fileName);
20891
- await fs.writeFile(filePath, content);
20910
+ if (append) {
20911
+ const existingData = await safeReadContent(filePath);
20912
+ await fs.writeFile(filePath, content + existingData);
20913
+ }
20914
+ else {
20915
+ await fs.writeFile(filePath, content);
20916
+ }
20892
20917
  }
20893
20918
  async function readYaml(filePath) {
20894
20919
  const fileData = await readFile(filePath, true, true);
@@ -20986,7 +21011,7 @@ function handleErrors(error) {
20986
21011
  }
20987
21012
  }
20988
21013
 
20989
- let config$2 = null;
21014
+ let config$3 = null;
20990
21015
  let specFileData = null;
20991
21016
  let objectSyntaxTemplate = null;
20992
21017
  let exporterModuleSyntaxTemplate = null;
@@ -20997,13 +21022,13 @@ let allOfSyntaxTemplate = null;
20997
21022
  const cachedReferencedTypes = new Map();
20998
21023
  let expectedOutputFiles = null;
20999
21024
  function setConfig(newConfig) {
21000
- config$2 = newConfig;
21025
+ config$3 = newConfig;
21001
21026
  }
21002
21027
  function getConfig() {
21003
- if (config$2 === null) {
21028
+ if (config$3 === null) {
21004
21029
  throw new RuntimeError('Failed to load configuration!');
21005
21030
  }
21006
- return config$2;
21031
+ return config$3;
21007
21032
  }
21008
21033
  function setSpecFileData(newSpecFileData) {
21009
21034
  specFileData = newSpecFileData;
@@ -21072,10 +21097,10 @@ function cacheReferenceType(referencePath, generatedData) {
21072
21097
  cachedReferencedTypes.set(referencePath, generatedData);
21073
21098
  }
21074
21099
  function getInputFilePath(absolutePath = true) {
21075
- if (config$2 === null) {
21100
+ if (config$3 === null) {
21076
21101
  throw new RuntimeError('Spec file path not set!');
21077
21102
  }
21078
- return absolutePath ? resolveFilePath(config$2.input) : config$2.input;
21103
+ return absolutePath ? resolveFilePath(config$3.input) : config$3.input;
21079
21104
  }
21080
21105
  function getAllOfTemplate() {
21081
21106
  if (allOfSyntaxTemplate === null) {
@@ -21155,16 +21180,21 @@ function getReferencedTypeModules(_referencedTypes, _writtenAt) {
21155
21180
  return [];
21156
21181
  }
21157
21182
  const expectedOutputFiles = Runtime.getExpectedOutputFiles();
21183
+ const modulePathConfig = Runtime.getConfig().language.modulePathConfig;
21158
21184
  const referencedTypeModules = {};
21159
21185
  for (const referenceType of referencedTypes) {
21160
21186
  const outputFile = expectedOutputFiles.get(referenceType);
21161
21187
  if (typeof outputFile !== 'undefined' &&
21162
21188
  resolveFilePath(outputFile.filePath) !== resolveFilePath(writtenAt)) {
21163
21189
  if (typeof referencedTypeModules[outputFile.modulePath] === 'undefined') {
21190
+ const rawRelativePath = generateRelativePath(writtenAt, outputFile.modulePath);
21191
+ const moduleName = outputFile.modulePath.split('/').pop() ?? '';
21164
21192
  referencedTypeModules[outputFile.modulePath] = {
21165
21193
  modulePath: outputFile.modulePath,
21166
- moduleRelativePath: generateRelativePath(writtenAt, outputFile.modulePath),
21167
- referencedTypes: [referenceType]
21194
+ moduleRelativePath: formatModulePath(rawRelativePath, writtenAt, modulePathConfig),
21195
+ referencedTypes: [referenceType],
21196
+ moduleName,
21197
+ fileBasedModules: moduleName === (modulePathConfig?.moduleFileName ?? '')
21168
21198
  };
21169
21199
  }
21170
21200
  else {
@@ -21191,6 +21221,35 @@ function toPascalCaseHelper(input) {
21191
21221
  }
21192
21222
  return toPascalCase(inputString);
21193
21223
  }
21224
+ function toSnakeCase(input) {
21225
+ return input
21226
+ .replace(/[-]/g, '_')
21227
+ .replace(/(?<upper>[A-Z]+)(?<next>[A-Z][a-z])/g, '$1_$2')
21228
+ .replace(/(?<lower>[a-z\d])(?<cap>[A-Z])/g, '$1_$2')
21229
+ .toLowerCase()
21230
+ .replace(/__+/g, '_');
21231
+ }
21232
+ function toSnakeCaseHelper(input) {
21233
+ const inputString = decodeString(input);
21234
+ if (inputString === null) {
21235
+ return input;
21236
+ }
21237
+ return toSnakeCase(inputString);
21238
+ }
21239
+ function toCamelCase(input) {
21240
+ const pascal = toPascalCase(input);
21241
+ return pascal.charAt(0).toLowerCase() + pascal.slice(1);
21242
+ }
21243
+ function formatCase(input, fontCase) {
21244
+ switch (fontCase) {
21245
+ case 'snake_case':
21246
+ return toSnakeCase(input);
21247
+ case 'PascalCase':
21248
+ return toPascalCase(input);
21249
+ case 'camelCase':
21250
+ return toCamelCase(input);
21251
+ }
21252
+ }
21194
21253
  function refineJSONKey(input) {
21195
21254
  if (typeof input === 'string' && input.includes('-')) {
21196
21255
  return `'${input}'`;
@@ -21209,6 +21268,19 @@ function refineIndexKey(input) {
21209
21268
  }
21210
21269
  return input;
21211
21270
  }
21271
+ function escapeReservedWord(input) {
21272
+ if (typeof input !== 'string') {
21273
+ return input;
21274
+ }
21275
+ const config = Runtime.getConfig().language.reservedKeywords;
21276
+ if (typeof config === 'undefined') {
21277
+ return input;
21278
+ }
21279
+ if (config.words.includes(input)) {
21280
+ return config.prefix + input;
21281
+ }
21282
+ return input;
21283
+ }
21212
21284
  function registerTemplateHelpers() {
21213
21285
  Handlebars.registerHelper('getOptionalKeys', getOptionalKeys);
21214
21286
  Handlebars.registerHelper('getRequiredKeys', getRequiredKeys);
@@ -21216,6 +21288,7 @@ function registerTemplateHelpers() {
21216
21288
  Handlebars.registerHelper('getReferencedTypes', getReferencedTypes);
21217
21289
  Handlebars.registerHelper('getReferencedTypeModules', getReferencedTypeModules);
21218
21290
  Handlebars.registerHelper('toPascalCase', toPascalCaseHelper);
21291
+ Handlebars.registerHelper('toSnakeCase', toSnakeCaseHelper);
21219
21292
  Handlebars.registerHelper('isNonEmptyArray', (value) => Array.isArray(value) && value.length === 0);
21220
21293
  Handlebars.registerHelper('eq', (value1, value2) => value1 === value2);
21221
21294
  Handlebars.registerHelper('notEq', (value1, value2) => value1 !== value2);
@@ -21223,6 +21296,8 @@ function registerTemplateHelpers() {
21223
21296
  Handlebars.registerHelper('jsonKey', refineJSONKey);
21224
21297
  Handlebars.registerHelper('variableName', refineVariableName);
21225
21298
  Handlebars.registerHelper('indexKey', refineIndexKey);
21299
+ Handlebars.registerHelper('escapeReservedWord', escapeReservedWord);
21300
+ Handlebars.registerHelper('stringify', (value) => JSON.stringify(value));
21226
21301
  Handlebars.registerHelper('not', (value) => {
21227
21302
  if (typeof value === 'boolean') {
21228
21303
  return !value;
@@ -21265,6 +21340,30 @@ function generateRelativePath(fromPath, toPath) {
21265
21340
  pathPrefix = pathPrefix === '' ? './' : pathPrefix;
21266
21341
  return pathPrefix + toPathArray.slice(diffIndex).join('/');
21267
21342
  }
21343
+ function formatModulePath(relativePath, writtenAt, config) {
21344
+ let path = relativePath.replace(/^\.\//, '');
21345
+ const isModuleFile = writtenAt.endsWith('/' + config.moduleFileName) ||
21346
+ writtenAt.endsWith('\\' + config.moduleFileName);
21347
+ let parentCount = config.fileBasedModules && !isModuleFile ? 1 : 0;
21348
+ while (path.startsWith('../')) {
21349
+ parentCount++;
21350
+ path = path.slice(3);
21351
+ }
21352
+ const moduleFileRegex = new RegExp(`\\/?${config.moduleFileName}$`);
21353
+ path = path.replace(moduleFileRegex, '').replace(/\/$/, '');
21354
+ const parentPart = parentCount > 0 ? Array(parentCount).fill(config.parentRef).join(config.separator) : '';
21355
+ if (path === '' && parentPart === '') {
21356
+ return config.selfRef;
21357
+ }
21358
+ if (path === '') {
21359
+ return parentPart;
21360
+ }
21361
+ const formattedPath = path.replace(/\//g, config.separator);
21362
+ if (parentPart === '') {
21363
+ return formattedPath;
21364
+ }
21365
+ return parentPart + config.separator + formattedPath;
21366
+ }
21268
21367
  // #region string utils
21269
21368
  function stripPrefix(value, prefix) {
21270
21369
  return value.startsWith(prefix) ? value.slice(prefix.length) : value;
@@ -21513,8 +21612,7 @@ async function generateObjectType(typeName, typeInfo, parentTypes) {
21513
21612
  const referencedType = await generateReferencedType(propertyName, propertyDetails, parentTypes);
21514
21613
  recursivePropertyName = referencedType.templateInput.typeName;
21515
21614
  languageDataType = recursivePropertyName;
21516
- references.push(...referencedType.references);
21517
- primitives.push(...referencedType.primitives);
21615
+ references.push(recursivePropertyName);
21518
21616
  isReferenced = true;
21519
21617
  }
21520
21618
  else if (enumValues !== null) {
@@ -21628,6 +21726,18 @@ async function generateArrayType(typeName, typeInfo, parentTypes) {
21628
21726
  }
21629
21727
  else {
21630
21728
  arrayItemsType = await generateType(typeName + 'Item', typeInfo.items, parentTypes);
21729
+ // For referenced types (e.g. enums via $ref), use the type name as the item type
21730
+ // identifier, consistent with how inline enums are handled above.
21731
+ // Also only keep the direct reference — the referenced type handles its own imports.
21732
+ // Create new objects to avoid mutating cached data from generateReferencedType.
21733
+ if (typeInfo.items.$ref !== null) {
21734
+ const refItemTypeName = arrayItemsType.templateInput.typeName;
21735
+ arrayItemsType = {
21736
+ ...arrayItemsType,
21737
+ templateInput: { ...arrayItemsType.templateInput, type: refItemTypeName },
21738
+ references: new Set([refItemTypeName])
21739
+ };
21740
+ }
21631
21741
  }
21632
21742
  if (typeof arrayItemsType.templateInput?.type === 'undefined') {
21633
21743
  throw new InvalidSpecFileError('Invalid array type for: ' + typeName);
@@ -21893,28 +22003,41 @@ async function generator(specFileData) {
21893
22003
  }
21894
22004
  }
21895
22005
  result.groupedTypes = groupedTypes;
22006
+ // remove self references from grouped types
22007
+ for (const groupName in result.groupedTypes) {
22008
+ for (const typeName in result.groupedTypes[groupName]) {
22009
+ result.groupedTypes[groupName][typeName].references.delete(typeName);
22010
+ }
22011
+ }
21896
22012
  return result;
21897
22013
  }
21898
22014
 
22015
+ function formatModuleName(name) {
22016
+ const moduleNameCase = Runtime.getConfig().language.modulePathConfig.moduleNameCase;
22017
+ return typeof moduleNameCase !== 'undefined' ? formatCase(name, moduleNameCase) : name;
22018
+ }
21899
22019
  function generateTypesOutputFiles(types, groupName = null) {
21900
22020
  const config = Runtime.getConfig();
21901
22021
  const extension = config.output.fileExtension;
21902
22022
  const outputDir = config.output.directory;
21903
22023
  const moduleFileName = config.language.exporterModuleName;
21904
22024
  const writerMode = groupName === null ? config.output.writerMode.types : config.output.writerMode.groupedTypes;
22025
+ const formattedGroupName = groupName !== null ? formatModuleName(groupName) : null;
21905
22026
  const result = new Map();
21906
22027
  for (const typeName in types) {
21907
22028
  const typeProperties = types[typeName];
21908
22029
  if (typeof typeProperties !== 'undefined') {
22030
+ const formattedTypeName = formatModuleName(typeName);
21909
22031
  result.set(typeName, {
21910
22032
  modulePath: outputDir +
21911
22033
  '/' +
21912
- (writerMode === 'FolderWithFiles' ? (groupName ?? '') + '/' : '') +
21913
- moduleFileName,
22034
+ (formattedGroupName
22035
+ ? formattedGroupName + (writerMode === 'FolderWithFiles' ? '/' + moduleFileName : '')
22036
+ : moduleFileName),
21914
22037
  filePath: outputDir +
21915
22038
  (writerMode === 'Files' || writerMode === 'FolderWithFiles'
21916
- ? '/' + (groupName ?? '') + typeName
21917
- : '/' + (groupName ?? 'types')),
22039
+ ? '/' + (formattedGroupName ?? '') + formattedTypeName
22040
+ : '/' + (formattedGroupName ?? 'types')),
21918
22041
  extension
21919
22042
  });
21920
22043
  }
@@ -21935,7 +22058,8 @@ function generateExpectedOutputFile() {
21935
22058
  // Generating expect writing types for referenced types
21936
22059
  let referredGroups = {};
21937
22060
  for (const generatedRefData of Runtime.getCachedReferencedTypes().values()) {
21938
- if (typeof generatedRefData.sourceFile !== 'undefined' &&
22061
+ if (generatedRefData.type !== 'local' &&
22062
+ typeof generatedRefData.sourceFile !== 'undefined' &&
21939
22063
  generatedRefData.completeSource !== Runtime.getInputFilePath() // Preventing new file creation for remote references from base file
21940
22064
  ) {
21941
22065
  const groupName = toPascalCase(generatedRefData.sourceFile.replace('.yaml', ''));
@@ -21971,7 +22095,7 @@ async function writeTypesToFiles(config, types, folderName = '') {
21971
22095
  const typeNames = Object.keys(types);
21972
22096
  for (const typeName in types) {
21973
22097
  const typeData = types[typeName];
21974
- const file = typeName + config.output.fileExtension;
22098
+ const file = formatModuleName(typeName) + config.output.fileExtension;
21975
22099
  const references = filterReferences
21976
22100
  ? [...types[typeName].references].filter((x) => !typeNames.includes(x))
21977
22101
  : [...types[typeName].references];
@@ -21990,7 +22114,7 @@ async function writeTypesToFiles(config, types, folderName = '') {
21990
22114
  }
21991
22115
  return result;
21992
22116
  }
21993
- async function writeTypesToFile(config, types, fileName = 'types') {
22117
+ async function writeTypesToFile(config, types, fileName) {
21994
22118
  const templateInput = {
21995
22119
  referencedTypes: [],
21996
22120
  primitives: [],
@@ -22020,7 +22144,13 @@ async function writeExporterModules(files, folder) {
22020
22144
  const exporterModuleContent = Runtime.getExporterModuleTemplate()({
22021
22145
  modules: [...files].map((file) => file.replace(Runtime.getConfig().output.fileExtension, ''))
22022
22146
  });
22023
- await writeFile(folder, Runtime.getConfig().language.exporterModuleName + Runtime.getConfig().output.fileExtension, exporterModuleContent);
22147
+ const config = Runtime.getConfig();
22148
+ // Merging the contents of exporter module & types file in case their names are same.
22149
+ const typesFileName = Runtime.getConfig().output.typesFileName;
22150
+ const moduleExporterFileName = Runtime.getConfig().language.exporterModuleName;
22151
+ const writingTypesFile = files.has(typesFileName + config.output.fileExtension);
22152
+ const appendContent = writingTypesFile && typesFileName === moduleExporterFileName;
22153
+ await writeFile(folder, Runtime.getConfig().language.exporterModuleName + Runtime.getConfig().output.fileExtension, exporterModuleContent, appendContent);
22024
22154
  }
22025
22155
  async function writeOutput(generationResult) {
22026
22156
  const config = Runtime.getConfig();
@@ -22031,28 +22161,30 @@ async function writeOutput(generationResult) {
22031
22161
  const writtenFiles = new Map();
22032
22162
  // pre compute all the folders and files that will be written
22033
22163
  Runtime.setExpectedOutputFiles(generateExpectedOutputFile());
22034
- // writing types to output directory
22164
+ // #region writing types to output directory
22035
22165
  let typesFilesWritten = null;
22036
22166
  if (Object.keys(generationResult.types).length > 0) {
22037
22167
  if (config.output.writerMode.types === 'Files') {
22038
22168
  typesFilesWritten = await writeTypesToFiles(config, generationResult.types);
22039
22169
  }
22040
22170
  else if (config.output.writerMode.types === 'SingleFile') {
22041
- typesFilesWritten = await writeTypesToFile(config, generationResult.types);
22171
+ typesFilesWritten = await writeTypesToFile(config, generationResult.types, Runtime.getConfig().output.typesFileName);
22042
22172
  }
22043
22173
  }
22044
22174
  if (typesFilesWritten !== null) {
22045
22175
  addValuesToMappedSet(writtenFiles, await getCompleteFolderPath(typesFilesWritten.folderName), typesFilesWritten.files);
22046
22176
  }
22047
- // writing grouped types to output directory
22177
+ // #endregion
22178
+ // #region writing grouped types to output directory
22048
22179
  if (config.output.writerMode.groupedTypes === 'FolderWithFiles') {
22049
22180
  for (const groupName in generationResult.groupedTypes) {
22050
22181
  let groupFilesWritten = null;
22051
- await createFolderWithBasePath(config.output.directory, groupName);
22182
+ const formattedGroupName = formatModuleName(groupName);
22183
+ await createFolderWithBasePath(config.output.directory, formattedGroupName);
22052
22184
  addValuesToMappedSet(writtenFiles, await getCompleteFolderPath(config.output.directory), [
22053
- groupName
22185
+ formattedGroupName
22054
22186
  ]);
22055
- groupFilesWritten = await writeTypesToFiles(config, generationResult.groupedTypes[groupName], groupName);
22187
+ groupFilesWritten = await writeTypesToFiles(config, generationResult.groupedTypes[groupName], formattedGroupName);
22056
22188
  if (groupFilesWritten !== null) {
22057
22189
  addValuesToMappedSet(writtenFiles, await getCompleteFolderPath(groupFilesWritten.folderName), groupFilesWritten.files);
22058
22190
  }
@@ -22061,18 +22193,19 @@ async function writeOutput(generationResult) {
22061
22193
  else if (config.output.writerMode.groupedTypes === 'SingleFile') {
22062
22194
  for (const groupName in generationResult.groupedTypes) {
22063
22195
  let groupFilesWritten = null;
22064
- groupFilesWritten = await writeTypesToFile(config, generationResult.groupedTypes[groupName], groupName);
22196
+ groupFilesWritten = await writeTypesToFile(config, generationResult.groupedTypes[groupName], formatModuleName(groupName));
22065
22197
  if (groupFilesWritten !== null) {
22066
22198
  addValuesToMappedSet(writtenFiles, await getCompleteFolderPath(groupFilesWritten.folderName), groupFilesWritten.files);
22067
22199
  }
22068
22200
  }
22069
22201
  }
22202
+ // #endregion
22070
22203
  writtenFiles.forEach((files, folder) => {
22071
22204
  void writeExporterModules(files, folder);
22072
22205
  });
22073
22206
  }
22074
22207
 
22075
- async function config$1(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode) {
22208
+ async function config$2(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode) {
22076
22209
  const devMode = 'PRODUCTION'.includes('DEVELOPMENT');
22077
22210
  // PRODUCTION will be replaced with PRODUCTION when package is built.
22078
22211
  const directoryPrefix = devMode ? 'src/' : './';
@@ -22088,6 +22221,7 @@ async function config$1(inputFilePath, outputDirectory, typesWriterMode, grouped
22088
22221
  cleanWrite: true,
22089
22222
  fileExtension: '.ts',
22090
22223
  directory: outputDirectory,
22224
+ typesFileName: 'types',
22091
22225
  writerMode: {
22092
22226
  groupedTypes: groupedTypesWriterMode,
22093
22227
  types: typesWriterMode
@@ -22111,13 +22245,20 @@ async function config$1(inputFilePath, outputDirectory, typesWriterMode, grouped
22111
22245
  array: '~ItemType~[]',
22112
22246
  object: 'type',
22113
22247
  unknown: 'unknown'
22248
+ },
22249
+ modulePathConfig: {
22250
+ separator: '/',
22251
+ parentRef: '..',
22252
+ selfRef: '.',
22253
+ moduleFileName: 'index',
22254
+ fileBasedModules: false
22114
22255
  }
22115
22256
  }
22116
22257
  };
22117
22258
  return config;
22118
22259
  }
22119
22260
 
22120
- async function config(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode) {
22261
+ async function config$1(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode) {
22121
22262
  const devMode = 'PRODUCTION'.includes('DEVELOPMENT');
22122
22263
  const directoryPrefix = devMode ? 'src/' : './';
22123
22264
  const objectSyntax = await readFile(directoryPrefix + 'templates/typescript-with-decoders/object-syntax.hbs', devMode);
@@ -22132,6 +22273,7 @@ async function config(inputFilePath, outputDirectory, typesWriterMode, groupedTy
22132
22273
  cleanWrite: true,
22133
22274
  fileExtension: '.ts',
22134
22275
  directory: outputDirectory,
22276
+ typesFileName: 'types',
22135
22277
  writerMode: {
22136
22278
  groupedTypes: groupedTypesWriterMode,
22137
22279
  types: typesWriterMode
@@ -22155,6 +22297,123 @@ async function config(inputFilePath, outputDirectory, typesWriterMode, groupedTy
22155
22297
  array: '~ItemType~[]',
22156
22298
  object: 'type',
22157
22299
  unknown: 'unknown'
22300
+ },
22301
+ modulePathConfig: {
22302
+ separator: '/',
22303
+ parentRef: '..',
22304
+ selfRef: '.',
22305
+ moduleFileName: 'index',
22306
+ fileBasedModules: false
22307
+ }
22308
+ }
22309
+ };
22310
+ return config;
22311
+ }
22312
+
22313
+ async function config(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode) {
22314
+ const devMode = 'PRODUCTION'.includes('DEVELOPMENT');
22315
+ // PRODUCTION will be replaced with PRODUCTION when package is built.
22316
+ const directoryPrefix = devMode ? 'src/' : './';
22317
+ const objectSyntax = await readFile(directoryPrefix + 'templates/rust/object-syntax.hbs', devMode);
22318
+ const exporterModuleSyntax = await readFile(directoryPrefix + 'templates/rust/exporter-module-syntax.hbs', devMode);
22319
+ const typesFileSyntax = await readFile(directoryPrefix + 'templates/rust/types-file-syntax.hbs', devMode);
22320
+ const enumSyntax = await readFile(directoryPrefix + 'templates/rust/enum-syntax.hbs', devMode);
22321
+ const oneOfSyntax = await readFile(directoryPrefix + 'templates/rust/oneOf-syntax.hbs', devMode);
22322
+ const allOfSyntax = await readFile(directoryPrefix + 'templates/rust/allOf-syntax.hbs', devMode);
22323
+ const config = {
22324
+ input: inputFilePath,
22325
+ output: {
22326
+ cleanWrite: true,
22327
+ fileExtension: '.rs',
22328
+ directory: outputDirectory,
22329
+ typesFileName: 'mod',
22330
+ writerMode: {
22331
+ groupedTypes: groupedTypesWriterMode,
22332
+ types: typesWriterMode
22333
+ }
22334
+ },
22335
+ template: {
22336
+ objectSyntax,
22337
+ exporterModuleSyntax,
22338
+ typesFileSyntax,
22339
+ enumSyntax,
22340
+ oneOfSyntax,
22341
+ allOfSyntax
22342
+ },
22343
+ language: {
22344
+ exporterModuleName: 'mod',
22345
+ typeMapper: {
22346
+ string: { default: 'String' },
22347
+ number: { default: 'i32' },
22348
+ integer: { default: 'i32' },
22349
+ boolean: 'bool',
22350
+ array: 'Vec<~ItemType~>',
22351
+ object: 'type',
22352
+ unknown: 'String'
22353
+ },
22354
+ modulePathConfig: {
22355
+ separator: '::',
22356
+ parentRef: 'super',
22357
+ selfRef: 'self',
22358
+ moduleFileName: 'mod',
22359
+ fileBasedModules: true,
22360
+ moduleNameCase: 'snake_case'
22361
+ },
22362
+ reservedKeywords: {
22363
+ prefix: 'r#',
22364
+ words: [
22365
+ 'as',
22366
+ 'break',
22367
+ 'const',
22368
+ 'continue',
22369
+ 'crate',
22370
+ 'else',
22371
+ 'enum',
22372
+ 'extern',
22373
+ 'false',
22374
+ 'fn',
22375
+ 'for',
22376
+ 'if',
22377
+ 'impl',
22378
+ 'in',
22379
+ 'let',
22380
+ 'loop',
22381
+ 'match',
22382
+ 'mod',
22383
+ 'move',
22384
+ 'mut',
22385
+ 'pub',
22386
+ 'ref',
22387
+ 'return',
22388
+ 'self',
22389
+ 'Self',
22390
+ 'static',
22391
+ 'struct',
22392
+ 'super',
22393
+ 'trait',
22394
+ 'true',
22395
+ 'type',
22396
+ 'unsafe',
22397
+ 'use',
22398
+ 'where',
22399
+ 'while',
22400
+ 'async',
22401
+ 'await',
22402
+ 'dyn',
22403
+ 'abstract',
22404
+ 'become',
22405
+ 'box',
22406
+ 'do',
22407
+ 'final',
22408
+ 'macro',
22409
+ 'override',
22410
+ 'priv',
22411
+ 'typeof',
22412
+ 'unsized',
22413
+ 'virtual',
22414
+ 'yield',
22415
+ 'try'
22416
+ ]
22158
22417
  }
22159
22418
  }
22160
22419
  };
@@ -22192,9 +22451,12 @@ async function runner(language, inputFilePath, outputDirectory, _typesWriterMode
22192
22451
  let generatorConfig = null;
22193
22452
  switch (language.toLowerCase()) {
22194
22453
  case 'typescript':
22195
- generatorConfig = await config$1(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode);
22454
+ generatorConfig = await config$2(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode);
22196
22455
  break;
22197
22456
  case 'typescript-with-decoders':
22457
+ generatorConfig = await config$1(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode);
22458
+ break;
22459
+ case 'rust':
22198
22460
  generatorConfig = await config(inputFilePath, outputDirectory, typesWriterMode, groupedTypesWriterMode);
22199
22461
  break;
22200
22462
  default:
@@ -22224,7 +22486,7 @@ async function runner(language, inputFilePath, outputDirectory, _typesWriterMode
22224
22486
  }
22225
22487
  }
22226
22488
  greeting();
22227
- const program = new Command().version('0.12.2');
22489
+ const program = new Command().version('0.13.1');
22228
22490
  program
22229
22491
  .command('generate')
22230
22492
  .description('Generate types for your language from a type spec file')
@@ -1,2 +1,3 @@
1
1
  export * as typescript from './typescript';
2
2
  export * as typescriptWithDecoders from './typescript-with-decoders';
3
+ export * as rust from './rust';
@@ -0,0 +1,26 @@
1
+ {{#if description}}
2
+ /// {{{description}}}
3
+ {{/if}}
4
+ #[derive(Debug, Clone, Serialize, Deserialize)]
5
+ pub struct {{typeName}} {
6
+ {{#each compositions}}
7
+ {{#if (eq this.source 'referenced')}}
8
+ #[serde(flatten)]
9
+ pub {{escapeReservedWord (toSnakeCase this.referencedType)}}: {{this.referencedType}},
10
+ {{else if (eq this.source 'inline')}}
11
+ {{#if (eq this.dataType 'object')}}
12
+ #[serde(flatten)]
13
+ pub {{escapeReservedWord (toSnakeCase this.templateInput.typeName)}}: {{this.templateInput.typeName}},
14
+ {{else}}
15
+ pub {{escapeReservedWord (toSnakeCase this.templateInput.typeName)}}: {{{this.templateInput.type}}},
16
+ {{/if}}
17
+ {{/if}}
18
+ {{/each}}
19
+ }
20
+ {{#each compositions}}
21
+ {{#if (eq this.source 'inline')}}
22
+ {{#if (eq this.dataType 'object')}}
23
+ {{{this.content}}}
24
+ {{/if}}
25
+ {{/if}}
26
+ {{/each}}
@@ -0,0 +1,17 @@
1
+ {{#if description}}
2
+ /// {{{description}}}
3
+ {{/if}}
4
+ {{#if example}}
5
+ /// Example: {{{example}}}
6
+ {{/if}}
7
+ #[derive(Debug, Clone, Serialize, Deserialize)]
8
+ pub enum {{typeName}} {
9
+ {{#each values}}
10
+ {{#if (eq ../type 'string')}}
11
+ #[serde(rename = "{{this}}")]
12
+ {{{toPascalCase this}}},
13
+ {{else}}
14
+ Value{{{this}}},
15
+ {{/if}}
16
+ {{/each}}
17
+ }
@@ -0,0 +1,3 @@
1
+ {{#each modules}}
2
+ pub mod {{this}};
3
+ {{/each}}
@@ -0,0 +1,2 @@
1
+ import type { Configuration, TypesWriterMode, GroupedTypesWriterMode } from '$types';
2
+ export declare function config(inputFilePath: string, outputDirectory: string, typesWriterMode: TypesWriterMode, groupedTypesWriterMode: GroupedTypesWriterMode): Promise<Configuration>;
@@ -0,0 +1,23 @@
1
+ {{#if description}}
2
+ /// {{{description}}}
3
+ {{/if}}
4
+ {{#if example}}
5
+ /// Example: {{{example}}}
6
+ {{/if}}
7
+ #[derive(Debug, Clone, Serialize, Deserialize)]
8
+ pub struct {{typeName}} {
9
+ {{#each properties}}
10
+ {{#if this.description}}
11
+ /// {{{this.description}}}
12
+ {{/if}}
13
+ #[serde(rename = "{{@key}}")]
14
+ {{#unless this.required}}
15
+ #[serde(skip_serializing_if = "Option::is_none")]
16
+ {{/unless}}
17
+ pub {{escapeReservedWord (toSnakeCase @key)}}: {{#unless this.required}}Option<{{/unless}}{{{this.type}}}{{#unless this.required}}>{{/unless}},
18
+ {{/each}}
19
+ {{#if additionalProperties}}
20
+ #[serde(flatten)]
21
+ pub additional_properties: std::collections::HashMap<{{{additionalProperties.keyType}}}, {{{additionalProperties.valueType}}}>,
22
+ {{/if}}
23
+ }
@@ -0,0 +1,25 @@
1
+ {{#if description}}
2
+ /// {{{description}}}
3
+ {{/if}}
4
+ #[derive(Debug, Clone, Serialize, Deserialize)]
5
+ #[serde(untagged)]
6
+ pub enum {{typeName}} {
7
+ {{#each compositions}}
8
+ {{#if (eq this.source 'referenced')}}
9
+ {{this.referencedType}}({{this.referencedType}}),
10
+ {{else if (eq this.source 'inline')}}
11
+ {{#if this.templateInput.values}}
12
+ {{this.templateInput.typeName}}({{this.templateInput.typeName}}),
13
+ {{else if (eq this.dataType 'object')}}
14
+ {{this.templateInput.typeName}}({{this.templateInput.typeName}}),
15
+ {{else}}
16
+ {{this.templateInput.typeName}}({{{this.templateInput.type}}}),
17
+ {{/if}}
18
+ {{/if}}
19
+ {{/each}}
20
+ }
21
+ {{#each compositions}}
22
+ {{#if (eq this.source 'inline')}}
23
+ {{{this.content}}}
24
+ {{/if}}
25
+ {{/each}}
@@ -0,0 +1,12 @@
1
+ use serde::{Serialize, Deserialize};
2
+ {{#each (getReferencedTypeModules referencedTypes writtenAt)}}
3
+ {{#each this.referencedTypes}}
4
+ {{#if ../fileBasedModules}}
5
+ use {{{../moduleRelativePath}}}::{{toSnakeCase this}}::{{this}};
6
+ {{else}}
7
+ use {{{../moduleRelativePath}}}::{{this}};
8
+ {{/if}}
9
+ {{/each}}
10
+ {{/each}}
11
+
12
+ {{{typesContent}}}
@@ -9,6 +9,7 @@ export type OutputConfig = {
9
9
  cleanWrite: boolean;
10
10
  fileExtension: string;
11
11
  directory: string;
12
+ typesFileName: string;
12
13
  writerMode: {
13
14
  groupedTypes: GroupedTypesWriterMode;
14
15
  types: TypesWriterMode;
@@ -24,9 +25,24 @@ export type Template = {
24
25
  oneOfSyntax: string;
25
26
  allOfSyntax: string;
26
27
  };
28
+ export type FontCase = 'snake_case' | 'PascalCase' | 'camelCase';
29
+ export type ModulePathConfig = {
30
+ separator: string;
31
+ parentRef: string;
32
+ selfRef: string;
33
+ moduleFileName: string;
34
+ fileBasedModules: boolean;
35
+ moduleNameCase?: FontCase;
36
+ };
37
+ export type ReservedKeywordsConfig = {
38
+ words: string[];
39
+ prefix: string;
40
+ };
27
41
  export type LanguageConfig = {
28
42
  exporterModuleName: string;
29
43
  typeMapper: LanguageTypeMapper;
44
+ modulePathConfig: ModulePathConfig;
45
+ reservedKeywords?: ReservedKeywordsConfig;
30
46
  };
31
47
  /**
32
48
  * @description Mappers for all the types supported by OpenAPI 3.0.0
@@ -139,6 +155,8 @@ export type ReferencedModule = {
139
155
  modulePath: string;
140
156
  moduleRelativePath: string;
141
157
  referencedTypes: string[];
158
+ moduleName: string;
159
+ fileBasedModules: boolean;
142
160
  };
143
161
  export type EnumTemplateInput = TypeDescriptors & {
144
162
  typeName: string;
@@ -5,5 +5,5 @@ export declare function createFolder(folderPath: string): Promise<void>;
5
5
  export declare function deleteFolder(folderPath: string): Promise<void>;
6
6
  export declare function getCompleteFolderPath(folderName: string): Promise<string>;
7
7
  export declare function getExpectedWrittenPath(basePath: string, fileName: string): Promise<string>;
8
- export declare function writeFile(basePath: string, fileName: string, content: string): Promise<void>;
8
+ export declare function writeFile(basePath: string, fileName: string, content: string, append?: boolean): Promise<void>;
9
9
  export declare function readYaml(filePath: string): Promise<unknown>;
@@ -1,4 +1,4 @@
1
- import { type TypeInfo, type TypeDataType } from '$types';
1
+ import { type ModulePathConfig, type FontCase, type TypeInfo, type TypeDataType } from '$types';
2
2
  import { type JSONObject } from 'type-decoder';
3
3
  export * from './file-system';
4
4
  export * from './logger';
@@ -9,12 +9,18 @@ export declare function getReferencedTypes(object: unknown): string[];
9
9
  export declare function getReferencedTypeModules(_referencedTypes: unknown, _writtenAt: string): unknown[];
10
10
  export declare function toPascalCase(input: string): string;
11
11
  export declare function toPascalCaseHelper(input: unknown): string | unknown;
12
+ export declare function toSnakeCase(input: string): string;
13
+ export declare function toSnakeCaseHelper(input: unknown): string | unknown;
14
+ export declare function toCamelCase(input: string): string;
15
+ export declare function formatCase(input: string, fontCase: FontCase): string;
12
16
  export declare function refineJSONKey(input: unknown): unknown;
13
17
  export declare function refineVariableName(input: unknown): unknown;
14
18
  export declare function refineIndexKey(input: unknown): unknown;
19
+ export declare function escapeReservedWord(input: unknown): unknown;
15
20
  export declare function registerTemplateHelpers(): void;
16
21
  export declare function readNestedValue(json: unknown, keyPath: string[]): JSONObject;
17
22
  export declare function generateRelativePath(fromPath: string, toPath: string): string;
23
+ export declare function formatModulePath(relativePath: string, writtenAt: string, config: ModulePathConfig): string;
18
24
  export declare function stripPrefix(value: string, prefix: string): string;
19
25
  export declare function isPrimitiveType(typeInfo: TypeInfo): boolean;
20
26
  export declare function isSimplePrimitiveType(type: TypeDataType | null): boolean;
@@ -1,3 +1,4 @@
1
1
  import { type TypeFilePath, type Types } from '$types';
2
+ export declare function formatModuleName(name: string): string;
2
3
  export declare function generateTypesOutputFiles(types: Types | null, groupName?: string | null): Map<string, TypeFilePath>;
3
4
  export declare function generateExpectedOutputFile(): Map<string, TypeFilePath>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "type-crafter",
3
- "version": "0.12.2",
3
+ "version": "0.13.1",
4
4
  "description": "A tool to generate types from a yaml schema for any language",
5
5
  "main": "./dist/index.js",
6
6
  "type": "module",
@@ -15,8 +15,8 @@
15
15
  ],
16
16
  "scripts": {
17
17
  "dev": "tsc --watch",
18
- "format:all": "npx prettier --write .",
19
- "lint:all": "eslint src",
18
+ "format": "npx prettier --write .",
19
+ "lint": "eslint src",
20
20
  "clean:output": "rm -rf dist",
21
21
  "build": "npm run clean:output && rollup --config rollup.config.js"
22
22
  },
@@ -49,12 +49,12 @@
49
49
  "@rollup/plugin-node-resolve": "^16.0.3",
50
50
  "@rollup/plugin-replace": "^6.0.3",
51
51
  "@rollup/plugin-typescript": "^12.3.0",
52
- "@types/node": "^25.2.0",
53
- "@typescript-eslint/eslint-plugin": "^8.54.0",
54
- "@typescript-eslint/parser": "^8.54.0",
52
+ "@types/node": "^25.2.3",
53
+ "@typescript-eslint/eslint-plugin": "^8.55.0",
54
+ "@typescript-eslint/parser": "^8.55.0",
55
55
  "commander": "^14.0.3",
56
- "eslint": "^9.39.2",
57
- "eslint-config-love": "^149.0.0",
56
+ "eslint": "^10.0.0",
57
+ "eslint-config-love": "^150.0.0",
58
58
  "eslint-config-prettier": "^10.1.8",
59
59
  "handlebars": "^4.7.8",
60
60
  "husky": "^9.1.7",
@@ -62,7 +62,7 @@
62
62
  "rollup": "^4.57.1",
63
63
  "rollup-plugin-copy": "^3.5.0",
64
64
  "tslib": "^2.8.1",
65
- "type-decoder": "^2.2.0",
65
+ "type-decoder": "^2.3.0",
66
66
  "typescript": "^5.9.3",
67
67
  "yaml": "^2.8.2"
68
68
  }