@intlayer/config 9.0.0-canary.8 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/built.cjs +2 -0
- package/dist/cjs/built.cjs.map +1 -1
- package/dist/cjs/bundle/index.cjs +1 -1
- package/dist/cjs/bundle/index.cjs.map +1 -1
- package/dist/cjs/bundle/logBundle.cjs.map +1 -1
- package/dist/cjs/callers/base.cjs +42 -0
- package/dist/cjs/callers/base.cjs.map +1 -0
- package/dist/cjs/callers/compat/i18next.cjs +27 -0
- package/dist/cjs/callers/compat/i18next.cjs.map +1 -0
- package/dist/cjs/callers/compat/lingui.cjs +82 -0
- package/dist/cjs/callers/compat/lingui.cjs.map +1 -0
- package/dist/cjs/callers/compat/nextIntl.cjs +44 -0
- package/dist/cjs/callers/compat/nextIntl.cjs.map +1 -0
- package/dist/cjs/callers/compat/reactI18next.cjs +50 -0
- package/dist/cjs/callers/compat/reactI18next.cjs.map +1 -0
- package/dist/cjs/callers/compat/reactIntl.cjs +31 -0
- package/dist/cjs/callers/compat/reactIntl.cjs.map +1 -0
- package/dist/cjs/callers/compat/useIntl.cjs +46 -0
- package/dist/cjs/callers/compat/useIntl.cjs.map +1 -0
- package/dist/cjs/callers/compat/vueI18n.cjs +26 -0
- package/dist/cjs/callers/compat/vueI18n.cjs.map +1 -0
- package/dist/cjs/callers/index.cjs +87 -0
- package/dist/cjs/callers/index.cjs.map +1 -0
- package/dist/cjs/callers/transform.cjs +46 -0
- package/dist/cjs/callers/transform.cjs.map +1 -0
- package/dist/cjs/callers/types.cjs +0 -0
- package/dist/cjs/client.cjs +1 -0
- package/dist/cjs/configFile/buildBrowserConfiguration.cjs +47 -3
- package/dist/cjs/configFile/buildBrowserConfiguration.cjs.map +1 -1
- package/dist/cjs/configFile/buildConfigurationFields.cjs +9 -3
- package/dist/cjs/configFile/buildConfigurationFields.cjs.map +1 -1
- package/dist/cjs/configFile/configurationSchema.cjs +7 -0
- package/dist/cjs/configFile/configurationSchema.cjs.map +1 -1
- package/dist/cjs/configFile/getConfiguration.cjs +10 -3
- package/dist/cjs/configFile/getConfiguration.cjs.map +1 -1
- package/dist/cjs/configFile/index.cjs +2 -0
- package/dist/cjs/configFile/loadConfigurationFile.cjs.map +1 -1
- package/dist/cjs/configFile/searchConfigurationFile.cjs +0 -1
- package/dist/cjs/configFile/searchConfigurationFile.cjs.map +1 -1
- package/dist/cjs/defaultValues/analytics.cjs +16 -0
- package/dist/cjs/defaultValues/analytics.cjs.map +1 -0
- package/dist/cjs/defaultValues/build.cjs.map +1 -1
- package/dist/cjs/defaultValues/content.cjs.map +1 -1
- package/dist/cjs/defaultValues/index.cjs +4 -0
- package/dist/cjs/defaultValues/internationalization.cjs.map +1 -1
- package/dist/cjs/defaultValues/routing.cjs.map +1 -1
- package/dist/cjs/envVars/envVars.cjs +2 -1
- package/dist/cjs/envVars/envVars.cjs.map +1 -1
- package/dist/cjs/loadEnvFile.cjs +44 -7
- package/dist/cjs/loadEnvFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/bundleFile.cjs +4 -3
- package/dist/cjs/loadExternalFile/bundleFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/bundleJSFile.cjs +0 -1
- package/dist/cjs/loadExternalFile/bundleJSFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/index.cjs +1 -0
- package/dist/cjs/loadExternalFile/loadExternalFile.cjs +11 -6
- package/dist/cjs/loadExternalFile/loadExternalFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/parseFileContent.cjs +52 -17
- package/dist/cjs/loadExternalFile/parseFileContent.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +99 -10
- package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
- package/dist/cjs/logger.cjs +2 -1
- package/dist/cjs/logger.cjs.map +1 -1
- package/dist/cjs/node.cjs +2 -0
- package/dist/cjs/utils/ESMxCJSHelpers.cjs +0 -1
- package/dist/cjs/utils/ESMxCJSHelpers.cjs.map +1 -1
- package/dist/cjs/utils/alias.cjs +0 -1
- package/dist/cjs/utils/alias.cjs.map +1 -1
- package/dist/cjs/utils/builtConfigKeys.cjs +38 -0
- package/dist/cjs/utils/builtConfigKeys.cjs.map +1 -0
- package/dist/cjs/utils/cacheDisk.cjs +2 -1
- package/dist/cjs/utils/cacheDisk.cjs.map +1 -1
- package/dist/cjs/utils/cacheMemory.cjs +0 -1
- package/dist/cjs/utils/cacheMemory.cjs.map +1 -1
- package/dist/cjs/utils/clearModuleCache.cjs.map +1 -1
- package/dist/cjs/utils/compareVersions.cjs.map +1 -1
- package/dist/cjs/utils/extractErrorMessage.cjs.map +1 -1
- package/dist/cjs/utils/getDictionarySelectorUsage.cjs.map +1 -1
- package/dist/cjs/utils/getExtension.cjs.map +1 -1
- package/dist/cjs/utils/getPackageJsonPath.cjs +0 -1
- package/dist/cjs/utils/getPackageJsonPath.cjs.map +1 -1
- package/dist/cjs/utils/getStorageAttributes.cjs +2 -1
- package/dist/cjs/utils/getStorageAttributes.cjs.map +1 -1
- package/dist/cjs/utils/getUsedNodeTypes.cjs +0 -1
- package/dist/cjs/utils/getUsedNodeTypes.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +2 -0
- package/dist/cjs/utils/logStack.cjs.map +1 -1
- package/dist/cjs/utils/normalizePath.cjs.map +1 -1
- package/dist/cjs/utils/parseFilePathPattern.cjs.map +1 -1
- package/dist/cjs/utils/pathSecurity.cjs +0 -1
- package/dist/cjs/utils/pathSecurity.cjs.map +1 -1
- package/dist/cjs/utils/retryManager.cjs.map +1 -1
- package/dist/cjs/utils/setIntlayerIdentifier.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs.map +1 -1
- package/dist/esm/built.mjs +2 -1
- package/dist/esm/built.mjs.map +1 -1
- package/dist/esm/bundle/index.mjs +2 -2
- package/dist/esm/bundle/index.mjs.map +1 -1
- package/dist/esm/bundle/logBundle.mjs.map +1 -1
- package/dist/esm/callers/base.mjs +40 -0
- package/dist/esm/callers/base.mjs.map +1 -0
- package/dist/esm/callers/compat/i18next.mjs +25 -0
- package/dist/esm/callers/compat/i18next.mjs.map +1 -0
- package/dist/esm/callers/compat/lingui.mjs +80 -0
- package/dist/esm/callers/compat/lingui.mjs.map +1 -0
- package/dist/esm/callers/compat/nextIntl.mjs +42 -0
- package/dist/esm/callers/compat/nextIntl.mjs.map +1 -0
- package/dist/esm/callers/compat/reactI18next.mjs +48 -0
- package/dist/esm/callers/compat/reactI18next.mjs.map +1 -0
- package/dist/esm/callers/compat/reactIntl.mjs +29 -0
- package/dist/esm/callers/compat/reactIntl.mjs.map +1 -0
- package/dist/esm/callers/compat/useIntl.mjs +44 -0
- package/dist/esm/callers/compat/useIntl.mjs.map +1 -0
- package/dist/esm/callers/compat/vueI18n.mjs +24 -0
- package/dist/esm/callers/compat/vueI18n.mjs.map +1 -0
- package/dist/esm/callers/index.mjs +72 -0
- package/dist/esm/callers/index.mjs.map +1 -0
- package/dist/esm/callers/transform.mjs +43 -0
- package/dist/esm/callers/transform.mjs.map +1 -0
- package/dist/esm/callers/types.mjs +0 -0
- package/dist/esm/client.mjs +2 -2
- package/dist/esm/configFile/buildBrowserConfiguration.mjs +47 -4
- package/dist/esm/configFile/buildBrowserConfiguration.mjs.map +1 -1
- package/dist/esm/configFile/buildConfigurationFields.mjs +10 -4
- package/dist/esm/configFile/buildConfigurationFields.mjs.map +1 -1
- package/dist/esm/configFile/configurationSchema.mjs +7 -1
- package/dist/esm/configFile/configurationSchema.mjs.map +1 -1
- package/dist/esm/configFile/getConfiguration.mjs +10 -2
- package/dist/esm/configFile/getConfiguration.mjs.map +1 -1
- package/dist/esm/configFile/index.mjs +3 -3
- package/dist/esm/configFile/loadConfigurationFile.mjs.map +1 -1
- package/dist/esm/configFile/searchConfigurationFile.mjs.map +1 -1
- package/dist/esm/defaultValues/analytics.mjs +12 -0
- package/dist/esm/defaultValues/analytics.mjs.map +1 -0
- package/dist/esm/defaultValues/build.mjs.map +1 -1
- package/dist/esm/defaultValues/content.mjs.map +1 -1
- package/dist/esm/defaultValues/index.mjs +2 -1
- package/dist/esm/defaultValues/internationalization.mjs.map +1 -1
- package/dist/esm/defaultValues/routing.mjs.map +1 -1
- package/dist/esm/envVars/envVars.mjs +2 -1
- package/dist/esm/envVars/envVars.mjs.map +1 -1
- package/dist/esm/loadEnvFile.mjs +45 -8
- package/dist/esm/loadEnvFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/bundleFile.mjs +4 -2
- package/dist/esm/loadExternalFile/bundleFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/bundleJSFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/index.mjs +2 -2
- package/dist/esm/loadExternalFile/loadExternalFile.mjs +11 -6
- package/dist/esm/loadExternalFile/loadExternalFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/parseFileContent.mjs +52 -17
- package/dist/esm/loadExternalFile/parseFileContent.mjs.map +1 -1
- package/dist/esm/loadExternalFile/transpileTSToCJS.mjs +102 -13
- package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
- package/dist/esm/logger.mjs +2 -1
- package/dist/esm/logger.mjs.map +1 -1
- package/dist/esm/node.mjs +3 -3
- package/dist/esm/utils/ESMxCJSHelpers.mjs.map +1 -1
- package/dist/esm/utils/alias.mjs.map +1 -1
- package/dist/esm/utils/builtConfigKeys.mjs +36 -0
- package/dist/esm/utils/builtConfigKeys.mjs.map +1 -0
- package/dist/esm/utils/cacheDisk.mjs +6 -5
- package/dist/esm/utils/cacheDisk.mjs.map +1 -1
- package/dist/esm/utils/cacheMemory.mjs.map +1 -1
- package/dist/esm/utils/clearModuleCache.mjs.map +1 -1
- package/dist/esm/utils/compareVersions.mjs.map +1 -1
- package/dist/esm/utils/extractErrorMessage.mjs.map +1 -1
- package/dist/esm/utils/getDictionarySelectorUsage.mjs.map +1 -1
- package/dist/esm/utils/getExtension.mjs.map +1 -1
- package/dist/esm/utils/getPackageJsonPath.mjs.map +1 -1
- package/dist/esm/utils/getStorageAttributes.mjs +2 -1
- package/dist/esm/utils/getStorageAttributes.mjs.map +1 -1
- package/dist/esm/utils/getUsedNodeTypes.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +2 -1
- package/dist/esm/utils/logStack.mjs.map +1 -1
- package/dist/esm/utils/normalizePath.mjs.map +1 -1
- package/dist/esm/utils/parseFilePathPattern.mjs.map +1 -1
- package/dist/esm/utils/pathSecurity.mjs.map +1 -1
- package/dist/esm/utils/retryManager.mjs.map +1 -1
- package/dist/esm/utils/setIntlayerIdentifier.mjs.map +1 -1
- package/dist/esm/utils/stringFormatter/camelCaseToKebabCase.mjs.map +1 -1
- package/dist/esm/utils/stringFormatter/camelCaseToSentence.mjs.map +1 -1
- package/dist/esm/utils/stringFormatter/kebabCaseToCamelCase.mjs.map +1 -1
- package/dist/esm/utils/stringFormatter/toLowerCamelCase.mjs.map +1 -1
- package/dist/types/built.d.ts +2 -1
- package/dist/types/built.d.ts.map +1 -1
- package/dist/types/bundle/index.d.ts +2 -4
- package/dist/types/bundle/index.d.ts.map +1 -1
- package/dist/types/bundle/logBundle.d.ts +0 -1
- package/dist/types/bundle/logBundle.d.ts.map +1 -1
- package/dist/types/callers/base.d.ts +13 -0
- package/dist/types/callers/base.d.ts.map +1 -0
- package/dist/types/callers/compat/i18next.d.ts +11 -0
- package/dist/types/callers/compat/i18next.d.ts.map +1 -0
- package/dist/types/callers/compat/lingui.d.ts +6 -0
- package/dist/types/callers/compat/lingui.d.ts.map +1 -0
- package/dist/types/callers/compat/nextIntl.d.ts +12 -0
- package/dist/types/callers/compat/nextIntl.d.ts.map +1 -0
- package/dist/types/callers/compat/reactI18next.d.ts +14 -0
- package/dist/types/callers/compat/reactI18next.d.ts.map +1 -0
- package/dist/types/callers/compat/reactIntl.d.ts +15 -0
- package/dist/types/callers/compat/reactIntl.d.ts.map +1 -0
- package/dist/types/callers/compat/useIntl.d.ts +11 -0
- package/dist/types/callers/compat/useIntl.d.ts.map +1 -0
- package/dist/types/callers/compat/vueI18n.d.ts +11 -0
- package/dist/types/callers/compat/vueI18n.d.ts.map +1 -0
- package/dist/types/callers/index.d.ts +48 -0
- package/dist/types/callers/index.d.ts.map +1 -0
- package/dist/types/callers/transform.d.ts +60 -0
- package/dist/types/callers/transform.d.ts.map +1 -0
- package/dist/types/callers/types.d.ts +160 -0
- package/dist/types/callers/types.d.ts.map +1 -0
- package/dist/types/client.d.ts +2 -2
- package/dist/types/colors.d.ts +14 -14
- package/dist/types/colors.d.ts.map +1 -1
- package/dist/types/configFile/buildBrowserConfiguration.d.ts +24 -4
- package/dist/types/configFile/buildBrowserConfiguration.d.ts.map +1 -1
- package/dist/types/configFile/buildConfigurationFields.d.ts +8 -4
- package/dist/types/configFile/buildConfigurationFields.d.ts.map +1 -1
- package/dist/types/configFile/configurationSchema.d.ts +43 -34
- package/dist/types/configFile/configurationSchema.d.ts.map +1 -1
- package/dist/types/configFile/getConfiguration.d.ts +0 -1
- package/dist/types/configFile/getConfiguration.d.ts.map +1 -1
- package/dist/types/configFile/index.d.ts +3 -3
- package/dist/types/configFile/loadConfigurationFile.d.ts +1 -2
- package/dist/types/configFile/loadConfigurationFile.d.ts.map +1 -1
- package/dist/types/configFile/searchConfigurationFile.d.ts +1 -1
- package/dist/types/configFile/searchConfigurationFile.d.ts.map +1 -1
- package/dist/types/defaultValues/analytics.d.ts +11 -0
- package/dist/types/defaultValues/analytics.d.ts.map +1 -0
- package/dist/types/defaultValues/build.d.ts.map +1 -1
- package/dist/types/defaultValues/compiler.d.ts.map +1 -1
- package/dist/types/defaultValues/content.d.ts.map +1 -1
- package/dist/types/defaultValues/dictionary.d.ts +0 -1
- package/dist/types/defaultValues/dictionary.d.ts.map +1 -1
- package/dist/types/defaultValues/editor.d.ts.map +1 -1
- package/dist/types/defaultValues/index.d.ts +2 -1
- package/dist/types/defaultValues/internationalization.d.ts +0 -1
- package/dist/types/defaultValues/internationalization.d.ts.map +1 -1
- package/dist/types/defaultValues/log.d.ts.map +1 -1
- package/dist/types/defaultValues/routing.d.ts +0 -1
- package/dist/types/defaultValues/routing.d.ts.map +1 -1
- package/dist/types/defaultValues/system.d.ts.map +1 -1
- package/dist/types/envVars/envVars.d.ts +0 -1
- package/dist/types/envVars/envVars.d.ts.map +1 -1
- package/dist/types/loadEnvFile.d.ts +1 -1
- package/dist/types/loadEnvFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/bundleFile.d.ts +0 -1
- package/dist/types/loadExternalFile/bundleFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/bundleJSFile.d.ts +57 -59
- package/dist/types/loadExternalFile/bundleJSFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/index.d.ts +2 -2
- package/dist/types/loadExternalFile/loadExternalFile.d.ts +0 -1
- package/dist/types/loadExternalFile/loadExternalFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/parseFileContent.d.ts +9 -1
- package/dist/types/loadExternalFile/parseFileContent.d.ts.map +1 -1
- package/dist/types/loadExternalFile/transpileTSToCJS.d.ts +4 -4
- package/dist/types/loadExternalFile/transpileTSToCJS.d.ts.map +1 -1
- package/dist/types/logger.d.ts +2 -3
- package/dist/types/logger.d.ts.map +1 -1
- package/dist/types/node.d.ts +3 -3
- package/dist/types/utils/ESMxCJSHelpers.d.ts.map +1 -1
- package/dist/types/utils/alias.d.ts +1 -6
- package/dist/types/utils/alias.d.ts.map +1 -1
- package/dist/types/utils/builtConfigKeys.d.ts +25 -0
- package/dist/types/utils/builtConfigKeys.d.ts.map +1 -0
- package/dist/types/utils/cacheDisk.d.ts +22 -11
- package/dist/types/utils/cacheDisk.d.ts.map +1 -1
- package/dist/types/utils/cacheMemory.d.ts +3 -3
- package/dist/types/utils/cacheMemory.d.ts.map +1 -1
- package/dist/types/utils/clearModuleCache.d.ts.map +1 -1
- package/dist/types/utils/compareVersions.d.ts +1 -1
- package/dist/types/utils/compareVersions.d.ts.map +1 -1
- package/dist/types/utils/extractErrorMessage.d.ts.map +1 -1
- package/dist/types/utils/getDictionarySelectorUsage.d.ts +0 -1
- package/dist/types/utils/getDictionarySelectorUsage.d.ts.map +1 -1
- package/dist/types/utils/getExtension.d.ts +1 -2
- package/dist/types/utils/getExtension.d.ts.map +1 -1
- package/dist/types/utils/getPackageJsonPath.d.ts.map +1 -1
- package/dist/types/utils/getStorageAttributes.d.ts +0 -1
- package/dist/types/utils/getStorageAttributes.d.ts.map +1 -1
- package/dist/types/utils/getUsedNodeTypes.d.ts +0 -1
- package/dist/types/utils/getUsedNodeTypes.d.ts.map +1 -1
- package/dist/types/utils/index.d.ts +2 -1
- package/dist/types/utils/logStack.d.ts.map +1 -1
- package/dist/types/utils/normalizePath.d.ts.map +1 -1
- package/dist/types/utils/parseFilePathPattern.d.ts +0 -1
- package/dist/types/utils/parseFilePathPattern.d.ts.map +1 -1
- package/dist/types/utils/pathSecurity.d.ts.map +1 -1
- package/dist/types/utils/retryManager.d.ts +8 -9
- package/dist/types/utils/retryManager.d.ts.map +1 -1
- package/dist/types/utils/setIntlayerIdentifier.d.ts.map +1 -1
- package/dist/types/utils/stringFormatter/camelCaseToKebabCase.d.ts.map +1 -1
- package/dist/types/utils/stringFormatter/camelCaseToSentence.d.ts.map +1 -1
- package/dist/types/utils/stringFormatter/kebabCaseToCamelCase.d.ts.map +1 -1
- package/dist/types/utils/stringFormatter/toLowerCamelCase.d.ts.map +1 -1
- package/package.json +11 -7
- package/dist/cjs/built.browser.cjs +0 -46
- package/dist/cjs/built.browser.cjs.map +0 -1
- package/dist/esm/built.browser.mjs +0 -32
- package/dist/esm/built.browser.mjs.map +0 -1
- package/dist/types/built.browser.d.ts +0 -27
- package/dist/types/built.browser.d.ts.map +0 -1
|
@@ -55,7 +55,7 @@ const formatDictionarySelectorEnvVar = (hasDictionarySelector, wrapKey = (key) =
|
|
|
55
55
|
* // { 'process.env.INTLAYER_ROUTING_MODE': '"prefix-no-default"', ... }
|
|
56
56
|
*/
|
|
57
57
|
const getConfigEnvVars = (config, wrapKey = (key) => key, wrapValue = (value) => value) => {
|
|
58
|
-
const { routing, editor } = config;
|
|
58
|
+
const { routing, editor, analytics } = config;
|
|
59
59
|
const envVars = { [wrapKey("INTLAYER_ROUTING_MODE")]: wrapValue(routing.mode) };
|
|
60
60
|
if (routing.enableProxy === false) envVars[wrapKey("INTLAYER_ROUTING_ENABLE_PROXY")] = wrapValue("false");
|
|
61
61
|
if (!routing.rewrite) envVars[wrapKey("INTLAYER_ROUTING_REWRITE_RULES")] = wrapValue("false");
|
|
@@ -65,6 +65,7 @@ const getConfigEnvVars = (config, wrapKey = (key) => key, wrapValue = (value) =>
|
|
|
65
65
|
if (!routing.storage.sessionStorage || routing.storage.sessionStorage.length === 0) envVars[wrapKey("INTLAYER_ROUTING_STORAGE_SESSIONSTORAGE")] = wrapValue("false");
|
|
66
66
|
if (!routing.storage.headers || routing.storage.headers.length === 0) envVars[wrapKey("INTLAYER_ROUTING_STORAGE_HEADERS")] = wrapValue("false");
|
|
67
67
|
if (editor?.enabled === false) envVars[wrapKey("INTLAYER_EDITOR_ENABLED")] = wrapValue("false");
|
|
68
|
+
if (analytics?.enabled !== true || !editor?.clientId) envVars[wrapKey("INTLAYER_ANALYTICS_ENABLED")] = wrapValue("false");
|
|
68
69
|
return envVars;
|
|
69
70
|
};
|
|
70
71
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"envVars.mjs","names":[],"sources":["../../../src/envVars/envVars.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Converts a camelCase node-type string to SCREAMING_SNAKE_CASE so that\n * the generated env-var name matches what the plugin source files check.\n *\n * @example\n * toScreamingSnakeCase('reactNode') // 'REACT_NODE'\n * toScreamingSnakeCase('markdown') // 'MARKDOWN'\n */\nconst toScreamingSnakeCase = (str: string): string =>\n str\n .replace(/([A-Z])/g, '_$1')\n .toUpperCase()\n .replace(/^_/, ''); // strip any leading underscore\n\n/**\n * Converts a list of unused NodeType keys into env-var definitions.\n * Set to `\"false\"` so bundlers can eliminate the corresponding plugin code.\n *\n * @example\n * formatNodeTypeToEnvVar(['enumeration'])\n * // { 'INTLAYER_NODE_TYPE_ENUMERATION': '\"false\"' }\n *\n * formatNodeTypeToEnvVar(['reactNode'], (k) => `process.env.${k}`, (v) => `\"${v}\"`)\n * // { 'process.env.INTLAYER_NODE_TYPE_REACT_NODE': '\"false\"' }\n */\nexport const formatNodeTypeToEnvVar = (\n nodeTypes: string[],\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> =>\n nodeTypes.reduce(\n (acc, nodeType) => {\n acc[wrapKey(`INTLAYER_NODE_TYPE_${toScreamingSnakeCase(nodeType)}`)] =\n wrapValue('false');\n return acc;\n },\n {} as Record<string, string>\n );\n\n/**\n * Returns the env-var definition disabling the dictionary-selector resolution\n * path (collections, variants) when no built dictionary declares\n * a qualifier. Set to `\"false\"` so bundlers can dead-code-eliminate the\n * selector branch in `getIntlayer` / `useIntlayer`.\n *\n * Emits nothing when selectors are used, leaving the runtime default in place.\n *\n * @example\n * formatDictionarySelectorEnvVar(false)\n * // { INTLAYER_DICTIONARY_SELECTOR: '\"false\"' }\n *\n * formatDictionarySelectorEnvVar(true)\n * // {}\n *\n * formatDictionarySelectorEnvVar(false, (k) => `process.env.${k}`, (v) => `\"${v}\"`)\n * // { 'process.env.INTLAYER_DICTIONARY_SELECTOR': '\"false\"' }\n */\nexport const formatDictionarySelectorEnvVar = (\n hasDictionarySelector: boolean,\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> =>\n hasDictionarySelector\n ? {}\n : { [wrapKey('INTLAYER_DICTIONARY_SELECTOR')]: wrapValue('false') };\n\n/**\n * Returns env-var definitions for the full Intlayer config to be injected at\n * build time. Allows bundlers to dead-code-eliminate unused routing modes,\n * rewrite logic, storage mechanisms, and editor code.\n *\n * @example\n * getConfigEnvVars(config)\n * // { INTLAYER_ROUTING_MODE: '\"prefix-no-default\"', INTLAYER_ROUTING_REWRITE_RULES: '\"false\"', ... }\n *\n * getConfigEnvVars(config, true)\n * // { 'process.env.INTLAYER_ROUTING_MODE': '\"prefix-no-default\"', ... }\n */\nexport const getConfigEnvVars = (\n config: IntlayerConfig,\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> => {\n const { routing, editor } = config;\n\n const envVars: Record<string, string> = {\n [wrapKey('INTLAYER_ROUTING_MODE')]: wrapValue(routing.mode),\n };\n\n if (routing.enableProxy === false) {\n envVars[wrapKey('INTLAYER_ROUTING_ENABLE_PROXY')] = wrapValue('false');\n }\n\n if (!routing.rewrite) {\n envVars[wrapKey('INTLAYER_ROUTING_REWRITE_RULES')] = wrapValue('false');\n }\n\n if (!routing.domains || Object.keys(routing.domains).length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_DOMAINS')] = wrapValue('false');\n }\n\n if (!routing.storage.cookies || routing.storage.cookies.length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_COOKIES')] = wrapValue('false');\n }\n\n if (\n !routing.storage.localStorage ||\n routing.storage.localStorage.length === 0\n ) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_LOCALSTORAGE')] =\n wrapValue('false');\n }\n\n if (\n !routing.storage.sessionStorage ||\n routing.storage.sessionStorage.length === 0\n ) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_SESSIONSTORAGE')] =\n wrapValue('false');\n }\n\n if (!routing.storage.headers || routing.storage.headers.length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_HEADERS')] = wrapValue('false');\n }\n\n if (editor?.enabled === false) {\n envVars[wrapKey('INTLAYER_EDITOR_ENABLED')] = wrapValue('false');\n }\n\n return envVars;\n};\n"],"mappings":";;;;;;;;;AAUA,MAAM,wBAAwB,QAC5B,IACG,QAAQ,YAAY,
|
|
1
|
+
{"version":3,"file":"envVars.mjs","names":[],"sources":["../../../src/envVars/envVars.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Converts a camelCase node-type string to SCREAMING_SNAKE_CASE so that\n * the generated env-var name matches what the plugin source files check.\n *\n * @example\n * toScreamingSnakeCase('reactNode') // 'REACT_NODE'\n * toScreamingSnakeCase('markdown') // 'MARKDOWN'\n */\nconst toScreamingSnakeCase = (str: string): string =>\n str\n .replace(/([A-Z])/g, '_$1')\n .toUpperCase()\n .replace(/^_/, ''); // strip any leading underscore\n\n/**\n * Converts a list of unused NodeType keys into env-var definitions.\n * Set to `\"false\"` so bundlers can eliminate the corresponding plugin code.\n *\n * @example\n * formatNodeTypeToEnvVar(['enumeration'])\n * // { 'INTLAYER_NODE_TYPE_ENUMERATION': '\"false\"' }\n *\n * formatNodeTypeToEnvVar(['reactNode'], (k) => `process.env.${k}`, (v) => `\"${v}\"`)\n * // { 'process.env.INTLAYER_NODE_TYPE_REACT_NODE': '\"false\"' }\n */\nexport const formatNodeTypeToEnvVar = (\n nodeTypes: string[],\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> =>\n nodeTypes.reduce(\n (acc, nodeType) => {\n acc[wrapKey(`INTLAYER_NODE_TYPE_${toScreamingSnakeCase(nodeType)}`)] =\n wrapValue('false');\n return acc;\n },\n {} as Record<string, string>\n );\n\n/**\n * Returns the env-var definition disabling the dictionary-selector resolution\n * path (collections, variants) when no built dictionary declares\n * a qualifier. Set to `\"false\"` so bundlers can dead-code-eliminate the\n * selector branch in `getIntlayer` / `useIntlayer`.\n *\n * Emits nothing when selectors are used, leaving the runtime default in place.\n *\n * @example\n * formatDictionarySelectorEnvVar(false)\n * // { INTLAYER_DICTIONARY_SELECTOR: '\"false\"' }\n *\n * formatDictionarySelectorEnvVar(true)\n * // {}\n *\n * formatDictionarySelectorEnvVar(false, (k) => `process.env.${k}`, (v) => `\"${v}\"`)\n * // { 'process.env.INTLAYER_DICTIONARY_SELECTOR': '\"false\"' }\n */\nexport const formatDictionarySelectorEnvVar = (\n hasDictionarySelector: boolean,\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> =>\n hasDictionarySelector\n ? {}\n : { [wrapKey('INTLAYER_DICTIONARY_SELECTOR')]: wrapValue('false') };\n\n/**\n * Returns env-var definitions for the full Intlayer config to be injected at\n * build time. Allows bundlers to dead-code-eliminate unused routing modes,\n * rewrite logic, storage mechanisms, and editor code.\n *\n * @example\n * getConfigEnvVars(config)\n * // { INTLAYER_ROUTING_MODE: '\"prefix-no-default\"', INTLAYER_ROUTING_REWRITE_RULES: '\"false\"', ... }\n *\n * getConfigEnvVars(config, true)\n * // { 'process.env.INTLAYER_ROUTING_MODE': '\"prefix-no-default\"', ... }\n */\nexport const getConfigEnvVars = (\n config: IntlayerConfig,\n wrapKey = (key: string) => key,\n wrapValue = (value: string) => value\n): Record<string, string> => {\n const { routing, editor, analytics } = config;\n\n const envVars: Record<string, string> = {\n [wrapKey('INTLAYER_ROUTING_MODE')]: wrapValue(routing.mode),\n };\n\n if (routing.enableProxy === false) {\n envVars[wrapKey('INTLAYER_ROUTING_ENABLE_PROXY')] = wrapValue('false');\n }\n\n if (!routing.rewrite) {\n envVars[wrapKey('INTLAYER_ROUTING_REWRITE_RULES')] = wrapValue('false');\n }\n\n if (!routing.domains || Object.keys(routing.domains).length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_DOMAINS')] = wrapValue('false');\n }\n\n if (!routing.storage.cookies || routing.storage.cookies.length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_COOKIES')] = wrapValue('false');\n }\n\n if (\n !routing.storage.localStorage ||\n routing.storage.localStorage.length === 0\n ) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_LOCALSTORAGE')] =\n wrapValue('false');\n }\n\n if (\n !routing.storage.sessionStorage ||\n routing.storage.sessionStorage.length === 0\n ) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_SESSIONSTORAGE')] =\n wrapValue('false');\n }\n\n if (!routing.storage.headers || routing.storage.headers.length === 0) {\n envVars[wrapKey('INTLAYER_ROUTING_STORAGE_HEADERS')] = wrapValue('false');\n }\n\n if (editor?.enabled === false) {\n envVars[wrapKey('INTLAYER_EDITOR_ENABLED')] = wrapValue('false');\n }\n\n // Analytics is strictly opt-in (`analytics.enabled === true`) and requires a\n // project key (`editor.clientId`) for attribution. Otherwise, disable it so\n // bundlers dead-code-eliminate the whole `@intlayer/analytics` integration\n // (providers + node plugins).\n if (analytics?.enabled !== true || !editor?.clientId) {\n envVars[wrapKey('INTLAYER_ANALYTICS_ENABLED')] = wrapValue('false');\n }\n\n return envVars;\n};\n"],"mappings":";;;;;;;;;AAUA,MAAM,wBAAwB,QAC5B,IACG,QAAQ,YAAY,KAAK,CAAC,CAC1B,YAAY,CAAC,CACb,QAAQ,MAAM,EAAE;;;;;;;;;;;;AAarB,MAAa,0BACX,WACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UAE/B,UAAU,QACP,KAAK,aAAa;CACjB,IAAI,QAAQ,sBAAsB,qBAAqB,QAAQ,GAAG,KAChE,UAAU,OAAO;CACnB,OAAO;AACT,GACA,CAAC,CACH;;;;;;;;;;;;;;;;;;;AAoBF,MAAa,kCACX,uBACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UAE/B,wBACI,CAAC,IACD,GAAG,QAAQ,8BAA8B,IAAI,UAAU,OAAO,EAAE;;;;;;;;;;;;;AActE,MAAa,oBACX,QACA,WAAW,QAAgB,KAC3B,aAAa,UAAkB,UACJ;CAC3B,MAAM,EAAE,SAAS,QAAQ,cAAc;CAEvC,MAAM,UAAkC,GACrC,QAAQ,uBAAuB,IAAI,UAAU,QAAQ,IAAI,EAC5D;CAEA,IAAI,QAAQ,gBAAgB,OAC1B,QAAQ,QAAQ,+BAA+B,KAAK,UAAU,OAAO;CAGvE,IAAI,CAAC,QAAQ,SACX,QAAQ,QAAQ,gCAAgC,KAAK,UAAU,OAAO;CAGxE,IAAI,CAAC,QAAQ,WAAW,OAAO,KAAK,QAAQ,OAAO,CAAC,CAAC,WAAW,GAC9D,QAAQ,QAAQ,0BAA0B,KAAK,UAAU,OAAO;CAGlE,IAAI,CAAC,QAAQ,QAAQ,WAAW,QAAQ,QAAQ,QAAQ,WAAW,GACjE,QAAQ,QAAQ,kCAAkC,KAAK,UAAU,OAAO;CAG1E,IACE,CAAC,QAAQ,QAAQ,gBACjB,QAAQ,QAAQ,aAAa,WAAW,GAExC,QAAQ,QAAQ,uCAAuC,KACrD,UAAU,OAAO;CAGrB,IACE,CAAC,QAAQ,QAAQ,kBACjB,QAAQ,QAAQ,eAAe,WAAW,GAE1C,QAAQ,QAAQ,yCAAyC,KACvD,UAAU,OAAO;CAGrB,IAAI,CAAC,QAAQ,QAAQ,WAAW,QAAQ,QAAQ,QAAQ,WAAW,GACjE,QAAQ,QAAQ,kCAAkC,KAAK,UAAU,OAAO;CAG1E,IAAI,QAAQ,YAAY,OACtB,QAAQ,QAAQ,yBAAyB,KAAK,UAAU,OAAO;CAOjE,IAAI,WAAW,YAAY,QAAQ,CAAC,QAAQ,UAC1C,QAAQ,QAAQ,4BAA4B,KAAK,UAAU,OAAO;CAGpE,OAAO;AACT"}
|
package/dist/esm/loadEnvFile.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync } from "node:fs";
|
|
1
|
+
import { existsSync, statSync } from "node:fs";
|
|
2
2
|
import dotenv from "dotenv";
|
|
3
3
|
|
|
4
4
|
//#region src/loadEnvFile.ts
|
|
@@ -11,16 +11,53 @@ const getEnvFilePath = (env = "development", envFile) => {
|
|
|
11
11
|
".env"
|
|
12
12
|
]).find(existsSync);
|
|
13
13
|
};
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Cache of parsed env files keyed by `cwd|env|envFile`. Loading content
|
|
16
|
+
* declarations calls `loadEnvFile` once per file; without this every call pays
|
|
17
|
+
* up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is
|
|
18
|
+
* validated with a single `stat` so edits to the env file are still picked up.
|
|
19
|
+
*/
|
|
20
|
+
const envFileCache = /* @__PURE__ */ new Map();
|
|
21
|
+
const parseEnvFile = (envFilePath) => {
|
|
22
|
+
const parsedEnv = {};
|
|
18
23
|
dotenv.config({
|
|
19
|
-
path:
|
|
20
|
-
processEnv:
|
|
24
|
+
path: envFilePath,
|
|
25
|
+
processEnv: parsedEnv,
|
|
21
26
|
quiet: true
|
|
22
27
|
});
|
|
23
|
-
return
|
|
28
|
+
return parsedEnv;
|
|
29
|
+
};
|
|
30
|
+
const loadEnvFile = (options) => {
|
|
31
|
+
const env = options?.env ?? DEFAULT_ENV;
|
|
32
|
+
const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ""}`;
|
|
33
|
+
const cachedEntry = envFileCache.get(cacheKey);
|
|
34
|
+
if (cachedEntry) if (cachedEntry.envFilePath === void 0) {
|
|
35
|
+
if (!getEnvFilePath(env, options?.envFile)) return cachedEntry.parsedEnv;
|
|
36
|
+
} else try {
|
|
37
|
+
const stats = statSync(cachedEntry.envFilePath);
|
|
38
|
+
if (stats.mtimeMs === cachedEntry.mtimeMs && stats.size === cachedEntry.size) return cachedEntry.parsedEnv;
|
|
39
|
+
} catch {}
|
|
40
|
+
const envFilePath = getEnvFilePath(env, options?.envFile);
|
|
41
|
+
if (!envFilePath) {
|
|
42
|
+
envFileCache.set(cacheKey, {
|
|
43
|
+
envFilePath: void 0,
|
|
44
|
+
mtimeMs: 0,
|
|
45
|
+
size: 0,
|
|
46
|
+
parsedEnv: {}
|
|
47
|
+
});
|
|
48
|
+
return {};
|
|
49
|
+
}
|
|
50
|
+
const parsedEnv = parseEnvFile(envFilePath);
|
|
51
|
+
try {
|
|
52
|
+
const stats = statSync(envFilePath);
|
|
53
|
+
envFileCache.set(cacheKey, {
|
|
54
|
+
envFilePath,
|
|
55
|
+
mtimeMs: stats.mtimeMs,
|
|
56
|
+
size: stats.size,
|
|
57
|
+
parsedEnv
|
|
58
|
+
});
|
|
59
|
+
} catch {}
|
|
60
|
+
return parsedEnv;
|
|
24
61
|
};
|
|
25
62
|
|
|
26
63
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadEnvFile.mjs","names":[],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\nexport const loadEnvFile = (options?: Partial<LoadEnvFileOptions
|
|
1
|
+
{"version":3,"file":"loadEnvFile.mjs","names":[],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\ntype EnvFileCacheEntry = {\n /** The env file that was resolved and parsed (undefined if none exists). */\n envFilePath: string | undefined;\n /** Fingerprint of the parsed file, used to detect edits. */\n mtimeMs: number;\n size: number;\n /** The parsed env variables. */\n parsedEnv: Record<string, string>;\n};\n\n/**\n * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content\n * declarations calls `loadEnvFile` once per file; without this every call pays\n * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is\n * validated with a single `stat` so edits to the env file are still picked up.\n */\nconst envFileCache = new Map<string, EnvFileCacheEntry>();\n\nconst parseEnvFile = (envFilePath: string): Record<string, string> => {\n const parsedEnv: Record<string, string> = {};\n\n dotenv.config({\n path: envFilePath,\n processEnv: parsedEnv,\n quiet: true,\n });\n\n return parsedEnv;\n};\n\nexport const loadEnvFile = (\n options?: Partial<LoadEnvFileOptions>\n): Record<string, string> => {\n const env = options?.env ?? DEFAULT_ENV;\n\n // Env file candidates are resolved relative to the working directory\n const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ''}`;\n\n const cachedEntry = envFileCache.get(cacheKey);\n\n if (cachedEntry) {\n if (cachedEntry.envFilePath === undefined) {\n // No env file existed. Re-probe cheaply in case one was created since.\n const envFilePath = getEnvFilePath(env, options?.envFile);\n if (!envFilePath) return cachedEntry.parsedEnv;\n } else {\n try {\n const stats = statSync(cachedEntry.envFilePath);\n if (\n stats.mtimeMs === cachedEntry.mtimeMs &&\n stats.size === cachedEntry.size\n ) {\n return cachedEntry.parsedEnv;\n }\n } catch {\n // File was removed — fall through and re-resolve\n }\n }\n }\n\n const envFilePath = getEnvFilePath(env, options?.envFile);\n\n if (!envFilePath) {\n envFileCache.set(cacheKey, {\n envFilePath: undefined,\n mtimeMs: 0,\n size: 0,\n parsedEnv: {},\n });\n return {};\n }\n\n const parsedEnv = parseEnvFile(envFilePath);\n\n try {\n const stats = statSync(envFilePath);\n envFileCache.set(cacheKey, {\n envFilePath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n parsedEnv,\n });\n } catch {\n // Race: file removed between parse and stat — skip caching this round\n }\n\n return parsedEnv; // Return the parsed env object\n};\n"],"mappings":";;;;AAGA,MAAM;AAON,MAAa,kBACX,qBACA,YACuB;CAKvB,QAJiB,UACb,CAAC,OAAO,IACR;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;CAAM,EAE9C,CAAC,KAAK,UAAU;AACjC;;;;;;;AAkBA,MAAM,+BAAe,IAAI,IAA+B;AAExD,MAAM,gBAAgB,gBAAgD;CACpE,MAAM,YAAoC,CAAC;CAE3C,OAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;CACT,CAAC;CAED,OAAO;AACT;AAEA,MAAa,eACX,YAC2B;CAC3B,MAAM,MAAM,SAAS,OAAO;CAG5B,MAAM,WAAW,GAAG,QAAQ,IAAI,EAAE,GAAG,IAAI,GAAG,SAAS,WAAW;CAEhE,MAAM,cAAc,aAAa,IAAI,QAAQ;CAE7C,IAAI,aACF,IAAI,YAAY,gBAAgB,QAG9B;MAAI,CADgB,eAAe,KAAK,SAAS,OAClC,GAAG,OAAO,YAAY;CAAS,OAE9C,IAAI;EACF,MAAM,QAAQ,SAAS,YAAY,WAAW;EAC9C,IACE,MAAM,YAAY,YAAY,WAC9B,MAAM,SAAS,YAAY,MAE3B,OAAO,YAAY;CAEvB,QAAQ,CAER;CAIJ,MAAM,cAAc,eAAe,KAAK,SAAS,OAAO;CAExD,IAAI,CAAC,aAAa;EAChB,aAAa,IAAI,UAAU;GACzB,aAAa;GACb,SAAS;GACT,MAAM;GACN,WAAW,CAAC;EACd,CAAC;EACD,OAAO,CAAC;CACV;CAEA,MAAM,YAAY,aAAa,WAAW;CAE1C,IAAI;EACF,MAAM,QAAQ,SAAS,WAAW;EAClC,aAAa,IAAI,UAAU;GACzB;GACA,SAAS,MAAM;GACf,MAAM,MAAM;GACZ;EACF,CAAC;CACH,QAAQ,CAER;CAEA,OAAO;AACT"}
|
|
@@ -39,10 +39,11 @@ const getTransformationOptions = (filePath) => ({
|
|
|
39
39
|
define: { "import.meta.url": JSON.stringify(pathToFileURL(filePath).href) }
|
|
40
40
|
});
|
|
41
41
|
const bundleFileSync = (code, filePath, options) => {
|
|
42
|
+
const extension = extname(filePath);
|
|
42
43
|
return buildSync({
|
|
43
44
|
stdin: {
|
|
44
45
|
contents: code,
|
|
45
|
-
loader: getLoader(
|
|
46
|
+
loader: getLoader(extension),
|
|
46
47
|
resolveDir: dirname(filePath),
|
|
47
48
|
sourcefile: filePath
|
|
48
49
|
},
|
|
@@ -51,10 +52,11 @@ const bundleFileSync = (code, filePath, options) => {
|
|
|
51
52
|
}).outputFiles?.[0].text;
|
|
52
53
|
};
|
|
53
54
|
const bundleFile = async (code, filePath, options) => {
|
|
55
|
+
const extension = extname(filePath);
|
|
54
56
|
return (await build({
|
|
55
57
|
stdin: {
|
|
56
58
|
contents: code,
|
|
57
|
-
loader: getLoader(
|
|
59
|
+
loader: getLoader(extension),
|
|
58
60
|
resolveDir: dirname(filePath),
|
|
59
61
|
sourcefile: filePath
|
|
60
62
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleFile.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Loader,\n type Plugin,\n} from 'esbuild';\n\nexport type ESBuildPlugin = Plugin;\n\nexport const getLoader = (extension: string): Loader => {\n switch (extension) {\n case '.js':\n return 'js';\n case '.jsx':\n return 'jsx';\n case '.mjs':\n return 'js';\n case '.ts':\n return 'ts';\n case '.tsx':\n return 'tsx';\n case '.cjs':\n return 'js';\n case '.json':\n return 'json';\n case '.md':\n return 'text';\n case '.mdx':\n return 'text';\n default:\n return 'js';\n }\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node16',\n platform: 'neutral',\n write: false,\n packages: 'bundle',\n external: ['esbuild'],\n bundle: true,\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const bundleFileSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const bundleFile = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":";;;;;AAaA,MAAa,aAAa,cAA8B;
|
|
1
|
+
{"version":3,"file":"bundleFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleFile.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Loader,\n type Plugin,\n} from 'esbuild';\n\nexport type ESBuildPlugin = Plugin;\n\nexport const getLoader = (extension: string): Loader => {\n switch (extension) {\n case '.js':\n return 'js';\n case '.jsx':\n return 'jsx';\n case '.mjs':\n return 'js';\n case '.ts':\n return 'ts';\n case '.tsx':\n return 'tsx';\n case '.cjs':\n return 'js';\n case '.json':\n return 'json';\n case '.md':\n return 'text';\n case '.mdx':\n return 'text';\n default:\n return 'js';\n }\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node16',\n platform: 'neutral',\n write: false,\n packages: 'bundle',\n external: ['esbuild'],\n bundle: true,\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const bundleFileSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const bundleFile = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":";;;;;AAaA,MAAa,aAAa,cAA8B;CACtD,QAAQ,WAAR;EACE,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;CACA,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,UAAU,CAAC,SAAS;CACpB,QAAQ;CACR,QAAQ,EACN,mBAAmB,KAAK,UAAU,cAAc,QAAQ,CAAC,CAAC,IAAI,EAChE;AACF;AAEA,MAAa,kBACX,MACA,UACA,YACuB;CACvB,MAAM,YAAY,QAAQ,QAAQ;CAgBlC,OAbkC,UAAU;EAC1C,OAAO;GACL,UAAU;GACV,QALW,UAAU,SAKhB;GACL,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAEsC,CAAC,CAAC,cAAc,EAAE,CAAC;AAG3D;AAEA,MAAa,aAAa,OACxB,MACA,UACA,YACgC;CAChC,MAAM,YAAY,QAAQ,QAAQ;CAgBlC,QAF2B,MAXa,MAAM;EAC5C,OAAO;GACL,UAAU;GACV,QALW,UAAU,SAKhB;GACL,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC,EAEsC,CAAC,cAAc,EAAE,CAAC;AAG3D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleJSFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleJSFile.ts"],"sourcesContent":["import { type BuildOptions, build } from 'esbuild';\n\nconst commonBuildOptions = {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n target: 'es2019',\n sourcemap: false,\n logLevel: 'silent',\n write: true,\n // Bundle relative/local files, but keep bare module imports external\n packages: 'external',\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n} as const;\n\nexport const bundleJSFile = async (buildOptions: BuildOptions) =>\n await build({\n ...commonBuildOptions,\n ...buildOptions,\n });\n"],"mappings":";;;AAEA,MAAM,qBAAqB;CACzB,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,WAAW;CACX,UAAU;CACV,OAAO;CAEP,UAAU;CACV,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;
|
|
1
|
+
{"version":3,"file":"bundleJSFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleJSFile.ts"],"sourcesContent":["import { type BuildOptions, build } from 'esbuild';\n\nconst commonBuildOptions = {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n target: 'es2019',\n sourcemap: false,\n logLevel: 'silent',\n write: true,\n // Bundle relative/local files, but keep bare module imports external\n packages: 'external',\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n} as const;\n\nexport const bundleJSFile = async (buildOptions: BuildOptions) =>\n await build({\n ...commonBuildOptions,\n ...buildOptions,\n });\n"],"mappings":";;;AAEA,MAAM,qBAAqB;CACzB,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,WAAW;CACX,UAAU;CACV,OAAO;CAEP,UAAU;CACV,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;AACF;AAEA,MAAa,eAAe,OAAO,iBACjC,MAAM,MAAM;CACV,GAAG;CACH,GAAG;AACL,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getSandBoxContext, parseFileContent } from "./parseFileContent.mjs";
|
|
2
2
|
import { bundleFile, bundleFileSync, getLoader } from "./bundleFile.mjs";
|
|
3
|
-
import { transpileTSToCJS, transpileTSToCJSSync } from "./transpileTSToCJS.mjs";
|
|
3
|
+
import { clearTranspileCache, transpileTSToCJS, transpileTSToCJSSync } from "./transpileTSToCJS.mjs";
|
|
4
4
|
import { loadExternalFile, loadExternalFileSync } from "./loadExternalFile.mjs";
|
|
5
5
|
import { bundleJSFile } from "./bundleJSFile.mjs";
|
|
6
6
|
|
|
7
|
-
export { bundleFile, bundleFileSync, bundleJSFile, getLoader, getSandBoxContext, loadExternalFile, loadExternalFileSync, parseFileContent, transpileTSToCJS, transpileTSToCJSSync };
|
|
7
|
+
export { bundleFile, bundleFileSync, bundleJSFile, clearTranspileCache, getLoader, getSandBoxContext, loadExternalFile, loadExternalFileSync, parseFileContent, transpileTSToCJS, transpileTSToCJSSync };
|
|
@@ -22,13 +22,13 @@ const loadExternalFileSync = (filePath, options) => {
|
|
|
22
22
|
logger("File could not be loaded.", { level: "error" });
|
|
23
23
|
return;
|
|
24
24
|
}
|
|
25
|
-
const fileContent = parseFileContent(moduleResultString, {
|
|
25
|
+
const fileContent = withPreloadedGlobals(options?.preloadGlobals, () => parseFileContent(moduleResultString, {
|
|
26
26
|
projectRequire: options?.projectRequire,
|
|
27
27
|
envVarOptions: options?.envVarOptions,
|
|
28
28
|
additionalEnvVars: options?.additionalEnvVars,
|
|
29
29
|
mocks: options?.mocks,
|
|
30
30
|
aliases: options?.aliases
|
|
31
|
-
});
|
|
31
|
+
}));
|
|
32
32
|
if (typeof fileContent === "undefined") {
|
|
33
33
|
logger(`File could not be loaded. Path : ${filePath}`);
|
|
34
34
|
return;
|
|
@@ -41,15 +41,17 @@ const loadExternalFileSync = (filePath, options) => {
|
|
|
41
41
|
const withPreloadedGlobals = (globals, fn) => {
|
|
42
42
|
if (!globals) return fn();
|
|
43
43
|
const globalVars = globalThis;
|
|
44
|
-
const
|
|
44
|
+
const previousValues = {};
|
|
45
|
+
const previouslyPresent = {};
|
|
45
46
|
for (const [key, value] of Object.entries(globals)) {
|
|
46
|
-
|
|
47
|
+
previouslyPresent[key] = key in globalVars;
|
|
48
|
+
previousValues[key] = globalVars[key];
|
|
47
49
|
globalVars[key] = value;
|
|
48
50
|
}
|
|
49
51
|
try {
|
|
50
52
|
return fn();
|
|
51
53
|
} finally {
|
|
52
|
-
for (const key of Object.keys(globals)) if (
|
|
54
|
+
for (const key of Object.keys(globals)) if (previouslyPresent[key]) globalVars[key] = previousValues[key];
|
|
53
55
|
else delete globalVars[key];
|
|
54
56
|
}
|
|
55
57
|
};
|
|
@@ -61,7 +63,10 @@ const withPreloadedGlobals = (globals, fn) => {
|
|
|
61
63
|
const loadExternalFile = async (filePath, options) => {
|
|
62
64
|
const fileExtension = extname(filePath);
|
|
63
65
|
try {
|
|
64
|
-
if (fileExtension === ".json" || fileExtension === ".json5" || fileExtension === ".jsonc")
|
|
66
|
+
if (fileExtension === ".json" || fileExtension === ".json5" || fileExtension === ".jsonc") {
|
|
67
|
+
const fileContent = await readFile(filePath, "utf-8");
|
|
68
|
+
return parseJSON5(fileContent);
|
|
69
|
+
}
|
|
65
70
|
const moduleResultString = await transpileTSToCJS(await readFile(filePath, "utf-8"), filePath, options?.buildOptions);
|
|
66
71
|
if (!moduleResultString) {
|
|
67
72
|
logger("File could not be loaded.", { level: "error" });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadExternalFile.mjs","names":[],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n const fileContent = parseFileContent(moduleResultString, {\n
|
|
1
|
+
{"version":3,"file":"loadExternalFile.mjs","names":[],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // fully restores the globals before returning.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const previousValues: Record<string, unknown> = {};\n const previouslyPresent: Record<string, boolean> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n previouslyPresent[key] = key in globalVars;\n previousValues[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n // `in` check (not `!== undefined`) so a global that legitimately held\n // `undefined` is restored rather than deleted.\n if (previouslyPresent[key]) {\n globalVars[key] = previousValues[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAiBA,MAAM,aAAa,MAAM,SAAU,MAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,gBAAgB,QAAQ,QAAQ,KAAK;CAE3C,IAAI;EACF,IACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,UAGlB,OAAO,WAAW,aAAa,UAAU,OAAO,CAAC;EAMnD,MAAM,qBAAyC,qBAFlC,aAAa,UAAU,OAG/B,GACH,UACA,SAAS,YACX;EAEA,IAAI,CAAC,oBAAoB;GACvB,OAAO,6BAA6B,EAAE,OAAO,QAAQ,CAAC;GACtD;EACF;EAIA,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;EACpB,CAAC,CACH;EAEA,IAAI,OAAO,gBAAgB,aAAa;GACtC,OAAO,oCAAoC,UAAU;GACrD;EACF;EAEA,OAAO;CACT,SAAS,OAAO;EACd,OACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,CAAC,CAChD,GACA,EACE,OAAO,QACT,CACF;CACF;AACF;AAEA,MAAM,wBACJ,SACA,OACM;CACN,IAAI,CAAC,SAAS,OAAO,GAAG;CAExB,MAAM,aAAa;CACnB,MAAM,iBAA0C,CAAC;CACjD,MAAM,oBAA6C,CAAC;CAEpD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAAG;EAClD,kBAAkB,OAAO,OAAO;EAChC,eAAe,OAAO,WAAW;EACjC,WAAW,OAAO;CACpB;CAEA,IAAI;EACF,OAAO,GAAG;CACZ,UAAU;EACR,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,GAGnC,IAAI,kBAAkB,MACpB,WAAW,OAAO,eAAe;OAEjC,OAAO,WAAW;CAGxB;AACF;;;;;;AAOA,MAAa,mBAAmB,OAC9B,UACA,YAC6B;CAC7B,MAAM,gBAAgB,QAAQ,QAAQ;CAEtC,IAAI;EACF,IACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,UAClB;GAEA,MAAM,cAAc,MAAM,SAAS,UAAU,OAAO;GACpD,OAAO,WAAW,WAAW;EAC/B;EAKA,MAAM,qBAAyC,MAAM,iBACnD,MAHiB,SAAS,UAAU,OAAO,GAI3C,UACA,SAAS,YACX;EAEA,IAAI,CAAC,oBAAoB;GACvB,OAAO,6BAA6B,EAAE,OAAO,QAAQ,CAAC;GACtD;EACF;EAIA,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;EACpB,CAAC,CACH;EAEA,IAAI,OAAO,gBAAgB,aAAa;GACtC,OAAO,oCAAoC,aAAa,QAAQ,GAAG;GACnE;EACF;EAEA,OAAO;CACT,SAAS,OAAO;EACd,IAAI,SAAS,YAAY,MACvB,OACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,CAAC,CAChD,GACA,EACE,OAAO,QACT,CACF;CAEJ;AACF"}
|
|
@@ -24,9 +24,58 @@ const NODE_GLOBALS = [
|
|
|
24
24
|
"crypto",
|
|
25
25
|
"structuredClone"
|
|
26
26
|
];
|
|
27
|
+
/**
|
|
28
|
+
* Cache of the project's React module (or the JSX-capturing fallback) keyed by
|
|
29
|
+
* the require's resolution paths. Node does not cache *failed* resolutions, so
|
|
30
|
+
* without this every sandbox creation in a non-React project (Vue, Svelte,
|
|
31
|
+
* Angular…) pays a full node_modules walk that ends in a throw.
|
|
32
|
+
*/
|
|
33
|
+
const reactModuleCache = /* @__PURE__ */ new Map();
|
|
34
|
+
/**
|
|
35
|
+
* Fallback React implementation used when React is not installed in the
|
|
36
|
+
* project. It captures JSX elements as plain objects so JSX can be used in
|
|
37
|
+
* content declarations (esbuild's tsx loader defaults to React.createElement).
|
|
38
|
+
*/
|
|
39
|
+
const createFallbackReact = () => ({
|
|
40
|
+
createElement: (type, props, ...children) => ({
|
|
41
|
+
type,
|
|
42
|
+
props: {
|
|
43
|
+
...props,
|
|
44
|
+
children: children.length <= 1 ? children[0] : children
|
|
45
|
+
}
|
|
46
|
+
}),
|
|
47
|
+
Fragment: Symbol.for("react.fragment")
|
|
48
|
+
});
|
|
49
|
+
const getReactGlobal = (baseRequire) => {
|
|
50
|
+
const resolutionKey = baseRequire.resolve.paths?.("react")?.join("|") ?? "<default>";
|
|
51
|
+
const cachedReactModule = reactModuleCache.get(resolutionKey);
|
|
52
|
+
if (cachedReactModule) return cachedReactModule;
|
|
53
|
+
let reactGlobal;
|
|
54
|
+
try {
|
|
55
|
+
reactGlobal = { React: baseRequire("react") };
|
|
56
|
+
} catch (_err) {
|
|
57
|
+
reactGlobal = { React: createFallbackReact() };
|
|
58
|
+
}
|
|
59
|
+
reactModuleCache.set(resolutionKey, reactGlobal);
|
|
60
|
+
return reactGlobal;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Snapshot of the non-env `process` properties, taken once at module load.
|
|
64
|
+
* Spreading `process` enumerates ~100 properties (some behind getters); doing
|
|
65
|
+
* it per sandbox is wasteful since everything except `env` is static.
|
|
66
|
+
*/
|
|
67
|
+
const processSnapshot = { ...process };
|
|
68
|
+
/**
|
|
69
|
+
* Builds the global context handed to `runInNewContext`.
|
|
70
|
+
*
|
|
71
|
+
* SECURITY NOTE: this sandbox exists for global-scope hygiene (fresh
|
|
72
|
+
* module/exports, controlled env), NOT for containment. It exposes the real
|
|
73
|
+
* project `require`, a copy of `process`, and `fetch` — code executed here has
|
|
74
|
+
* full host privileges. Only ever run trusted, build-time project files
|
|
75
|
+
* (same trust model as `vite.config.ts`).
|
|
76
|
+
*/
|
|
27
77
|
const getSandBoxContext = (options) => {
|
|
28
78
|
const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } = options ?? {};
|
|
29
|
-
let additionalGlobalVar = {};
|
|
30
79
|
const baseRequire = typeof projectRequire === "function" ? projectRequire : getProjectRequire();
|
|
31
80
|
const mockedRequire = (() => {
|
|
32
81
|
const mockTable = Object.assign({ esbuild }, mocks);
|
|
@@ -43,25 +92,11 @@ const getSandBoxContext = (options) => {
|
|
|
43
92
|
wrappedRequire.cache = baseRequire.cache;
|
|
44
93
|
return wrappedRequire;
|
|
45
94
|
})();
|
|
46
|
-
try {
|
|
47
|
-
additionalGlobalVar = { React: baseRequire("react") };
|
|
48
|
-
} catch (_err) {
|
|
49
|
-
additionalGlobalVar = { React: {
|
|
50
|
-
createElement: (type, props, ...children) => ({
|
|
51
|
-
type,
|
|
52
|
-
props: {
|
|
53
|
-
...props,
|
|
54
|
-
children: children.length <= 1 ? children[0] : children
|
|
55
|
-
}
|
|
56
|
-
}),
|
|
57
|
-
Fragment: Symbol.for("react.fragment")
|
|
58
|
-
} };
|
|
59
|
-
}
|
|
60
95
|
const sandboxContext = {
|
|
61
96
|
exports: { default: {} },
|
|
62
97
|
module: { exports: {} },
|
|
63
98
|
process: {
|
|
64
|
-
...
|
|
99
|
+
...processSnapshot,
|
|
65
100
|
env: {
|
|
66
101
|
...process.env,
|
|
67
102
|
...loadEnvFile(envVarOptions),
|
|
@@ -70,7 +105,7 @@ const getSandBoxContext = (options) => {
|
|
|
70
105
|
},
|
|
71
106
|
console,
|
|
72
107
|
require: mockedRequire,
|
|
73
|
-
...
|
|
108
|
+
...getReactGlobal(baseRequire)
|
|
74
109
|
};
|
|
75
110
|
for (const key of NODE_GLOBALS) if (!(key in sandboxContext) && key in globalThis) sandboxContext[key] = globalThis[key];
|
|
76
111
|
return sandboxContext;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parseFileContent.mjs","names":[],"sources":["../../../src/loadExternalFile/parseFileContent.ts"],"sourcesContent":["import { type Context, runInNewContext } from 'node:vm';\nimport * as esbuild from 'esbuild';\nimport { type LoadEnvFileOptions, loadEnvFile } from '../loadEnvFile';\nimport { getProjectRequire } from '../utils/ESMxCJSHelpers';\n\nexport type SandBoxContextOptions = {\n envVarOptions?: LoadEnvFileOptions;\n projectRequire?: NodeJS.Require;\n additionalEnvVars?: Record<string, string>;\n /**\n * Map of specifier -> mocked export to be returned when code in the VM calls require(specifier).\n * Example:\n * mocks: {\n * '@intlayer/config/built': { getConfig: () => ({}), Locales: {} }\n * }\n */\n mocks?: Record<string, any>;\n /**\n * Optional alias map if you want to redirect specifiers.\n * Useful when user code imports a subpath you want to collapse.\n * Example:\n * aliases: { '@intlayer/config/built': '@intlayer/config' }\n */\n aliases?: Record<string, string>;\n};\n\n// Inject only Node.js-specific globals that are absent from a plain V8 context.\n// JS built-ins (Object, Array, Promise, Math, Date, JSON, Symbol, etc.) are\n// provided automatically by runInNewContext — no need to copy them.\n// Copying all of globalThis would retain hundreds of references (including the\n// full module cache via `global`) inside every sandbox, causing a memory leak.\nconst NODE_GLOBALS = [\n 'Buffer',\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'setImmediate',\n 'clearImmediate',\n 'queueMicrotask',\n 'URL',\n 'URLSearchParams',\n 'TextEncoder',\n 'TextDecoder',\n 'AbortController',\n 'AbortSignal',\n 'performance',\n 'fetch',\n 'crypto',\n 'structuredClone',\n] as const;\n\nexport const getSandBoxContext = (options?: SandBoxContextOptions): Context => {\n const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } =\n options ?? {};\n\n
|
|
1
|
+
{"version":3,"file":"parseFileContent.mjs","names":[],"sources":["../../../src/loadExternalFile/parseFileContent.ts"],"sourcesContent":["import { type Context, runInNewContext } from 'node:vm';\nimport * as esbuild from 'esbuild';\nimport { type LoadEnvFileOptions, loadEnvFile } from '../loadEnvFile';\nimport { getProjectRequire } from '../utils/ESMxCJSHelpers';\n\nexport type SandBoxContextOptions = {\n envVarOptions?: LoadEnvFileOptions;\n projectRequire?: NodeJS.Require;\n additionalEnvVars?: Record<string, string>;\n /**\n * Map of specifier -> mocked export to be returned when code in the VM calls require(specifier).\n * Example:\n * mocks: {\n * '@intlayer/config/built': { getConfig: () => ({}), Locales: {} }\n * }\n */\n mocks?: Record<string, any>;\n /**\n * Optional alias map if you want to redirect specifiers.\n * Useful when user code imports a subpath you want to collapse.\n * Example:\n * aliases: { '@intlayer/config/built': '@intlayer/config' }\n */\n aliases?: Record<string, string>;\n};\n\n// Inject only Node.js-specific globals that are absent from a plain V8 context.\n// JS built-ins (Object, Array, Promise, Math, Date, JSON, Symbol, etc.) are\n// provided automatically by runInNewContext — no need to copy them.\n// Copying all of globalThis would retain hundreds of references (including the\n// full module cache via `global`) inside every sandbox, causing a memory leak.\nconst NODE_GLOBALS = [\n 'Buffer',\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'setImmediate',\n 'clearImmediate',\n 'queueMicrotask',\n 'URL',\n 'URLSearchParams',\n 'TextEncoder',\n 'TextDecoder',\n 'AbortController',\n 'AbortSignal',\n 'performance',\n 'fetch',\n 'crypto',\n 'structuredClone',\n] as const;\n\n/**\n * Cache of the project's React module (or the JSX-capturing fallback) keyed by\n * the require's resolution paths. Node does not cache *failed* resolutions, so\n * without this every sandbox creation in a non-React project (Vue, Svelte,\n * Angular…) pays a full node_modules walk that ends in a throw.\n */\nconst reactModuleCache = new Map<string, { React: unknown }>();\n\n/**\n * Fallback React implementation used when React is not installed in the\n * project. It captures JSX elements as plain objects so JSX can be used in\n * content declarations (esbuild's tsx loader defaults to React.createElement).\n */\nconst createFallbackReact = () => ({\n createElement: (type: any, props: any, ...children: any[]) => ({\n type,\n props: {\n ...props,\n children: children.length <= 1 ? children[0] : children,\n },\n }),\n Fragment: Symbol.for('react.fragment'),\n});\n\nconst getReactGlobal = (baseRequire: NodeJS.Require): { React: unknown } => {\n // resolve.paths() is computed in-memory (no fs access) and identifies the\n // node_modules chain this require instance resolves against.\n const resolutionKey =\n baseRequire.resolve.paths?.('react')?.join('|') ?? '<default>';\n\n const cachedReactModule = reactModuleCache.get(resolutionKey);\n if (cachedReactModule) return cachedReactModule;\n\n let reactGlobal: { React: unknown };\n try {\n // Dynamically try to require React if it's installed in the project\n reactGlobal = { React: baseRequire('react') };\n } catch (_err) {\n reactGlobal = { React: createFallbackReact() };\n }\n\n reactModuleCache.set(resolutionKey, reactGlobal);\n\n return reactGlobal;\n};\n\n/**\n * Snapshot of the non-env `process` properties, taken once at module load.\n * Spreading `process` enumerates ~100 properties (some behind getters); doing\n * it per sandbox is wasteful since everything except `env` is static.\n */\nconst processSnapshot = { ...process };\n\n/**\n * Builds the global context handed to `runInNewContext`.\n *\n * SECURITY NOTE: this sandbox exists for global-scope hygiene (fresh\n * module/exports, controlled env), NOT for containment. It exposes the real\n * project `require`, a copy of `process`, and `fetch` — code executed here has\n * full host privileges. Only ever run trusted, build-time project files\n * (same trust model as `vite.config.ts`).\n */\nexport const getSandBoxContext = (options?: SandBoxContextOptions): Context => {\n const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } =\n options ?? {};\n\n const baseRequire: NodeJS.Require =\n typeof projectRequire === 'function' ? projectRequire : getProjectRequire();\n\n // Wrap require to honor mocks and aliases inside the VM\n const mockedRequire: NodeJS.Require = (() => {\n const mockTable = Object.assign(\n {\n esbuild,\n },\n mocks\n );\n const aliasTable = Object.assign({}, aliases);\n\n const wrappedRequire = function mockableRequire(id: string) {\n const target = aliasTable?.[id] ? aliasTable[id] : id;\n\n if (mockTable && Object.hasOwn(mockTable, target)) {\n return mockTable[target];\n }\n\n // If the original id was aliased, allow mocks to be defined on either key.\n if (target !== id && mockTable && Object.hasOwn(mockTable, id)) {\n return mockTable[id];\n }\n\n return baseRequire(target);\n } as NodeJS.Require;\n\n // Mirror NodeJS.Require properties\n wrappedRequire.resolve = baseRequire.resolve.bind(baseRequire);\n wrappedRequire.main = baseRequire.main;\n wrappedRequire.extensions = baseRequire.extensions;\n wrappedRequire.cache = baseRequire.cache;\n\n return wrappedRequire;\n })();\n\n const sandboxContext: Context = {\n exports: {\n default: {},\n },\n module: {\n exports: {},\n },\n process: {\n ...processSnapshot,\n env: {\n ...process.env,\n ...loadEnvFile(envVarOptions),\n ...additionalEnvVars,\n },\n },\n console,\n require: mockedRequire,\n ...getReactGlobal(baseRequire),\n };\n\n for (const key of NODE_GLOBALS) {\n if (!(key in sandboxContext) && key in globalThis) {\n (sandboxContext as Record<string, unknown>)[key] =\n globalThis[key as keyof typeof globalThis];\n }\n }\n\n return sandboxContext;\n};\n\nexport const parseFileContent = <T>(\n fileContentString: string,\n options?: SandBoxContextOptions\n): T | undefined => {\n const sandboxContext = getSandBoxContext(options);\n\n // Force strict mode so illegal writes throw instead of silently failing.\n runInNewContext(`\"use strict\";\\n${fileContentString}`, sandboxContext);\n\n const candidates: unknown[] = [\n sandboxContext.exports?.default,\n sandboxContext.module?.exports?.defaults,\n sandboxContext.module?.exports?.default,\n sandboxContext.module?.exports,\n ];\n\n let result: T | undefined;\n for (const candidate of candidates) {\n if (\n candidate &&\n typeof candidate === 'object' &&\n Object.keys(candidate as object).length > 0\n ) {\n result = candidate as T;\n break;\n }\n }\n\n // Drop heavy references so the V8 context created by runInNewContext can be\n // garbage-collected promptly. The extracted `result` is a plain data object\n // and does not retain the sandbox.\n (sandboxContext as Record<string, unknown>).require = undefined;\n (sandboxContext as Record<string, unknown>).process = undefined;\n (sandboxContext as Record<string, unknown>).React = undefined;\n (sandboxContext as Record<string, unknown>).module = undefined;\n (sandboxContext as Record<string, unknown>).exports = undefined;\n\n return result;\n};\n"],"mappings":";;;;;;AA+BA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,mCAAmB,IAAI,IAAgC;;;;;;AAO7D,MAAM,6BAA6B;CACjC,gBAAgB,MAAW,OAAY,GAAG,cAAqB;EAC7D;EACA,OAAO;GACL,GAAG;GACH,UAAU,SAAS,UAAU,IAAI,SAAS,KAAK;EACjD;CACF;CACA,UAAU,OAAO,IAAI,gBAAgB;AACvC;AAEA,MAAM,kBAAkB,gBAAoD;CAG1E,MAAM,gBACJ,YAAY,QAAQ,QAAQ,OAAO,CAAC,EAAE,KAAK,GAAG,KAAK;CAErD,MAAM,oBAAoB,iBAAiB,IAAI,aAAa;CAC5D,IAAI,mBAAmB,OAAO;CAE9B,IAAI;CACJ,IAAI;EAEF,cAAc,EAAE,OAAO,YAAY,OAAO,EAAE;CAC9C,SAAS,MAAM;EACb,cAAc,EAAE,OAAO,oBAAoB,EAAE;CAC/C;CAEA,iBAAiB,IAAI,eAAe,WAAW;CAE/C,OAAO;AACT;;;;;;AAOA,MAAM,kBAAkB,EAAE,GAAG,QAAQ;;;;;;;;;;AAWrC,MAAa,qBAAqB,YAA6C;CAC7E,MAAM,EAAE,eAAe,gBAAgB,mBAAmB,OAAO,YAC/D,WAAW,CAAC;CAEd,MAAM,cACJ,OAAO,mBAAmB,aAAa,iBAAiB,kBAAkB;CAG5E,MAAM,uBAAuC;EAC3C,MAAM,YAAY,OAAO,OACvB,EACE,QACF,GACA,KACF;EACA,MAAM,aAAa,OAAO,OAAO,CAAC,GAAG,OAAO;EAE5C,MAAM,iBAAiB,SAAS,gBAAgB,IAAY;GAC1D,MAAM,SAAS,aAAa,MAAM,WAAW,MAAM;GAEnD,IAAI,aAAa,OAAO,OAAO,WAAW,MAAM,GAC9C,OAAO,UAAU;GAInB,IAAI,WAAW,MAAM,aAAa,OAAO,OAAO,WAAW,EAAE,GAC3D,OAAO,UAAU;GAGnB,OAAO,YAAY,MAAM;EAC3B;EAGA,eAAe,UAAU,YAAY,QAAQ,KAAK,WAAW;EAC7D,eAAe,OAAO,YAAY;EAClC,eAAe,aAAa,YAAY;EACxC,eAAe,QAAQ,YAAY;EAEnC,OAAO;CACT,EAAC,CAAE;CAEH,MAAM,iBAA0B;EAC9B,SAAS,EACP,SAAS,CAAC,EACZ;EACA,QAAQ,EACN,SAAS,CAAC,EACZ;EACA,SAAS;GACP,GAAG;GACH,KAAK;IACH,GAAG,QAAQ;IACX,GAAG,YAAY,aAAa;IAC5B,GAAG;GACL;EACF;EACA;EACA,SAAS;EACT,GAAG,eAAe,WAAW;CAC/B;CAEA,KAAK,MAAM,OAAO,cAChB,IAAI,EAAE,OAAO,mBAAmB,OAAO,YACrC,AAAC,eAA2C,OAC1C,WAAW;CAIjB,OAAO;AACT;AAEA,MAAa,oBACX,mBACA,YACkB;CAClB,MAAM,iBAAiB,kBAAkB,OAAO;CAGhD,gBAAgB,kBAAkB,qBAAqB,cAAc;CAErE,MAAM,aAAwB;EAC5B,eAAe,SAAS;EACxB,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ,SAAS;EAChC,eAAe,QAAQ;CACzB;CAEA,IAAI;CACJ,KAAK,MAAM,aAAa,YACtB,IACE,aACA,OAAO,cAAc,YACrB,OAAO,KAAK,SAAmB,CAAC,CAAC,SAAS,GAC1C;EACA,SAAS;EACT;CACF;CAMF,AAAC,eAA2C,UAAU;CACtD,AAAC,eAA2C,UAAU;CACtD,AAAC,eAA2C,QAAQ;CACpD,AAAC,eAA2C,SAAS;CACrD,AAAC,eAA2C,UAAU;CAEtD,OAAO;AACT"}
|
|
@@ -1,15 +1,30 @@
|
|
|
1
|
+
import { computeKeyId } from "../utils/cacheMemory.mjs";
|
|
1
2
|
import { getPackageJsonPath } from "../utils/getPackageJsonPath.mjs";
|
|
2
3
|
import { getLoader } from "./bundleFile.mjs";
|
|
3
|
-
import { existsSync } from "node:fs";
|
|
4
|
-
import { dirname, extname, join } from "node:path";
|
|
4
|
+
import { existsSync, statSync } from "node:fs";
|
|
5
|
+
import { dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
5
6
|
import { createRequire } from "node:module";
|
|
6
|
-
import {
|
|
7
|
+
import { build, buildSync } from "esbuild";
|
|
7
8
|
import { pathToFileURL } from "node:url";
|
|
8
9
|
|
|
9
10
|
//#region src/loadExternalFile/transpileTSToCJS.ts
|
|
11
|
+
/**
|
|
12
|
+
* Cache of resolved tsconfig paths keyed by the file's directory.
|
|
13
|
+
* Avoids re-walking to package.json + existsSync on every transpilation.
|
|
14
|
+
*/
|
|
15
|
+
const tsConfigPathCache = /* @__PURE__ */ new Map();
|
|
10
16
|
const getTsConfigPath = (filePath) => {
|
|
11
|
-
const
|
|
12
|
-
|
|
17
|
+
const fileDirectory = dirname(filePath);
|
|
18
|
+
if (tsConfigPathCache.has(fileDirectory)) return tsConfigPathCache.get(fileDirectory);
|
|
19
|
+
let resolvedPath;
|
|
20
|
+
try {
|
|
21
|
+
const tsconfigPath = join(getPackageJsonPath(fileDirectory).baseDir, "tsconfig.json");
|
|
22
|
+
resolvedPath = existsSync(tsconfigPath) ? tsconfigPath : void 0;
|
|
23
|
+
} catch {
|
|
24
|
+
resolvedPath = void 0;
|
|
25
|
+
}
|
|
26
|
+
tsConfigPathCache.set(fileDirectory, resolvedPath);
|
|
27
|
+
return resolvedPath;
|
|
13
28
|
};
|
|
14
29
|
const getTransformationOptions = (filePath) => ({
|
|
15
30
|
loader: {
|
|
@@ -29,15 +44,85 @@ const getTransformationOptions = (filePath) => ({
|
|
|
29
44
|
write: false,
|
|
30
45
|
packages: "external",
|
|
31
46
|
bundle: true,
|
|
47
|
+
metafile: true,
|
|
32
48
|
tsconfig: getTsConfigPath(filePath),
|
|
33
49
|
define: {
|
|
34
50
|
"import.meta.url": JSON.stringify(pathToFileURL(filePath).href),
|
|
35
51
|
"import.meta.env": "process.env"
|
|
36
52
|
}
|
|
37
53
|
});
|
|
54
|
+
/**
|
|
55
|
+
* In-memory cache of transpiled outputs keyed by entry file path (one entry
|
|
56
|
+
* per file, so re-transpilations replace rather than accumulate).
|
|
57
|
+
* The entry file is validated by content hash; bundled relative imports are
|
|
58
|
+
* validated by mtime + size so an edited dependency invalidates the cache.
|
|
59
|
+
*/
|
|
60
|
+
const transpileCache = /* @__PURE__ */ new Map();
|
|
61
|
+
const isInputUnchanged = (input) => {
|
|
62
|
+
try {
|
|
63
|
+
const stats = statSync(input.path);
|
|
64
|
+
return stats.mtimeMs === input.mtimeMs && stats.size === input.size;
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const getCachedTranspilation = (filePath, codeHash, optionsKey) => {
|
|
70
|
+
const cacheEntry = transpileCache.get(filePath);
|
|
71
|
+
if (!cacheEntry) return void 0;
|
|
72
|
+
if (cacheEntry.codeHash !== codeHash) return void 0;
|
|
73
|
+
if (cacheEntry.optionsKey !== optionsKey) return void 0;
|
|
74
|
+
if (!cacheEntry.inputs.every(isInputUnchanged)) return void 0;
|
|
75
|
+
return cacheEntry.output;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Extracts the fingerprints of every bundled input from the esbuild metafile.
|
|
79
|
+
* Returns `undefined` when an input cannot be fingerprinted (the result should
|
|
80
|
+
* then not be cached, as invalidation would be unreliable).
|
|
81
|
+
*/
|
|
82
|
+
const getInputFingerprints = (metafile, entryFilePath) => {
|
|
83
|
+
if (!metafile) return void 0;
|
|
84
|
+
const resolvedEntryFilePath = resolve(entryFilePath);
|
|
85
|
+
const inputs = [];
|
|
86
|
+
for (const inputPath of Object.keys(metafile.inputs)) {
|
|
87
|
+
if (inputPath === "<stdin>") continue;
|
|
88
|
+
if (inputPath.includes(":") && !isAbsolute(inputPath)) return void 0;
|
|
89
|
+
const absoluteInputPath = isAbsolute(inputPath) ? inputPath : resolve(process.cwd(), inputPath);
|
|
90
|
+
if (absoluteInputPath === resolvedEntryFilePath) continue;
|
|
91
|
+
try {
|
|
92
|
+
const stats = statSync(absoluteInputPath);
|
|
93
|
+
inputs.push({
|
|
94
|
+
path: absoluteInputPath,
|
|
95
|
+
mtimeMs: stats.mtimeMs,
|
|
96
|
+
size: stats.size
|
|
97
|
+
});
|
|
98
|
+
} catch {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return inputs;
|
|
103
|
+
};
|
|
104
|
+
const setCachedTranspilation = (filePath, codeHash, optionsKey, moduleResult, output) => {
|
|
105
|
+
const inputs = getInputFingerprints(moduleResult.metafile, filePath);
|
|
106
|
+
if (!inputs) return;
|
|
107
|
+
transpileCache.set(filePath, {
|
|
108
|
+
codeHash,
|
|
109
|
+
optionsKey,
|
|
110
|
+
output,
|
|
111
|
+
inputs
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
/** Clears the in-memory transpilation cache (mainly for tests). */
|
|
115
|
+
const clearTranspileCache = () => {
|
|
116
|
+
transpileCache.clear();
|
|
117
|
+
tsConfigPathCache.clear();
|
|
118
|
+
};
|
|
38
119
|
const transpileTSToCJSSync = (code, filePath, options) => {
|
|
39
120
|
const loader = getLoader(extname(filePath));
|
|
40
121
|
const { esbuildInstance, ...buildOptions } = options ?? {};
|
|
122
|
+
const codeHash = computeKeyId([code]);
|
|
123
|
+
const optionsKey = computeKeyId([buildOptions]);
|
|
124
|
+
const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);
|
|
125
|
+
if (typeof cachedOutput === "string") return cachedOutput;
|
|
41
126
|
const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;
|
|
42
127
|
const g = globalThis;
|
|
43
128
|
const hadFilename = typeof g.__filename === "string";
|
|
@@ -68,12 +153,18 @@ const transpileTSToCJSSync = (code, filePath, options) => {
|
|
|
68
153
|
else g.__dirname = prevDirname;
|
|
69
154
|
}
|
|
70
155
|
}
|
|
71
|
-
|
|
156
|
+
const moduleResultString = moduleResult.outputFiles?.[0]?.text;
|
|
157
|
+
if (typeof moduleResultString === "string") setCachedTranspilation(filePath, codeHash, optionsKey, moduleResult, moduleResultString);
|
|
158
|
+
return moduleResultString;
|
|
72
159
|
};
|
|
73
160
|
const transpileTSToCJS = async (code, filePath, options) => {
|
|
74
161
|
const loader = getLoader(extname(filePath));
|
|
75
162
|
const { esbuildInstance, ...buildOptions } = options ?? {};
|
|
76
|
-
const
|
|
163
|
+
const codeHash = computeKeyId([code]);
|
|
164
|
+
const optionsKey = computeKeyId([buildOptions]);
|
|
165
|
+
const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);
|
|
166
|
+
if (typeof cachedOutput === "string") return cachedOutput;
|
|
167
|
+
const moduleResult = await (esbuildInstance?.build ?? build)({
|
|
77
168
|
stdin: {
|
|
78
169
|
contents: code,
|
|
79
170
|
loader,
|
|
@@ -83,13 +174,11 @@ const transpileTSToCJS = async (code, filePath, options) => {
|
|
|
83
174
|
...getTransformationOptions(filePath),
|
|
84
175
|
...buildOptions
|
|
85
176
|
});
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
await ctx.dispose();
|
|
90
|
-
}
|
|
177
|
+
const moduleResultString = moduleResult.outputFiles?.[0]?.text;
|
|
178
|
+
if (typeof moduleResultString === "string") setCachedTranspilation(filePath, codeHash, optionsKey, moduleResult, moduleResultString);
|
|
179
|
+
return moduleResultString;
|
|
91
180
|
};
|
|
92
181
|
|
|
93
182
|
//#endregion
|
|
94
|
-
export { transpileTSToCJS, transpileTSToCJSSync };
|
|
183
|
+
export { clearTranspileCache, transpileTSToCJS, transpileTSToCJSSync };
|
|
95
184
|
//# sourceMappingURL=transpileTSToCJS.mjs.map
|