UNPKG

@intlayer/config

Version:

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

77 lines 2.64 kB
import { buildSync } from "esbuild"; import { dirname } from "path"; import { runInNewContext } from "vm"; import { getSandBoxContext } from "./getSandboxContext.mjs"; import { logger } from "./logger.mjs"; import { ESMxCJSRequire } from "./utils/ESMxCJSHelpers.mjs"; const getTransformationOptions = (filePath) => ({ loader: { ".js": "js", ".jsx": "jsx", ".mjs": "js", ".ts": "ts", ".tsx": "tsx", ".cjs": "js", ".json": "json", ".md": "text", ".mdx": "text" }, format: "cjs", // Output format as commonjs target: "es2017", packages: "external", write: false, bundle: true, banner: { js: ` globalThis.intlayer_file_path = ${JSON.stringify(filePath)}; globalThis.intlayer_file_dir = ${JSON.stringify(dirname(filePath))}; ` } }); const loadExternalFile = (filePath, envVarOptions, projectRequire = ESMxCJSRequire) => { let fileContent = void 0; const fileExtension = filePath.split(".").pop() ?? ""; try { if (fileExtension === "json") { delete ESMxCJSRequire.cache[ESMxCJSRequire.resolve(filePath)]; return ESMxCJSRequire(filePath); } const moduleResult = buildSync({ entryPoints: [filePath], ...getTransformationOptions(filePath) }); const moduleResultString = moduleResult.outputFiles?.[0].text; if (!moduleResultString) { logger("File could not be loaded.", { level: "error" }); return void 0; } const sandboxContext = getSandBoxContext(envVarOptions, projectRequire); runInNewContext(moduleResultString, sandboxContext); if (sandboxContext.exports.default && Object.keys(sandboxContext.exports.default).length > 0) { fileContent = sandboxContext.exports.default; } else if (sandboxContext.module.exports.defaults && Object.keys(sandboxContext.module.exports.defaults).length > 0) { fileContent = sandboxContext.module.exports.default; } else if (sandboxContext.module.exports.default && Object.keys(sandboxContext.module.exports.default).length > 0) { fileContent = sandboxContext.module.exports.default; } else if (sandboxContext.module.exports && Object.keys(sandboxContext.module.exports).length > 0) { fileContent = sandboxContext.module.exports; } if (typeof fileContent === "undefined") { logger(`File file could not be loaded. Path : ${filePath}`); return void 0; } return fileContent; } catch (error) { logger( `Error: ${error} ${JSON.stringify(error.stack, null, 2)}`, { level: "error" } ); } }; export { loadExternalFile }; //# sourceMappingURL=loadExternalFile.mjs.map