-
-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy pathtypescript.js
More file actions
449 lines (382 loc) · 15.4 KB
/
typescript.js
File metadata and controls
449 lines (382 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
import fs from 'fs'
import path from 'path'
import { pathToFileURL } from 'url'
/**
* Load tsconfig.json if it exists
* @param {string} tsConfigPath - Path to tsconfig.json
* @returns {object|null} - Parsed tsconfig or null
*/
function loadTsConfig(tsConfigPath) {
if (!fs.existsSync(tsConfigPath)) {
return null
}
try {
const tsConfigContent = fs.readFileSync(tsConfigPath, 'utf8')
return JSON.parse(tsConfigContent)
} catch (err) {
return null
}
}
/**
* Resolve TypeScript path alias to actual file path
* @param {string} importPath - Import path with alias (e.g., '#config/urls')
* @param {object} tsConfig - Parsed tsconfig.json
* @param {string} configDir - Directory containing tsconfig.json
* @returns {string|null} - Resolved file path or null if not an alias
*/
function resolveTsPathAlias(importPath, tsConfig, configDir) {
if (!tsConfig || !tsConfig.compilerOptions || !tsConfig.compilerOptions.paths) {
return null
}
const paths = tsConfig.compilerOptions.paths
for (const [pattern, targets] of Object.entries(paths)) {
if (!targets || targets.length === 0) {
continue
}
const patternRegex = new RegExp(
'^' + pattern.replace(/\*/g, '(.*)') + '$'
)
const match = importPath.match(patternRegex)
if (match) {
const wildcard = match[1] || ''
const target = targets[0]
const resolvedTarget = target.replace(/\*/g, wildcard)
return path.resolve(configDir, resolvedTarget)
}
}
return null
}
/**
* Transpile TypeScript files to ES modules with CommonJS shim support
* Handles recursive transpilation of imported TypeScript files
*
* @param {string} mainFilePath - Path to the main TypeScript file to transpile
* @param {object} typescript - TypeScript compiler instance
* @returns {Promise<{tempFile: string, allTempFiles: string[], fileMapping: any}>} - Main temp file and all temp files created
*/
export async function transpileTypeScript(mainFilePath, typescript) {
const { transpile } = typescript
/**
* Transpile a single TypeScript file to JavaScript
* Injects CommonJS shims (require, module, exports, __dirname, __filename) as needed
*/
const transpileTS = (filePath) => {
const tsContent = fs.readFileSync(filePath, 'utf8')
// Transpile TypeScript to JavaScript with ES module output
let jsContent = transpile(tsContent, {
module: 99, // ModuleKind.ESNext
target: 99, // ScriptTarget.ESNext
esModuleInterop: true,
allowSyntheticDefaultImports: true,
lib: ['lib.esnext.d.ts'], // Enable latest features including top-level await
suppressOutputPathCheck: true,
skipLibCheck: true,
})
// Check if the code uses CommonJS globals
const usesCommonJSGlobals = /__dirname|__filename/.test(jsContent)
const usesRequire = /\brequire\s*\(/.test(jsContent)
const usesModuleExports = /\b(module\.exports|exports\.)/.test(jsContent)
if (usesCommonJSGlobals || usesRequire || usesModuleExports) {
// Inject ESM equivalents at the top of the file
let esmGlobals = ''
if (usesRequire || usesModuleExports) {
// IMPORTANT: Use the original .ts file path as the base for require()
// This ensures dynamic require() calls work with relative paths from the original file location
const originalFileUrl = `file://${filePath.replace(/\\/g, '/')}`
esmGlobals += `import { createRequire } from 'module';
import { extname as __extname } from 'path';
const __baseRequire = createRequire('${originalFileUrl}');
// Wrap require to auto-resolve extensions (mimics CommonJS behavior)
const require = (id) => {
try {
return __baseRequire(id);
} catch (err) {
// If module not found and it's a relative/absolute path without extension, try common extensions
if (err.code === 'MODULE_NOT_FOUND' && (id.startsWith('./') || id.startsWith('../') || id.startsWith('/'))) {
const ext = __extname(id);
// Only treat known file extensions as real extensions (so names like .TEST don't block probing)
const __knownExts = ['.js', '.cjs', '.mjs', '.json', '.node'];
const hasKnownExt = ext && __knownExts.includes(ext.toLowerCase());
if (!hasKnownExt) {
// Try common extensions in order: .js, .cjs, .json, .node
// Note: .ts files cannot be required - they need transpilation first
const extensions = ['.js', '.cjs', '.json', '.node'];
for (const testExt of extensions) {
try {
return __baseRequire(id + testExt);
} catch (e) {
// Continue to next extension
}
}
}
}
// Re-throw original error if all attempts failed
throw err;
}
};
const module = { exports: {} };
const exports = module.exports;
`
}
if (usesCommonJSGlobals) {
// For __dirname and __filename, also use the original file path
const originalFileUrl = `file://${filePath.replace(/\\/g, '/')}`
esmGlobals += `import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __dirname_fn } from 'path';
const __filename = '${filePath.replace(/\\/g, '/')}';
const __dirname = __dirname_fn(__filename);
`
}
jsContent = esmGlobals + jsContent
// If module.exports is used, we need to export it as default
if (usesModuleExports) {
jsContent += `\nexport default module.exports;\n`
}
}
return jsContent
}
// Create a map to track transpiled files
const transpiledFiles = new Map()
const baseDir = path.dirname(mainFilePath)
// Try to find tsconfig.json by walking up the directory tree
let tsConfigPath = path.join(baseDir, 'tsconfig.json')
let configDir = baseDir
let searchDir = baseDir
while (!fs.existsSync(tsConfigPath) && searchDir !== path.dirname(searchDir)) {
searchDir = path.dirname(searchDir)
tsConfigPath = path.join(searchDir, 'tsconfig.json')
if (fs.existsSync(tsConfigPath)) {
configDir = searchDir
break
}
}
const tsConfig = loadTsConfig(tsConfigPath)
// Recursive function to transpile a file and all its TypeScript dependencies
const transpileFileAndDeps = (filePath) => {
// Already transpiled, skip
if (transpiledFiles.has(filePath)) {
return
}
// Transpile this file
let jsContent = transpileTS(filePath)
// Find all TypeScript imports in this file (both ESM imports and require() calls)
const importRegex = /from\s+['"]([^'"]+?)['"]/g
const requireRegex = /require\s*\(\s*['"]([^'"]+?)['"]\s*\)/g
let match
const imports = []
while ((match = importRegex.exec(jsContent)) !== null) {
imports.push({ path: match[1], type: 'import' })
}
while ((match = requireRegex.exec(jsContent)) !== null) {
imports.push({ path: match[1], type: 'require' })
}
// Get the base directory for this file
const fileBaseDir = path.dirname(filePath)
// Recursively transpile each imported TypeScript file
for (const { path: importPath } of imports) {
let importedPath = importPath
// Check if this is a path alias
const resolvedAlias = resolveTsPathAlias(importPath, tsConfig, configDir)
if (resolvedAlias) {
importedPath = resolvedAlias
} else if (importPath.startsWith('.')) {
importedPath = path.resolve(fileBaseDir, importPath)
} else {
continue
}
// Handle .js extensions that might actually be .ts files
if (importedPath.endsWith('.js')) {
const tsVersion = importedPath.replace(/\.js$/, '.ts')
if (fs.existsSync(tsVersion)) {
importedPath = tsVersion
}
}
// Check for standard module extensions to determine if we should try adding .ts
const ext = path.extname(importedPath)
const standardExtensions = ['.js', '.mjs', '.cjs', '.json', '.node']
const hasStandardExtension = standardExtensions.includes(ext.toLowerCase())
// If it doesn't end with .ts and doesn't have a standard extension, try adding .ts
if (!importedPath.endsWith('.ts') && !hasStandardExtension) {
const tsPath = importedPath + '.ts'
if (fs.existsSync(tsPath)) {
importedPath = tsPath
} else {
// Try index.ts for directory imports
const indexTsPath = path.join(importedPath, 'index.ts')
if (fs.existsSync(indexTsPath)) {
importedPath = indexTsPath
} else {
// Try .js extension as well
const jsPath = importedPath + '.js'
if (fs.existsSync(jsPath)) {
// Skip .js files, they don't need transpilation
continue
}
}
}
}
// If it's a TypeScript file, recursively transpile it and its dependencies
if (importedPath.endsWith('.ts') && fs.existsSync(importedPath)) {
transpileFileAndDeps(importedPath)
}
}
// After all dependencies are transpiled, rewrite imports in this file
jsContent = jsContent.replace(
/from\s+['"]([^'"]+?)['"]/g,
(match, importPath) => {
let resolvedPath = importPath
const originalExt = path.extname(importPath)
// Check if this is a path alias
const resolvedAlias = resolveTsPathAlias(importPath, tsConfig, configDir)
if (resolvedAlias) {
resolvedPath = resolvedAlias
} else if (importPath.startsWith('.')) {
resolvedPath = path.resolve(fileBaseDir, importPath)
} else {
return match
}
// If resolved path is a directory, try index.ts
if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isDirectory()) {
const indexPath = path.join(resolvedPath, 'index.ts')
if (fs.existsSync(indexPath) && transpiledFiles.has(indexPath)) {
const tempFile = transpiledFiles.get(indexPath)
const relPath = path.relative(fileBaseDir, tempFile).replace(/\\/g, '/')
if (!relPath.startsWith('.')) {
return `from './${relPath}'`
}
return `from '${relPath}'`
}
}
// Handle .js extension that might be .ts
if (resolvedPath.endsWith('.js')) {
const tsVersion = resolvedPath.replace(/\.js$/, '.ts')
if (transpiledFiles.has(tsVersion)) {
const tempFile = transpiledFiles.get(tsVersion)
const relPath = path.relative(fileBaseDir, tempFile).replace(/\\/g, '/')
if (!relPath.startsWith('.')) {
return `from './${relPath}'`
}
return `from '${relPath}'`
}
return match
}
// Try with .ts extension
const tsPath = resolvedPath.endsWith('.ts') ? resolvedPath : resolvedPath + '.ts'
// If we transpiled this file, use the temp file
if (transpiledFiles.has(tsPath)) {
const tempFile = transpiledFiles.get(tsPath)
const relPath = path.relative(fileBaseDir, tempFile).replace(/\\/g, '/')
if (!relPath.startsWith('.')) {
return `from './${relPath}'`
}
return `from '${relPath}'`
}
// Try index.ts for directory imports
const indexTsPath = path.join(resolvedPath, 'index.ts')
if (transpiledFiles.has(indexTsPath)) {
const tempFile = transpiledFiles.get(indexTsPath)
const relPath = path.relative(fileBaseDir, tempFile).replace(/\\/g, '/')
if (!relPath.startsWith('.')) {
return `from './${relPath}'`
}
return `from '${relPath}'`
}
// If the import doesn't have a standard module extension, add .js for ESM compatibility
const standardExtensions = ['.js', '.mjs', '.cjs', '.json', '.node']
const hasStandardExtension = standardExtensions.includes(originalExt.toLowerCase())
if (!hasStandardExtension) {
return match.replace(importPath, importPath + '.js')
}
return match
}
)
// Also rewrite require() calls to point to transpiled TypeScript files
jsContent = jsContent.replace(
/require\s*\(\s*['"]([^'"]+?)['"]\s*\)/g,
(match, requirePath) => {
let resolvedPath = requirePath
// Check if this is a path alias
const resolvedAlias = resolveTsPathAlias(requirePath, tsConfig, configDir)
if (resolvedAlias) {
resolvedPath = resolvedAlias
} else if (requirePath.startsWith('.')) {
resolvedPath = path.resolve(fileBaseDir, requirePath)
} else {
return match
}
// Handle .js extension that might be .ts
if (resolvedPath.endsWith('.js')) {
const tsVersion = resolvedPath.replace(/\.js$/, '.ts')
if (transpiledFiles.has(tsVersion)) {
const tempFile = transpiledFiles.get(tsVersion)
const relPath = path.relative(fileBaseDir, tempFile).replace(/\\/g, '/')
const finalPath = relPath.startsWith('.') ? relPath : './' + relPath
return `require('${finalPath}')`
}
return match
}
// Try with .ts extension
const tsPath = resolvedPath.endsWith('.ts') ? resolvedPath : resolvedPath + '.ts'
// If we transpiled this file, use the temp file
if (transpiledFiles.has(tsPath)) {
const tempFile = transpiledFiles.get(tsPath)
const relPath = path.relative(fileBaseDir, tempFile).replace(/\\/g, '/')
const finalPath = relPath.startsWith('.') ? relPath : './' + relPath
return `require('${finalPath}')`
}
// Otherwise, keep the require as-is
return match
}
)
// Write the transpiled file with updated imports
const tempFile = filePath.replace(/\.ts$/, '.temp.mjs')
fs.writeFileSync(tempFile, jsContent)
transpiledFiles.set(filePath, tempFile)
}
// Start recursive transpilation from the main file
transpileFileAndDeps(mainFilePath)
// Get the main transpiled file
const tempJsFile = transpiledFiles.get(mainFilePath)
// Convert to file:// URL for dynamic import() (required on Windows)
const tempFileUrl = pathToFileURL(tempJsFile).href
// Store all temp files for cleanup (keep as paths, not URLs)
const allTempFiles = Array.from(transpiledFiles.values())
return { tempFile: tempFileUrl, allTempFiles, fileMapping: transpiledFiles }
}
/**
* Map error stack traces from temp .mjs files back to original .ts files
* @param {Error} error - The error object to fix
* @param {Map<string, string>} fileMapping - Map of original .ts files to temp .mjs files
* @returns {Error} - Error with fixed stack trace
*/
export function fixErrorStack(error, fileMapping) {
if (!error.stack || !fileMapping) return error
let stack = error.stack
// Create reverse mapping (temp.mjs -> original.ts)
const reverseMap = new Map()
for (const [tsFile, mjsFile] of fileMapping.entries()) {
reverseMap.set(mjsFile, tsFile)
}
// Replace all temp.mjs references with original .ts files
for (const [mjsFile, tsFile] of reverseMap.entries()) {
const mjsPattern = mjsFile.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
stack = stack.replace(new RegExp(mjsPattern, 'g'), tsFile)
}
error.stack = stack
return error
}
/**
* Clean up temporary transpiled files
* @param {string[]} tempFiles - Array of temp file paths to delete
*/
export function cleanupTempFiles(tempFiles) {
for (const file of tempFiles) {
if (fs.existsSync(file)) {
try {
fs.unlinkSync(file)
} catch (err) {
// Ignore cleanup errors
}
}
}
}