getTSImportedNames.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {TokenType as tt} from "../parser/tokenizer/types";
  2. import getImportExportSpecifierInfo from "./getImportExportSpecifierInfo";
  3. /**
  4. * Special case code to scan for imported names in ESM TypeScript. We need to do this so we can
  5. * properly get globals so we can compute shadowed globals.
  6. *
  7. * This is similar to logic in CJSImportProcessor, but trimmed down to avoid logic with CJS
  8. * replacement and flow type imports.
  9. */
  10. export default function getTSImportedNames(tokens) {
  11. const importedNames = new Set();
  12. for (let i = 0; i < tokens.tokens.length; i++) {
  13. if (
  14. tokens.matches1AtIndex(i, tt._import) &&
  15. !tokens.matches3AtIndex(i, tt._import, tt.name, tt.eq)
  16. ) {
  17. collectNamesForImport(tokens, i, importedNames);
  18. }
  19. }
  20. return importedNames;
  21. }
  22. function collectNamesForImport(
  23. tokens,
  24. index,
  25. importedNames,
  26. ) {
  27. index++;
  28. if (tokens.matches1AtIndex(index, tt.parenL)) {
  29. // Dynamic import, so nothing to do
  30. return;
  31. }
  32. if (tokens.matches1AtIndex(index, tt.name)) {
  33. importedNames.add(tokens.identifierNameAtIndex(index));
  34. index++;
  35. if (tokens.matches1AtIndex(index, tt.comma)) {
  36. index++;
  37. }
  38. }
  39. if (tokens.matches1AtIndex(index, tt.star)) {
  40. // * as
  41. index += 2;
  42. importedNames.add(tokens.identifierNameAtIndex(index));
  43. index++;
  44. }
  45. if (tokens.matches1AtIndex(index, tt.braceL)) {
  46. index++;
  47. collectNamesForNamedImport(tokens, index, importedNames);
  48. }
  49. }
  50. function collectNamesForNamedImport(
  51. tokens,
  52. index,
  53. importedNames,
  54. ) {
  55. while (true) {
  56. if (tokens.matches1AtIndex(index, tt.braceR)) {
  57. return;
  58. }
  59. const specifierInfo = getImportExportSpecifierInfo(tokens, index);
  60. index = specifierInfo.endIndex;
  61. if (!specifierInfo.isType) {
  62. importedNames.add(specifierInfo.rightName);
  63. }
  64. if (tokens.matches2AtIndex(index, tt.comma, tt.braceR)) {
  65. return;
  66. } else if (tokens.matches1AtIndex(index, tt.braceR)) {
  67. return;
  68. } else if (tokens.matches1AtIndex(index, tt.comma)) {
  69. index++;
  70. } else {
  71. throw new Error(`Unexpected token: ${JSON.stringify(tokens.tokens[index])}`);
  72. }
  73. }
  74. }