javascript.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { getNodeText, getChildByField } from '../tree-sitter-helpers';
  2. import type { LanguageExtractor } from '../tree-sitter-types';
  3. export const javascriptExtractor: LanguageExtractor = {
  4. functionTypes: ['function_declaration', 'arrow_function', 'function_expression'],
  5. classTypes: ['class_declaration'],
  6. methodTypes: ['method_definition', 'field_definition'],
  7. interfaceTypes: [],
  8. structTypes: [],
  9. enumTypes: [],
  10. typeAliasTypes: [],
  11. importTypes: ['import_statement'],
  12. callTypes: ['call_expression'],
  13. variableTypes: ['lexical_declaration', 'variable_declaration'],
  14. nameField: 'name',
  15. bodyField: 'body',
  16. paramsField: 'parameters',
  17. getSignature: (node, source) => {
  18. const params = getChildByField(node, 'parameters');
  19. return params ? getNodeText(params, source) : undefined;
  20. },
  21. isExported: (node, _source) => {
  22. let current = node.parent;
  23. while (current) {
  24. if (current.type === 'export_statement') return true;
  25. current = current.parent;
  26. }
  27. return false;
  28. },
  29. isAsync: (node) => {
  30. for (let i = 0; i < node.childCount; i++) {
  31. const child = node.child(i);
  32. if (child?.type === 'async') return true;
  33. }
  34. return false;
  35. },
  36. isConst: (node) => {
  37. if (node.type === 'lexical_declaration') {
  38. for (let i = 0; i < node.childCount; i++) {
  39. const child = node.child(i);
  40. if (child?.type === 'const') return true;
  41. }
  42. }
  43. return false;
  44. },
  45. extractImport: (node, source) => {
  46. const sourceField = node.childForFieldName('source');
  47. if (sourceField) {
  48. const moduleName = source.substring(sourceField.startIndex, sourceField.endIndex).replace(/['"]/g, '');
  49. if (moduleName) {
  50. return { moduleName, signature: source.substring(node.startIndex, node.endIndex).trim() };
  51. }
  52. }
  53. return null;
  54. },
  55. };