updateSchemaIndex function

void updateSchemaIndex(
  1. String name,
  2. String tsPath
)

Implementation

void updateSchemaIndex(String name, String tsPath) {
  final schemaName = '${toCamelCase(name)}Component';
  final file = File('$tsPath/index.ts');
  if (!file.existsSync()) {
    print(
        '⚠️ Could not find index.ts at ${file.path}. Please add the import and export manually.');
    return;
  }

  var content = file.readAsStringSync();
  if (content.contains("import $schemaName")) {
    return;
  }

  // Find the last import line and insert the new import after it
  final importRegex = RegExp(r"^import\s+.*\n", multiLine: true);
  final imports = importRegex.allMatches(content);
  if (imports.isNotEmpty) {
    final lastImport = imports.last;
    final importStatement =
        "import $schemaName from './components/$schemaName'\n";
    content =
        content.replaceRange(lastImport.end, lastImport.end, importStatement);
  }

  // Target the schemaTypes array closing bracket specifically to avoid false matches
  // Use replaceFirstMapped to build the replacement without literal $ interpretation
  final newContent = content.replaceFirstMapped(
    RegExp(r'(export const schemaTypes = \[[\s\S]*?)\]'),
    (match) => '${match.group(1)}  $schemaName,\n]',
  );

  file.writeAsStringSync(newContent);
  print('✅ Updated index.ts');
}