UNPKG

@intlayer/config

Version:

Retrieve Intlayer configurations and manage environment variables for both server-side and client-side environments.

80 lines (78 loc) 2.35 kB
import { getPackageJsonPath } from "../utils/getPackageJsonPath.mjs"; import { getLoader } from "./bundleFile.mjs"; import { existsSync } from "node:fs"; import { dirname, extname, join } from "node:path"; import { createRequire } from "node:module"; import { buildSync, context } from "esbuild"; import { pathToFileURL } from "node:url"; //#region src/loadExternalFile/transpileTSToCJS.ts const getTsConfigPath = (filePath) => { const tsconfigPath = join(getPackageJsonPath(dirname(filePath)).baseDir, "tsconfig.json"); return existsSync(tsconfigPath) ? tsconfigPath : void 0; }; const getTransformationOptions = (filePath) => ({ loader: { ".js": "js", ".jsx": "jsx", ".mjs": "js", ".ts": "ts", ".tsx": "tsx", ".cjs": "js", ".json": "json", ".md": "text", ".mdx": "text" }, format: "cjs", target: "node20", platform: "node", write: false, packages: "external", bundle: true, tsconfig: getTsConfigPath(filePath), define: { "import.meta.url": JSON.stringify(pathToFileURL(filePath).href), "import.meta.env": "process.env" } }); const transpileTSToCJSSync = (code, filePath, options) => { const loader = getLoader(extname(filePath)); const { esbuildInstance, ...buildOptions } = options ?? {}; const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync; if (typeof globalThis.__filename !== "string") try { const esbuildEntry = createRequire(import.meta.url).resolve("esbuild"); globalThis.__filename = esbuildEntry; globalThis.__dirname = dirname(esbuildEntry); } catch {} return esbuildBuildSync({ stdin: { contents: code, loader, resolveDir: dirname(filePath), sourcefile: filePath }, ...getTransformationOptions(filePath), ...buildOptions }).outputFiles?.[0].text; }; const transpileTSToCJS = async (code, filePath, options) => { const loader = getLoader(extname(filePath)); const { esbuildInstance, ...buildOptions } = options ?? {}; const ctx = await (esbuildInstance?.context ?? context)({ stdin: { contents: code, loader, resolveDir: dirname(filePath), sourcefile: filePath }, ...getTransformationOptions(filePath), ...buildOptions }); try { return (await ctx.rebuild()).outputFiles?.[0].text; } finally { await ctx.dispose(); } }; //#endregion export { transpileTSToCJS, transpileTSToCJSSync }; //# sourceMappingURL=transpileTSToCJS.mjs.map