Dynamically imports a .ts file by converting it to a temporary .mjs file.
(locale)
| 32 | |
| 33 | /** Dynamically imports a .ts file by converting it to a temporary .mjs file. */ |
| 34 | async function loadLocaleModule(locale) { |
| 35 | const filePath = path.join(RESOURCES_DIR, `${locale}.ts`); |
| 36 | |
| 37 | if (!fs.existsSync(filePath)) { |
| 38 | throw new Error(`Locale file not found: ${filePath}`); |
| 39 | } |
| 40 | |
| 41 | // Read the TypeScript file |
| 42 | let content = fs.readFileSync(filePath, 'utf8'); |
| 43 | |
| 44 | // Remove imports (they won't work in our simple conversion) |
| 45 | content = content.replace(/^import\s+.*?;$/gm, ''); |
| 46 | |
| 47 | // Remove type exports at the end |
| 48 | content = content.replace(/export\s+type\s+.*?;$/gm, ''); |
| 49 | |
| 50 | // Convert TypeScript export to ES module format that Node can import |
| 51 | // Replace "export const locale = {" with "export default {" |
| 52 | content = content.replace( |
| 53 | new RegExp(`export\\s+const\\s+${locale}\\s*:\\s*\\w+\\s*=\\s*`, 'g'), |
| 54 | 'export default ' |
| 55 | ); |
| 56 | |
| 57 | // Also handle the case without type annotation |
| 58 | content = content.replace( |
| 59 | new RegExp(`export\\s+const\\s+${locale}\\s*=\\s*`, 'g'), |
| 60 | 'export default ' |
| 61 | ); |
| 62 | |
| 63 | // Write to temporary .mjs file |
| 64 | const tempPath = path.join(RESOURCES_DIR, `.${locale}.temp.mjs`); |
| 65 | fs.writeFileSync(tempPath, content); |
| 66 | |
| 67 | try { |
| 68 | // Import the temporary file with cache busting - need absolute path with file:// protocol |
| 69 | const absolutePath = path.resolve(tempPath); |
| 70 | const module = await import(`file://${absolutePath}?v=${Date.now()}`); |
| 71 | return module.default; |
| 72 | } finally { |
| 73 | // Clean up temporary file |
| 74 | if (fs.existsSync(tempPath)) { |
| 75 | fs.unlinkSync(tempPath); |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | /** Loads and flattens a locale file. */ |
| 81 | async function getLocaleMap(locale) { |
no test coverage detected