import-emitted-specifier.test.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /**
  2. * TypeScript's node16/nodenext/bundler resolution writes the EMITTED extension
  3. * in a relative specifier (`./util.js` for `util.ts`). The import resolver must
  4. * map that back to the source file that is actually in the repo; otherwise the
  5. * imported names fall through to bare-name matching and a method that wraps a
  6. * same-named import resolves to itself.
  7. */
  8. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  9. import * as fs from 'fs';
  10. import * as path from 'path';
  11. import * as os from 'os';
  12. import { CodeGraph } from '../src';
  13. import { resolveImportPath } from '../src/resolution/import-resolver';
  14. import type { ResolutionContext } from '../src/resolution';
  15. function contextWithFiles(files: string[]): ResolutionContext {
  16. const set = new Set(files);
  17. return {
  18. getNodesInFile: () => [],
  19. getNodesByName: () => [],
  20. getNodesByQualifiedName: () => [],
  21. getNodesByKind: () => [],
  22. fileExists: (p: string) => set.has(p),
  23. readFile: () => null,
  24. getProjectRoot: () => '/test',
  25. getAllFiles: () => files,
  26. getNodesByLowerName: () => [],
  27. getImportMappings: () => [],
  28. } as unknown as ResolutionContext;
  29. }
  30. describe('emitted-extension import specifiers (`./x.js` naming `x.ts`)', () => {
  31. it('maps a relative .js specifier onto the .ts source', () => {
  32. const ctx = contextWithFiles(['shared/engine.ts', 'shared/util.ts']);
  33. expect(resolveImportPath('./util.js', 'shared/engine.ts', 'typescript', ctx)).toBe('shared/util.ts');
  34. });
  35. it('prefers a real .js file over the remap when both exist', () => {
  36. const ctx = contextWithFiles(['shared/engine.ts', 'shared/util.js', 'shared/util.ts']);
  37. expect(resolveImportPath('./util.js', 'shared/engine.ts', 'typescript', ctx)).toBe('shared/util.js');
  38. });
  39. it('maps .jsx, .mjs and .cjs onto their TypeScript sources', () => {
  40. const ctx = contextWithFiles(['app/a.tsx', 'app/View.tsx', 'app/esm.mts', 'app/cjs.cts']);
  41. expect(resolveImportPath('./View.jsx', 'app/a.tsx', 'tsx', ctx)).toBe('app/View.tsx');
  42. expect(resolveImportPath('./esm.mjs', 'app/a.tsx', 'tsx', ctx)).toBe('app/esm.mts');
  43. expect(resolveImportPath('./cjs.cjs', 'app/a.tsx', 'tsx', ctx)).toBe('app/cjs.cts');
  44. });
  45. it('maps an aliased .js specifier through tsconfig paths', () => {
  46. const files = ['src/main.ts', 'src/lib/util.ts'];
  47. const ctx = {
  48. ...contextWithFiles(files),
  49. getProjectAliases: () => ({
  50. baseUrl: '/test',
  51. patterns: [{ prefix: '@/', suffix: '', hasWildcard: true, replacements: ['src/*'] }],
  52. }),
  53. } as unknown as ResolutionContext;
  54. expect(resolveImportPath('@/lib/util.js', 'src/main.ts', 'typescript', ctx)).toBe('src/lib/util.ts');
  55. });
  56. it('leaves a specifier that names no source unresolved', () => {
  57. const ctx = contextWithFiles(['shared/engine.ts']);
  58. expect(resolveImportPath('./missing.js', 'shared/engine.ts', 'typescript', ctx)).toBeNull();
  59. });
  60. it('does not remap for a language without TypeScript emit (python)', () => {
  61. const ctx = contextWithFiles(['pkg/a.py', 'pkg/b.ts']);
  62. expect(resolveImportPath('./b.js', 'pkg/a.py', 'python', ctx)).toBeNull();
  63. });
  64. });
  65. describe('end to end: a wrapper method calling the same-named import it wraps', () => {
  66. let tempDir: string;
  67. let cg: CodeGraph | null = null;
  68. beforeEach(() => {
  69. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-emitted-spec-'));
  70. });
  71. afterEach(() => {
  72. cg?.destroy();
  73. cg = null;
  74. try {
  75. fs.rmSync(tempDir, { recursive: true, force: true });
  76. } catch {
  77. // Windows can still hold the SQLite handle for a moment; the OS temp dir is swept anyway.
  78. }
  79. });
  80. it('links the call to the imported function, not to the method itself', async () => {
  81. fs.writeFileSync(
  82. path.join(tempDir, 'template.ts'),
  83. 'export function renderDockStyles(): string {\n return ".dock {}";\n}\n'
  84. );
  85. fs.writeFileSync(
  86. path.join(tempDir, 'sidebar.ts'),
  87. [
  88. 'import { renderDockStyles } from "./template.js";',
  89. '',
  90. 'export class Sidebar {',
  91. ' renderDockStyles(): string {',
  92. ' return renderDockStyles();',
  93. ' }',
  94. '}',
  95. '',
  96. ].join('\n')
  97. );
  98. cg = await CodeGraph.init(tempDir, { index: true });
  99. cg.resolveReferences();
  100. const method = cg.getNodesByKind('method').find((n) => n.name === 'renderDockStyles');
  101. const fn = cg
  102. .getNodesByKind('function')
  103. .find((n) => n.name === 'renderDockStyles' && n.filePath === 'template.ts');
  104. expect(method).toBeDefined();
  105. expect(fn).toBeDefined();
  106. const targets = cg
  107. .getOutgoingEdges(method!.id)
  108. .filter((e) => e.kind === 'calls')
  109. .map((e) => e.target);
  110. expect(targets).toContain(fn!.id);
  111. expect(targets).not.toContain(method!.id);
  112. });
  113. });