@intlayer/config 9.7.0 → 9.7.2
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/_virtual/_rolldown/runtime.cjs +1 -2
- package/dist/cjs/built.cjs +2 -3
- package/dist/cjs/bundle/index.cjs +6 -7
- package/dist/cjs/bundle/logBundle.cjs +4 -5
- package/dist/cjs/callers/base.cjs +1 -2
- package/dist/cjs/callers/compat/i18next.cjs +1 -2
- package/dist/cjs/callers/compat/lingui.cjs +1 -2
- package/dist/cjs/callers/compat/nextIntl.cjs +1 -2
- package/dist/cjs/callers/compat/ngxTranslate.cjs +1 -2
- package/dist/cjs/callers/compat/nuxtjsI18n.cjs +1 -2
- package/dist/cjs/callers/compat/reactI18next.cjs +1 -2
- package/dist/cjs/callers/compat/reactIntl.cjs +1 -2
- package/dist/cjs/callers/compat/svelteI18n.cjs +1 -2
- package/dist/cjs/callers/compat/useIntl.cjs +1 -2
- package/dist/cjs/callers/compat/vueI18n.cjs +1 -2
- package/dist/cjs/callers/index.cjs +13 -14
- package/dist/cjs/callers/transform.cjs +1 -2
- package/dist/cjs/client.cjs +15 -9
- package/dist/cjs/colors.cjs +1 -2
- package/dist/cjs/configFile/buildBrowserConfiguration.cjs +7 -8
- package/dist/cjs/configFile/buildConfigurationFields.cjs +10 -11
- package/dist/cjs/configFile/configurationSchema.cjs +2 -3
- package/dist/cjs/configFile/editorServerOverride.cjs +1 -2
- package/dist/cjs/configFile/getConfiguration.cjs +7 -8
- package/dist/cjs/configFile/index.cjs +6 -6
- package/dist/cjs/configFile/loadConfigurationFile.cjs +3 -4
- package/dist/cjs/configFile/searchConfigurationFile.cjs +3 -4
- package/dist/cjs/defaultValues/analytics.cjs +1 -2
- package/dist/cjs/defaultValues/build.cjs +1 -2
- package/dist/cjs/defaultValues/compiler.cjs +1 -2
- package/dist/cjs/defaultValues/content.cjs +1 -2
- package/dist/cjs/defaultValues/dictionary.cjs +1 -2
- package/dist/cjs/defaultValues/editor.cjs +1 -2
- package/dist/cjs/defaultValues/index.cjs +10 -10
- package/dist/cjs/defaultValues/internationalization.cjs +1 -2
- package/dist/cjs/defaultValues/log.cjs +2 -3
- package/dist/cjs/defaultValues/routing.cjs +1 -2
- package/dist/cjs/defaultValues/system.cjs +1 -2
- package/dist/cjs/dictionaryPreload.cjs +2 -3
- package/dist/cjs/envVars/envVars.cjs +1 -2
- package/dist/cjs/envVars/index.cjs +1 -1
- package/dist/cjs/extract/constants.cjs +1 -2
- package/dist/cjs/extract/index.cjs +2 -2
- package/dist/cjs/extract/shouldExtract.cjs +1 -2
- package/dist/cjs/loadEnvFile.cjs +2 -3
- package/dist/cjs/loadExternalFile/bundleFile.cjs +1 -2
- package/dist/cjs/loadExternalFile/bundleJSFile.cjs +1 -2
- package/dist/cjs/loadExternalFile/index.cjs +5 -5
- package/dist/cjs/loadExternalFile/loadExternalFile.cjs +5 -6
- package/dist/cjs/loadExternalFile/parseFileContent.cjs +4 -5
- package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +4 -5
- package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
- package/dist/cjs/logger.cjs +2 -3
- package/dist/cjs/logger.cjs.map +1 -1
- package/dist/cjs/node.cjs +6 -6
- package/dist/cjs/secrets.browser.cjs +1 -2
- package/dist/cjs/secrets.cjs +1 -2
- package/dist/cjs/utils/ESMxCJSHelpers.cjs +2 -3
- package/dist/cjs/utils/alias.cjs +3 -4
- package/dist/cjs/utils/alias.cjs.map +1 -1
- package/dist/cjs/utils/builtConfigKeys.cjs +1 -2
- package/dist/cjs/utils/cacheDisk.cjs +3 -4
- package/dist/cjs/utils/cacheDisk.cjs.map +1 -1
- package/dist/cjs/utils/cacheMemory.cjs +1 -2
- package/dist/cjs/utils/chunkArray.cjs +22 -0
- package/dist/cjs/utils/chunkArray.cjs.map +1 -0
- package/dist/cjs/utils/clearModuleCache.cjs +2 -3
- package/dist/cjs/utils/compareVersions.cjs +1 -2
- package/dist/cjs/utils/extractErrorMessage.cjs +1 -2
- package/dist/cjs/utils/getDictionarySelectorUsage.cjs +1 -2
- package/dist/cjs/utils/getExtension.cjs +1 -2
- package/dist/cjs/utils/getPackageJsonPath.cjs +2 -3
- package/dist/cjs/utils/getStorageAttributes.cjs +2 -3
- package/dist/cjs/utils/getUsedNodeTypes.cjs +1 -2
- package/dist/cjs/utils/index.cjs +31 -24
- package/dist/cjs/utils/isPackageInstalled.cjs +2 -3
- package/dist/cjs/utils/logStack.cjs +3 -4
- package/dist/cjs/utils/normalizePath.cjs +1 -2
- package/dist/cjs/utils/pLimit.cjs +132 -0
- package/dist/cjs/utils/pLimit.cjs.map +1 -0
- package/dist/cjs/utils/parallelize.cjs +11 -0
- package/dist/cjs/utils/parallelize.cjs.map +1 -0
- package/dist/cjs/utils/parseFilePathPattern.cjs +1 -2
- package/dist/cjs/utils/pathSecurity.cjs +1 -2
- package/dist/cjs/utils/retryManager.cjs +3 -4
- package/dist/cjs/utils/setIntlayerIdentifier.cjs +1 -2
- package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs +1 -2
- package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs +1 -2
- package/dist/cjs/utils/stringFormatter/index.cjs +4 -4
- package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs +1 -2
- package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs +1 -2
- package/dist/esm/_virtual/_rolldown/runtime.mjs +1 -2
- package/dist/esm/built.mjs +1 -2
- package/dist/esm/bundle/index.mjs +2 -3
- package/dist/esm/bundle/logBundle.mjs +2 -3
- package/dist/esm/callers/base.mjs +1 -2
- package/dist/esm/callers/compat/i18next.mjs +1 -2
- package/dist/esm/callers/compat/lingui.mjs +1 -2
- package/dist/esm/callers/compat/nextIntl.mjs +1 -2
- package/dist/esm/callers/compat/ngxTranslate.mjs +1 -2
- package/dist/esm/callers/compat/nuxtjsI18n.mjs +1 -2
- package/dist/esm/callers/compat/reactI18next.mjs +1 -2
- package/dist/esm/callers/compat/reactIntl.mjs +1 -2
- package/dist/esm/callers/compat/svelteI18n.mjs +1 -2
- package/dist/esm/callers/compat/useIntl.mjs +1 -2
- package/dist/esm/callers/compat/vueI18n.mjs +1 -2
- package/dist/esm/callers/index.mjs +1 -2
- package/dist/esm/callers/transform.mjs +1 -2
- package/dist/esm/client.mjs +4 -1
- package/dist/esm/colors.mjs +1 -2
- package/dist/esm/configFile/buildBrowserConfiguration.mjs +1 -2
- package/dist/esm/configFile/buildConfigurationFields.mjs +2 -3
- package/dist/esm/configFile/configurationSchema.mjs +1 -2
- package/dist/esm/configFile/editorServerOverride.mjs +1 -2
- package/dist/esm/configFile/getConfiguration.mjs +1 -2
- package/dist/esm/configFile/index.mjs +2 -2
- package/dist/esm/configFile/loadConfigurationFile.mjs +2 -3
- package/dist/esm/configFile/searchConfigurationFile.mjs +1 -2
- package/dist/esm/defaultValues/analytics.mjs +1 -2
- package/dist/esm/defaultValues/build.mjs +1 -2
- package/dist/esm/defaultValues/compiler.mjs +1 -2
- package/dist/esm/defaultValues/content.mjs +1 -2
- package/dist/esm/defaultValues/dictionary.mjs +1 -2
- package/dist/esm/defaultValues/editor.mjs +1 -2
- package/dist/esm/defaultValues/index.mjs +4 -4
- package/dist/esm/defaultValues/internationalization.mjs +1 -2
- package/dist/esm/defaultValues/log.mjs +1 -2
- package/dist/esm/defaultValues/routing.mjs +1 -2
- package/dist/esm/defaultValues/system.mjs +1 -2
- package/dist/esm/dictionaryPreload.mjs +1 -2
- package/dist/esm/envVars/envVars.mjs +1 -2
- package/dist/esm/extract/constants.mjs +1 -2
- package/dist/esm/extract/shouldExtract.mjs +1 -2
- package/dist/esm/loadEnvFile.mjs +1 -2
- package/dist/esm/loadExternalFile/bundleFile.mjs +1 -2
- package/dist/esm/loadExternalFile/bundleJSFile.mjs +1 -2
- package/dist/esm/loadExternalFile/index.mjs +3 -3
- package/dist/esm/loadExternalFile/loadExternalFile.mjs +1 -2
- package/dist/esm/loadExternalFile/parseFileContent.mjs +1 -2
- package/dist/esm/loadExternalFile/transpileTSToCJS.mjs +1 -2
- package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
- package/dist/esm/logger.mjs +1 -2
- package/dist/esm/logger.mjs.map +1 -1
- package/dist/esm/node.mjs +2 -2
- package/dist/esm/secrets.browser.mjs +1 -2
- package/dist/esm/secrets.mjs +1 -2
- package/dist/esm/utils/ESMxCJSHelpers.mjs +1 -2
- package/dist/esm/utils/alias.mjs +2 -3
- package/dist/esm/utils/alias.mjs.map +1 -1
- package/dist/esm/utils/builtConfigKeys.mjs +1 -2
- package/dist/esm/utils/cacheDisk.mjs +1 -2
- package/dist/esm/utils/cacheDisk.mjs.map +1 -1
- package/dist/esm/utils/cacheMemory.mjs +1 -2
- package/dist/esm/utils/chunkArray.mjs +21 -0
- package/dist/esm/utils/chunkArray.mjs.map +1 -0
- package/dist/esm/utils/clearModuleCache.mjs +1 -2
- package/dist/esm/utils/compareVersions.mjs +1 -2
- package/dist/esm/utils/extractErrorMessage.mjs +1 -2
- package/dist/esm/utils/getDictionarySelectorUsage.mjs +1 -2
- package/dist/esm/utils/getExtension.mjs +1 -2
- package/dist/esm/utils/getPackageJsonPath.mjs +1 -2
- package/dist/esm/utils/getStorageAttributes.mjs +1 -2
- package/dist/esm/utils/getUsedNodeTypes.mjs +1 -2
- package/dist/esm/utils/index.mjs +17 -14
- package/dist/esm/utils/isPackageInstalled.mjs +1 -2
- package/dist/esm/utils/logStack.mjs +1 -2
- package/dist/esm/utils/normalizePath.mjs +1 -2
- package/dist/esm/utils/pLimit.mjs +130 -0
- package/dist/esm/utils/pLimit.mjs.map +1 -0
- package/dist/esm/utils/parallelize.mjs +10 -0
- package/dist/esm/utils/parallelize.mjs.map +1 -0
- package/dist/esm/utils/parseFilePathPattern.mjs +1 -2
- package/dist/esm/utils/pathSecurity.mjs +1 -2
- package/dist/esm/utils/retryManager.mjs +2 -3
- package/dist/esm/utils/setIntlayerIdentifier.mjs +1 -2
- package/dist/esm/utils/stringFormatter/camelCaseToKebabCase.mjs +1 -2
- package/dist/esm/utils/stringFormatter/camelCaseToSentence.mjs +1 -2
- package/dist/esm/utils/stringFormatter/kebabCaseToCamelCase.mjs +1 -2
- package/dist/esm/utils/stringFormatter/toLowerCamelCase.mjs +1 -2
- package/dist/types/built.d.ts +0 -2
- package/dist/types/built.d.ts.map +1 -1
- package/dist/types/bundle/index.d.ts +0 -2
- package/dist/types/bundle/index.d.ts.map +1 -1
- package/dist/types/bundle/logBundle.d.ts +0 -2
- package/dist/types/bundle/logBundle.d.ts.map +1 -1
- package/dist/types/callers/base.d.ts +0 -2
- package/dist/types/callers/base.d.ts.map +1 -1
- package/dist/types/callers/compat/i18next.d.ts +0 -2
- package/dist/types/callers/compat/i18next.d.ts.map +1 -1
- package/dist/types/callers/compat/lingui.d.ts +0 -2
- package/dist/types/callers/compat/lingui.d.ts.map +1 -1
- package/dist/types/callers/compat/nextIntl.d.ts +0 -2
- package/dist/types/callers/compat/nextIntl.d.ts.map +1 -1
- package/dist/types/callers/compat/ngxTranslate.d.ts +0 -2
- package/dist/types/callers/compat/ngxTranslate.d.ts.map +1 -1
- package/dist/types/callers/compat/nuxtjsI18n.d.ts +0 -2
- package/dist/types/callers/compat/nuxtjsI18n.d.ts.map +1 -1
- package/dist/types/callers/compat/reactI18next.d.ts +0 -2
- package/dist/types/callers/compat/reactI18next.d.ts.map +1 -1
- package/dist/types/callers/compat/reactIntl.d.ts +0 -2
- package/dist/types/callers/compat/reactIntl.d.ts.map +1 -1
- package/dist/types/callers/compat/svelteI18n.d.ts +0 -2
- package/dist/types/callers/compat/svelteI18n.d.ts.map +1 -1
- package/dist/types/callers/compat/useIntl.d.ts +0 -2
- package/dist/types/callers/compat/useIntl.d.ts.map +1 -1
- package/dist/types/callers/compat/vueI18n.d.ts +0 -2
- package/dist/types/callers/compat/vueI18n.d.ts.map +1 -1
- package/dist/types/callers/index.d.ts +0 -2
- package/dist/types/callers/index.d.ts.map +1 -1
- package/dist/types/callers/transform.d.ts +0 -2
- package/dist/types/callers/transform.d.ts.map +1 -1
- package/dist/types/callers/types.d.ts +0 -2
- package/dist/types/callers/types.d.ts.map +1 -1
- package/dist/types/client.d.ts +5 -1
- package/dist/types/colors.d.ts +0 -1
- package/dist/types/configFile/buildBrowserConfiguration.d.ts +0 -2
- package/dist/types/configFile/buildBrowserConfiguration.d.ts.map +1 -1
- package/dist/types/configFile/buildConfigurationFields.d.ts +0 -2
- package/dist/types/configFile/buildConfigurationFields.d.ts.map +1 -1
- package/dist/types/configFile/configurationSchema.d.ts +0 -2
- package/dist/types/configFile/configurationSchema.d.ts.map +1 -1
- package/dist/types/configFile/editorServerOverride.d.ts +0 -2
- package/dist/types/configFile/editorServerOverride.d.ts.map +1 -1
- package/dist/types/configFile/getConfiguration.d.ts +1 -3
- package/dist/types/configFile/getConfiguration.d.ts.map +1 -1
- package/dist/types/configFile/index.d.ts +1 -1
- package/dist/types/configFile/loadConfigurationFile.d.ts +0 -2
- package/dist/types/configFile/loadConfigurationFile.d.ts.map +1 -1
- package/dist/types/configFile/searchConfigurationFile.d.ts +1 -2
- package/dist/types/configFile/searchConfigurationFile.d.ts.map +1 -1
- package/dist/types/defaultValues/analytics.d.ts +0 -2
- package/dist/types/defaultValues/analytics.d.ts.map +1 -1
- package/dist/types/defaultValues/build.d.ts +0 -2
- package/dist/types/defaultValues/build.d.ts.map +1 -1
- package/dist/types/defaultValues/compiler.d.ts +0 -2
- package/dist/types/defaultValues/compiler.d.ts.map +1 -1
- package/dist/types/defaultValues/content.d.ts +0 -2
- package/dist/types/defaultValues/content.d.ts.map +1 -1
- package/dist/types/defaultValues/dictionary.d.ts +0 -2
- package/dist/types/defaultValues/dictionary.d.ts.map +1 -1
- package/dist/types/defaultValues/editor.d.ts +0 -2
- package/dist/types/defaultValues/editor.d.ts.map +1 -1
- package/dist/types/defaultValues/internationalization.d.ts +1 -3
- package/dist/types/defaultValues/internationalization.d.ts.map +1 -1
- package/dist/types/defaultValues/log.d.ts +0 -2
- package/dist/types/defaultValues/log.d.ts.map +1 -1
- package/dist/types/defaultValues/routing.d.ts +0 -2
- package/dist/types/defaultValues/routing.d.ts.map +1 -1
- package/dist/types/defaultValues/system.d.ts +0 -2
- package/dist/types/defaultValues/system.d.ts.map +1 -1
- package/dist/types/dictionaryPreload.d.ts +0 -2
- package/dist/types/dictionaryPreload.d.ts.map +1 -1
- package/dist/types/envVars/envVars.d.ts +0 -2
- package/dist/types/envVars/envVars.d.ts.map +1 -1
- package/dist/types/extract/constants.d.ts +0 -2
- package/dist/types/extract/constants.d.ts.map +1 -1
- package/dist/types/extract/index.d.ts +11 -0
- package/dist/types/extract/shouldExtract.d.ts +0 -2
- package/dist/types/extract/shouldExtract.d.ts.map +1 -1
- package/dist/types/loadEnvFile.d.ts +0 -2
- package/dist/types/loadEnvFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/bundleFile.d.ts +0 -2
- package/dist/types/loadExternalFile/bundleFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/bundleJSFile.d.ts +0 -2
- package/dist/types/loadExternalFile/bundleJSFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/index.d.ts +3 -3
- package/dist/types/loadExternalFile/loadExternalFile.d.ts +0 -2
- package/dist/types/loadExternalFile/loadExternalFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/parseFileContent.d.ts +0 -2
- package/dist/types/loadExternalFile/parseFileContent.d.ts.map +1 -1
- package/dist/types/loadExternalFile/transpileTSToCJS.d.ts +0 -2
- package/dist/types/loadExternalFile/transpileTSToCJS.d.ts.map +1 -1
- package/dist/types/logger.d.ts +1 -3
- package/dist/types/logger.d.ts.map +1 -1
- package/dist/types/node.d.ts +1 -1
- package/dist/types/secrets.browser.d.ts +0 -2
- package/dist/types/secrets.browser.d.ts.map +1 -1
- package/dist/types/secrets.d.ts +0 -2
- package/dist/types/secrets.d.ts.map +1 -1
- package/dist/types/utils/ESMxCJSHelpers.d.ts +0 -2
- package/dist/types/utils/ESMxCJSHelpers.d.ts.map +1 -1
- package/dist/types/utils/alias.d.ts +0 -2
- package/dist/types/utils/alias.d.ts.map +1 -1
- package/dist/types/utils/builtConfigKeys.d.ts +0 -2
- package/dist/types/utils/builtConfigKeys.d.ts.map +1 -1
- package/dist/types/utils/cacheDisk.d.ts +1 -2
- package/dist/types/utils/cacheDisk.d.ts.map +1 -1
- package/dist/types/utils/cacheMemory.d.ts +1 -2
- package/dist/types/utils/cacheMemory.d.ts.map +1 -1
- package/dist/types/utils/chunkArray.d.ts +13 -0
- package/dist/types/utils/chunkArray.d.ts.map +1 -0
- package/dist/types/utils/clearModuleCache.d.ts +0 -2
- package/dist/types/utils/clearModuleCache.d.ts.map +1 -1
- package/dist/types/utils/compareVersions.d.ts +0 -2
- package/dist/types/utils/compareVersions.d.ts.map +1 -1
- package/dist/types/utils/extractErrorMessage.d.ts +0 -2
- package/dist/types/utils/extractErrorMessage.d.ts.map +1 -1
- package/dist/types/utils/getDictionarySelectorUsage.d.ts +1 -2
- package/dist/types/utils/getDictionarySelectorUsage.d.ts.map +1 -1
- package/dist/types/utils/getExtension.d.ts +0 -2
- package/dist/types/utils/getExtension.d.ts.map +1 -1
- package/dist/types/utils/getPackageJsonPath.d.ts +1 -2
- package/dist/types/utils/getPackageJsonPath.d.ts.map +1 -1
- package/dist/types/utils/getStorageAttributes.d.ts +0 -2
- package/dist/types/utils/getStorageAttributes.d.ts.map +1 -1
- package/dist/types/utils/getUsedNodeTypes.d.ts +0 -2
- package/dist/types/utils/getUsedNodeTypes.d.ts.map +1 -1
- package/dist/types/utils/index.d.ts +15 -11
- package/dist/types/utils/isPackageInstalled.d.ts +0 -2
- package/dist/types/utils/isPackageInstalled.d.ts.map +1 -1
- package/dist/types/utils/logStack.d.ts +0 -2
- package/dist/types/utils/logStack.d.ts.map +1 -1
- package/dist/types/utils/normalizePath.d.ts +0 -2
- package/dist/types/utils/normalizePath.d.ts.map +1 -1
- package/dist/types/utils/pLimit.d.ts +13 -0
- package/dist/types/utils/pLimit.d.ts.map +1 -0
- package/dist/types/utils/parallelize.d.ts +2 -0
- package/dist/types/utils/parallelize.d.ts.map +1 -0
- package/dist/types/utils/parseFilePathPattern.d.ts +0 -2
- package/dist/types/utils/parseFilePathPattern.d.ts.map +1 -1
- package/dist/types/utils/pathSecurity.d.ts +0 -2
- package/dist/types/utils/pathSecurity.d.ts.map +1 -1
- package/dist/types/utils/retryManager.d.ts +0 -2
- package/dist/types/utils/retryManager.d.ts.map +1 -1
- package/dist/types/utils/setIntlayerIdentifier.d.ts +1 -2
- package/dist/types/utils/setIntlayerIdentifier.d.ts.map +1 -1
- package/dist/types/utils/stringFormatter/camelCaseToKebabCase.d.ts +0 -2
- package/dist/types/utils/stringFormatter/camelCaseToKebabCase.d.ts.map +1 -1
- package/dist/types/utils/stringFormatter/camelCaseToSentence.d.ts +0 -2
- package/dist/types/utils/stringFormatter/camelCaseToSentence.d.ts.map +1 -1
- package/dist/types/utils/stringFormatter/kebabCaseToCamelCase.d.ts +0 -2
- package/dist/types/utils/stringFormatter/kebabCaseToCamelCase.d.ts.map +1 -1
- package/dist/types/utils/stringFormatter/toLowerCamelCase.d.ts +0 -2
- package/dist/types/utils/stringFormatter/toLowerCamelCase.d.ts.map +1 -1
- package/package.json +73 -73
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { ANALYTICS_ENABLED, ANALYTICS_FLUSH_INTERVAL, ANALYTICS_SAMPLE_RATE } from "./analytics.mjs";
|
|
2
|
-
import { APPLICATION_URL, BACKEND_URL, CMS_URL, DICTIONARY_PRIORITY_STRATEGY, EDITOR_URL, IS_ENABLED, LIVE_SYNC, LIVE_SYNC_PORT, PORT } from "./editor.mjs";
|
|
3
|
-
import { DEFAULT_LOCALE, LOCALES, REQUIRED_LOCALES, STRICT_MODE } from "./internationalization.mjs";
|
|
4
|
-
import { MODE, PREFIX } from "./log.mjs";
|
|
5
|
-
import { BASE_PATH, COOKIE_NAME, ENABLE_PROXY, HEADER_NAME, LOCALE_STORAGE_NAME, ROUTING_MODE, SERVER_SET_COOKIE, STORAGE } from "./routing.mjs";
|
|
6
2
|
import { BUILD_MODE, CACHE, CHUNK_GROUPING, DICTIONARIES_PRELOAD, MINIFY, OPTIMIZE, OUTPUT_FORMAT, PURGE, TRAVERSE_PATTERN, TYPE_CHECKING } from "./build.mjs";
|
|
7
3
|
import { COMPILER_DICTIONARY_KEY_PREFIX, COMPILER_ENABLED, COMPILER_NO_METADATA, COMPILER_SAVE_COMPONENTS } from "./compiler.mjs";
|
|
8
4
|
import { CODE_DIR, CONTENT_DIR, EXCLUDED_PATHS, FILE_EXTENSIONS, I18NEXT_DICTIONARIES_DIR, REACT_INTL_MESSAGES_DIR, WATCH } from "./content.mjs";
|
|
9
5
|
import { CONTENT_AUTO_TRANSFORMATION, DYNAMIC_DICTIONARIES_JSON_SUBDIR, DYNAMIC_ENTRY_LOADER_MAP_IDENTIFIER, FILL, IMPORT_MODE, LOCATION, PRELOADED_DYNAMIC_KEY, QUALIFIER_DYNAMIC_TYPES_KEY } from "./dictionary.mjs";
|
|
6
|
+
import { APPLICATION_URL, BACKEND_URL, CMS_URL, DICTIONARY_PRIORITY_STRATEGY, EDITOR_URL, IS_ENABLED, LIVE_SYNC, LIVE_SYNC_PORT, PORT } from "./editor.mjs";
|
|
7
|
+
import { DEFAULT_LOCALE, LOCALES, REQUIRED_LOCALES, STRICT_MODE } from "./internationalization.mjs";
|
|
8
|
+
import { MODE, PREFIX } from "./log.mjs";
|
|
9
|
+
import { BASE_PATH, COOKIE_NAME, ENABLE_PROXY, HEADER_NAME, LOCALE_STORAGE_NAME, ROUTING_MODE, SERVER_SET_COOKIE, STORAGE } from "./routing.mjs";
|
|
10
10
|
import { CACHE_DIR, CONFIG_DIR, DICTIONARIES_DIR, DYNAMIC_DICTIONARIES_DIR, FETCH_DICTIONARIES_DIR, MAIN_DIR, MASKS_DIR, MODULE_AUGMENTATION_DIR, REMOTE_DICTIONARIES_DIR, TEMP_DIR, TYPES_DIR, UNMERGED_DICTIONARIES_DIR } from "./system.mjs";
|
|
11
11
|
|
|
12
12
|
export { ANALYTICS_ENABLED, ANALYTICS_FLUSH_INTERVAL, ANALYTICS_SAMPLE_RATE, APPLICATION_URL, BACKEND_URL, BASE_PATH, BUILD_MODE, CACHE, CACHE_DIR, CHUNK_GROUPING, CMS_URL, CODE_DIR, COMPILER_DICTIONARY_KEY_PREFIX, COMPILER_ENABLED, COMPILER_NO_METADATA, COMPILER_SAVE_COMPONENTS, CONFIG_DIR, CONTENT_AUTO_TRANSFORMATION, CONTENT_DIR, COOKIE_NAME, DEFAULT_LOCALE, DICTIONARIES_DIR, DICTIONARIES_PRELOAD, DICTIONARY_PRIORITY_STRATEGY, DYNAMIC_DICTIONARIES_DIR, DYNAMIC_DICTIONARIES_JSON_SUBDIR, DYNAMIC_ENTRY_LOADER_MAP_IDENTIFIER, EDITOR_URL, ENABLE_PROXY, EXCLUDED_PATHS, FETCH_DICTIONARIES_DIR, FILE_EXTENSIONS, FILL, HEADER_NAME, I18NEXT_DICTIONARIES_DIR, IMPORT_MODE, IS_ENABLED, LIVE_SYNC, LIVE_SYNC_PORT, LOCALES, LOCALE_STORAGE_NAME, LOCATION, MAIN_DIR, MASKS_DIR, MINIFY, MODE, MODULE_AUGMENTATION_DIR, OPTIMIZE, OUTPUT_FORMAT, PORT, PREFIX, PRELOADED_DYNAMIC_KEY, PURGE, QUALIFIER_DYNAMIC_TYPES_KEY, REACT_INTL_MESSAGES_DIR, REMOTE_DICTIONARIES_DIR, REQUIRED_LOCALES, ROUTING_MODE, SERVER_SET_COOKIE, STORAGE, STRICT_MODE, TEMP_DIR, TRAVERSE_PATTERN, TYPES_DIR, TYPE_CHECKING, UNMERGED_DICTIONARIES_DIR, WATCH };
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
// src/defaultValues/internationalization.ts
|
|
2
2
|
const LOCALES = ["en"];
|
|
3
3
|
const REQUIRED_LOCALES = [];
|
|
4
4
|
const DEFAULT_LOCALE = "en";
|
|
5
5
|
const STRICT_MODE = "inclusive";
|
|
6
6
|
|
|
7
|
-
//#endregion
|
|
8
7
|
export { DEFAULT_LOCALE, LOCALES, REQUIRED_LOCALES, STRICT_MODE };
|
|
9
8
|
//# sourceMappingURL=internationalization.mjs.map
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { GREY_DARK, RESET } from "../colors.mjs";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// src/defaultValues/log.ts
|
|
4
4
|
const MODE = "default";
|
|
5
5
|
const PREFIX = `${GREY_DARK}[intlayer] ${RESET}`;
|
|
6
6
|
|
|
7
|
-
//#endregion
|
|
8
7
|
export { MODE, PREFIX };
|
|
9
8
|
//# sourceMappingURL=log.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/defaultValues/routing.ts
|
|
2
2
|
const HEADER_NAME = "x-intlayer-locale";
|
|
3
3
|
const COOKIE_NAME = "INTLAYER_LOCALE";
|
|
4
4
|
const LOCALE_STORAGE_NAME = "INTLAYER_LOCALE";
|
|
@@ -14,6 +14,5 @@ const ROUTING_MODE = "prefix-no-default";
|
|
|
14
14
|
const ENABLE_PROXY = void 0;
|
|
15
15
|
const STORAGE = ["cookie", "header"];
|
|
16
16
|
|
|
17
|
-
//#endregion
|
|
18
17
|
export { BASE_PATH, COOKIE_NAME, ENABLE_PROXY, HEADER_NAME, LOCALE_STORAGE_NAME, ROUTING_MODE, SERVER_SET_COOKIE, STORAGE };
|
|
19
18
|
//# sourceMappingURL=routing.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/defaultValues/system.ts
|
|
2
2
|
const MAIN_DIR = ".intlayer/main";
|
|
3
3
|
const DICTIONARIES_DIR = ".intlayer/dictionary";
|
|
4
4
|
const MASKS_DIR = ".intlayer/mask";
|
|
@@ -12,6 +12,5 @@ const CONFIG_DIR = ".intlayer/config";
|
|
|
12
12
|
const CACHE_DIR = ".intlayer/cache";
|
|
13
13
|
const TEMP_DIR = ".intlayer/tmp";
|
|
14
14
|
|
|
15
|
-
//#endregion
|
|
16
15
|
export { CACHE_DIR, CONFIG_DIR, DICTIONARIES_DIR, DYNAMIC_DICTIONARIES_DIR, FETCH_DICTIONARIES_DIR, MAIN_DIR, MASKS_DIR, MODULE_AUGMENTATION_DIR, REMOTE_DICTIONARIES_DIR, TEMP_DIR, TYPES_DIR, UNMERGED_DICTIONARIES_DIR };
|
|
17
16
|
//# sourceMappingURL=system.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DYNAMIC_ENTRY_LOADER_MAP_IDENTIFIER, PRELOADED_DYNAMIC_KEY, QUALIFIER_DYNAMIC_TYPES_KEY } from "./defaultValues/dictionary.mjs";
|
|
2
2
|
import { dirname, resolve } from "node:path";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// src/dictionaryPreload.ts
|
|
5
5
|
/**
|
|
6
6
|
* Matches a generated dynamic entry point, whose layout is
|
|
7
7
|
* `<dynamicDictionariesDir>/<key>.mjs`. The per-locale JSON chunks it imports
|
|
@@ -139,6 +139,5 @@ const addDynamicEntryPreload = (code, preloadModuleId) => {
|
|
|
139
139
|
return { code: buildPreloadImport(preloadModuleId) + code + PRELOAD_PREAMBLE };
|
|
140
140
|
};
|
|
141
141
|
|
|
142
|
-
//#endregion
|
|
143
142
|
export { DYNAMIC_ENTRY_PATTERN, PRELOAD_MODULE_SPECIFIER, addDynamicEntryPreload, createDynamicEntryFilter, resolvePreloadModuleId };
|
|
144
143
|
//# sourceMappingURL=dictionaryPreload.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/envVars/envVars.ts
|
|
2
2
|
/**
|
|
3
3
|
* Converts a camelCase node-type string to SCREAMING_SNAKE_CASE so that
|
|
4
4
|
* the generated env-var name matches what the plugin source files check.
|
|
@@ -92,6 +92,5 @@ const getConfigEnvVars = (config, wrapKey = (key) => key, wrapValue = (value) =>
|
|
|
92
92
|
return envVars;
|
|
93
93
|
};
|
|
94
94
|
|
|
95
|
-
//#endregion
|
|
96
95
|
export { formatDictionarySelectorEnvVar, formatNodeTypeToEnvVar, formatOptimizedNestingEnvVar, getConfigEnvVars };
|
|
97
96
|
//# sourceMappingURL=envVars.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/extract/constants.ts
|
|
2
2
|
/**
|
|
3
3
|
* Attributes that should be extracted as translatable strings from JSX/HTML elements.
|
|
4
4
|
* This is the single source of truth shared across all Intlayer compiler packages
|
|
@@ -13,6 +13,5 @@ const ATTRIBUTES_TO_EXTRACT = [
|
|
|
13
13
|
"label"
|
|
14
14
|
];
|
|
15
15
|
|
|
16
|
-
//#endregion
|
|
17
16
|
export { ATTRIBUTES_TO_EXTRACT };
|
|
18
17
|
//# sourceMappingURL=constants.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/extract/shouldExtract.ts
|
|
2
2
|
/**
|
|
3
3
|
* Checks whether the given text should be extracted as a translatable string.
|
|
4
4
|
*
|
|
@@ -32,6 +32,5 @@ const shouldExtract = (text) => {
|
|
|
32
32
|
return true;
|
|
33
33
|
};
|
|
34
34
|
|
|
35
|
-
//#endregion
|
|
36
35
|
export { shouldExtract };
|
|
37
36
|
//# sourceMappingURL=shouldExtract.mjs.map
|
package/dist/esm/loadEnvFile.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync, statSync } from "node:fs";
|
|
2
2
|
import dotenv from "dotenv";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// src/loadEnvFile.ts
|
|
5
5
|
const DEFAULT_ENV = process.env.NODE_ENV ?? "development";
|
|
6
6
|
const getEnvFilePath = (env = process.env.NODE_ENV ?? "development", envFile) => {
|
|
7
7
|
return (envFile ? [envFile] : [
|
|
@@ -62,6 +62,5 @@ const loadEnvFile = (options) => {
|
|
|
62
62
|
return parsedEnv;
|
|
63
63
|
};
|
|
64
64
|
|
|
65
|
-
//#endregion
|
|
66
65
|
export { getEnvFilePath, loadEnvFile };
|
|
67
66
|
//# sourceMappingURL=loadEnvFile.mjs.map
|
|
@@ -2,7 +2,7 @@ import { dirname, extname } from "node:path";
|
|
|
2
2
|
import { build, buildSync } from "esbuild";
|
|
3
3
|
import { pathToFileURL } from "node:url";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
// src/loadExternalFile/bundleFile.ts
|
|
6
6
|
const getLoader = (extension) => {
|
|
7
7
|
switch (extension) {
|
|
8
8
|
case ".js": return "js";
|
|
@@ -67,6 +67,5 @@ const bundleFile = async (code, filePath, options) => {
|
|
|
67
67
|
})).outputFiles?.[0].text;
|
|
68
68
|
};
|
|
69
69
|
|
|
70
|
-
//#endregion
|
|
71
70
|
export { bundleFile, bundleFileSync, getLoader };
|
|
72
71
|
//# sourceMappingURL=bundleFile.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { build } from "esbuild";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// src/loadExternalFile/bundleJSFile.ts
|
|
4
4
|
const commonBuildOptions = {
|
|
5
5
|
bundle: true,
|
|
6
6
|
format: "cjs",
|
|
@@ -27,6 +27,5 @@ const bundleJSFile = async (buildOptions) => await build({
|
|
|
27
27
|
...buildOptions
|
|
28
28
|
});
|
|
29
29
|
|
|
30
|
-
//#endregion
|
|
31
30
|
export { bundleJSFile };
|
|
32
31
|
//# sourceMappingURL=bundleJSFile.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { getSandBoxContext, parseFileContent } from "./parseFileContent.mjs";
|
|
2
1
|
import { bundleFile, bundleFileSync, getLoader } from "./bundleFile.mjs";
|
|
3
|
-
import { clearTranspileCache, transpileTSToCJS, transpileTSToCJSSync } from "./transpileTSToCJS.mjs";
|
|
4
|
-
import { loadExternalFile, loadExternalFileSync } from "./loadExternalFile.mjs";
|
|
5
2
|
import { bundleJSFile } from "./bundleJSFile.mjs";
|
|
3
|
+
import { loadExternalFile, loadExternalFileSync } from "./loadExternalFile.mjs";
|
|
4
|
+
import { getSandBoxContext, parseFileContent } from "./parseFileContent.mjs";
|
|
5
|
+
import { clearTranspileCache, transpileTSToCJS, transpileTSToCJSSync } from "./transpileTSToCJS.mjs";
|
|
6
6
|
|
|
7
7
|
export { bundleFile, bundleFileSync, bundleJSFile, clearTranspileCache, getLoader, getSandBoxContext, loadExternalFile, loadExternalFileSync, parseFileContent, transpileTSToCJS, transpileTSToCJSSync };
|
|
@@ -6,7 +6,7 @@ import { extname } from "node:path";
|
|
|
6
6
|
import { readFile } from "node:fs/promises";
|
|
7
7
|
import JSON5 from "json5";
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
// src/loadExternalFile/loadExternalFile.ts
|
|
10
10
|
const parseJSON5 = JSON5.parse || JSON5.default?.parse;
|
|
11
11
|
/**
|
|
12
12
|
* Load the content declaration from the given path
|
|
@@ -91,6 +91,5 @@ const loadExternalFile = async (filePath, options) => {
|
|
|
91
91
|
}
|
|
92
92
|
};
|
|
93
93
|
|
|
94
|
-
//#endregion
|
|
95
94
|
export { loadExternalFile, loadExternalFileSync };
|
|
96
95
|
//# sourceMappingURL=loadExternalFile.mjs.map
|
|
@@ -3,7 +3,7 @@ import { getProjectRequire } from "../utils/ESMxCJSHelpers.mjs";
|
|
|
3
3
|
import { runInNewContext } from "node:vm";
|
|
4
4
|
import * as esbuild from "esbuild";
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
// src/loadExternalFile/parseFileContent.ts
|
|
7
7
|
const NODE_GLOBALS = [
|
|
8
8
|
"Buffer",
|
|
9
9
|
"setTimeout",
|
|
@@ -132,6 +132,5 @@ const parseFileContent = (fileContentString, options) => {
|
|
|
132
132
|
return result;
|
|
133
133
|
};
|
|
134
134
|
|
|
135
|
-
//#endregion
|
|
136
135
|
export { getSandBoxContext, parseFileContent };
|
|
137
136
|
//# sourceMappingURL=parseFileContent.mjs.map
|
|
@@ -7,7 +7,7 @@ import { createRequire } from "node:module";
|
|
|
7
7
|
import { build, buildSync } from "esbuild";
|
|
8
8
|
import { pathToFileURL } from "node:url";
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
// src/loadExternalFile/transpileTSToCJS.ts
|
|
11
11
|
/**
|
|
12
12
|
* Cache of resolved tsconfig paths keyed by the file's directory.
|
|
13
13
|
* Avoids re-walking to package.json + existsSync on every transpilation.
|
|
@@ -181,6 +181,5 @@ const transpileTSToCJS = async (code, filePath, options) => {
|
|
|
181
181
|
return moduleResultString;
|
|
182
182
|
};
|
|
183
183
|
|
|
184
|
-
//#endregion
|
|
185
184
|
export { clearTranspileCache, transpileTSToCJS, transpileTSToCJSSync };
|
|
186
185
|
//# sourceMappingURL=transpileTSToCJS.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transpileTSToCJS.mjs","names":[],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, extname, isAbsolute, join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Metafile,\n} from 'esbuild';\nimport { computeKeyId } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nexport type TranspileOptions = BuildOptions & {\n /**\n * Optional custom esbuild instance to use for transpilation.\n * Useful in environments (e.g. VS Code extensions) where the bundled\n * esbuild binary may not match the host platform.\n * When provided, its `buildSync`/`build` methods are used instead of\n * the ones imported from the `esbuild` package.\n */\n esbuildInstance?: typeof import('esbuild');\n};\n\n/**\n * Cache of resolved tsconfig paths keyed by the file's directory.\n * Avoids re-walking to package.json + existsSync on every transpilation.\n */\nconst tsConfigPathCache = new Map<string, string | undefined>();\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const fileDirectory = dirname(filePath);\n\n if (tsConfigPathCache.has(fileDirectory)) {\n return tsConfigPathCache.get(fileDirectory);\n }\n\n let resolvedPath: string | undefined;\n try {\n const tsconfigPath = join(\n getPackageJsonPath(fileDirectory).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n resolvedPath = existsSync(tsconfigPath) ? tsconfigPath : undefined;\n } catch {\n // No package.json found up the tree — transpile without a tsconfig\n resolvedPath = undefined;\n }\n\n tsConfigPathCache.set(fileDirectory, resolvedPath);\n\n return resolvedPath;\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: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n // The metafile lists every bundled input, which the transpile cache uses to\n // invalidate when an imported file changes (the entry itself is keyed by hash).\n metafile: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n 'import.meta.env': 'process.env',\n },\n});\n\n/** Fingerprint of a bundled input file, used to detect changes without re-reading it. */\ntype TranspileCacheInput = {\n path: string;\n mtimeMs: number;\n size: number;\n};\n\ntype TranspileCacheEntry = {\n /** Hash of the entry file's source code. */\n codeHash: string;\n /** Hash of the build options, so different option sets don't collide. */\n optionsKey: string;\n /** The transpiled CJS output. */\n output: string;\n /** Fingerprints of every non-entry input bundled into the output. */\n inputs: TranspileCacheInput[];\n};\n\n/**\n * In-memory cache of transpiled outputs keyed by entry file path (one entry\n * per file, so re-transpilations replace rather than accumulate).\n * The entry file is validated by content hash; bundled relative imports are\n * validated by mtime + size so an edited dependency invalidates the cache.\n */\nconst transpileCache = new Map<string, TranspileCacheEntry>();\n\nconst isInputUnchanged = (input: TranspileCacheInput): boolean => {\n try {\n const stats = statSync(input.path);\n return stats.mtimeMs === input.mtimeMs && stats.size === input.size;\n } catch {\n // File removed or unreadable — treat as changed\n return false;\n }\n};\n\nconst getCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string\n): string | undefined => {\n const cacheEntry = transpileCache.get(filePath);\n\n if (!cacheEntry) return undefined;\n if (cacheEntry.codeHash !== codeHash) return undefined;\n if (cacheEntry.optionsKey !== optionsKey) return undefined;\n if (!cacheEntry.inputs.every(isInputUnchanged)) return undefined;\n\n return cacheEntry.output;\n};\n\n/**\n * Extracts the fingerprints of every bundled input from the esbuild metafile.\n * Returns `undefined` when an input cannot be fingerprinted (the result should\n * then not be cached, as invalidation would be unreliable).\n */\nconst getInputFingerprints = (\n metafile: Metafile | undefined,\n entryFilePath: string\n): TranspileCacheInput[] | undefined => {\n if (!metafile) return undefined;\n\n const resolvedEntryFilePath = resolve(entryFilePath);\n const inputs: TranspileCacheInput[] = [];\n\n for (const inputPath of Object.keys(metafile.inputs)) {\n // The entry itself is provided via stdin and validated by content hash.\n // esbuild labels it \"<stdin>\", or with the sourcefile path when set.\n if (inputPath === '<stdin>') continue;\n // Virtual modules from plugins (e.g. \"plugin:...\") cannot be fingerprinted\n if (inputPath.includes(':') && !isAbsolute(inputPath)) return undefined;\n\n const absoluteInputPath = isAbsolute(inputPath)\n ? inputPath\n : resolve(process.cwd(), inputPath);\n\n if (absoluteInputPath === resolvedEntryFilePath) continue;\n\n try {\n const stats = statSync(absoluteInputPath);\n inputs.push({\n path: absoluteInputPath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n });\n } catch {\n return undefined;\n }\n }\n\n return inputs;\n};\n\nconst setCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string,\n moduleResult: BuildResult,\n output: string\n): void => {\n const inputs = getInputFingerprints(moduleResult.metafile, filePath);\n\n // Without a usable metafile the cache cannot be invalidated reliably — skip\n if (!inputs) return;\n\n transpileCache.set(filePath, { codeHash, optionsKey, output, inputs });\n};\n\n/** Clears the in-memory transpilation cache (mainly for tests). */\nexport const clearTranspileCache = (): void => {\n transpileCache.clear();\n tsConfigPathCache.clear();\n};\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;\n\n // esbuild's worker thread service calls `new Worker(__filename, …)` on first use.\n // In Vite's SSR module runner the SSR-optimised chunk is ESM and __filename is\n // never declared (confirmed: accessing it throws ReferenceError, not undefined).\n // Because there is no local declaration the bare `__filename` lookup falls\n // through to globalThis, so we set it there to esbuild's own CJS entry-point –\n // the exact path esbuild would use if it were loaded in a normal CJS context.\n //\n // IMPORTANT: We save/restore the globals so this temporary shim does not leak\n // to other Vite plugins (e.g. `@vitejs/plugin-react-swc`) that check\n // `typeof __dirname !== \"undefined\"` to locate their own assets.\n const g = globalThis as Record<string, unknown>;\n const hadFilename = typeof g.__filename === 'string';\n const prevFilename = g.__filename;\n const prevDirname = g.__dirname;\n\n if (!hadFilename) {\n try {\n const _require = createRequire(import.meta.url);\n const esbuildEntry = _require.resolve('esbuild');\n g.__filename = esbuildEntry;\n g.__dirname = dirname(esbuildEntry);\n } catch {\n // Best-effort: if esbuild can't be resolved the caller's catch handles it\n }\n }\n\n let moduleResult: BuildResult;\n try {\n moduleResult = esbuildBuildSync({\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 ...buildOptions,\n });\n } finally {\n // Always restore the previous values so the globals don't linger.\n if (!hadFilename) {\n if (prevFilename === undefined) {\n // biome-ignore lint/performance/noDelete: the global must be truly absent — assigning undefined would leave the key present and break `typeof __filename` checks in other tools\n delete g.__filename;\n } else {\n g.__filename = prevFilename;\n }\n if (prevDirname === undefined) {\n // biome-ignore lint/performance/noDelete: same as __filename above\n delete g.__dirname;\n } else {\n g.__dirname = prevDirname;\n }\n }\n }\n\n const moduleResultString = moduleResult!.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult!,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n // A one-shot build() releases its Go-side resources on completion and costs a\n // single service round-trip (context()+rebuild()+dispose() costs three).\n const esbuildBuild = esbuildInstance?.build ?? build;\n\n const moduleResult = await esbuildBuild({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath),\n sourcefile: filePath,\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,oCAAoB,IAAI,IAAgC;AAE9D,MAAM,mBAAmB,aAAyC;CAChE,MAAM,gBAAgB,QAAQ,QAAQ;CAEtC,IAAI,kBAAkB,IAAI,aAAa,GACrC,OAAO,kBAAkB,IAAI,aAAa;CAG5C,IAAI;CACJ,IAAI;E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O;IACL,UAAU;IACV;IACA,YAAY,QAAQ,QAAQ;IAC5B,YAAY;GACd;GACA,GAAG,yBAAyB,QAAQ;GACpC,GAAG;EACL,CAAC;CACH,UAAU;EAER,IAAI,CAAC,aAAa;GAChB,IAAI,iBAAiB,QAEnB,OAAO,EAAE;QAET,EAAE,aAAa;GAEjB,IAAI,gBAAgB,QAElB,OAAO,EAAE;QAET,EAAE,YAAY;EAElB;CACF;CAEA,MAAM,qBAAqB,aAAc,cAAc,EAAE,EAAE;CAE3D,IAAI,OAAO,uBAAuB,UAChC,uBACE,UACA,UACA,YACA,cACA,kBACF;CAGF,OAAO;AACT;AAEA,MAAa,mBAAmB,OAC9B,MACA,UACA,YACgC;CAChC,MAAM,YAAY,QAAQ,QAAQ;CAClC,MAAM,SAAS,UAAU,SAAS;CAElC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,WAAW,CAAC;CAEzD,MAAM,WAAW,aAAa,CAAC,IAAI,CAAC;CACpC,MAAM,aAAa,aAAa,CAAC,YAAY,CAAC;CAE9C,MAAM,eAAe,uBAAuB,UAAU,UAAU,UAAU;CAC1E,IAAI,OAAO,iBAAiB,UAAU,OAAO;CAM7C,MAAM,eAAe,OAFA,iBAAiB,SAAS,MAER,CAAC;EACtC,OAAO;GACL,UAAU;GACV;GACA,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC;CAED,MAAM,qBAAqB,aAAa,cAAc,EAAE,EAAE;CAE1D,IAAI,OAAO,uBAAuB,UAChC,uBACE,UACA,UACA,YACA,cACA,kBACF;CAGF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"transpileTSToCJS.mjs","names":[],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, extname, isAbsolute, join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Metafile,\n} from 'esbuild';\nimport { computeKeyId } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nexport type TranspileOptions = BuildOptions & {\n /**\n * Optional custom esbuild instance to use for transpilation.\n * Useful in environments (e.g. VS Code extensions) where the bundled\n * esbuild binary may not match the host platform.\n * When provided, its `buildSync`/`build` methods are used instead of\n * the ones imported from the `esbuild` package.\n */\n esbuildInstance?: typeof import('esbuild');\n};\n\n/**\n * Cache of resolved tsconfig paths keyed by the file's directory.\n * Avoids re-walking to package.json + existsSync on every transpilation.\n */\nconst tsConfigPathCache = new Map<string, string | undefined>();\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const fileDirectory = dirname(filePath);\n\n if (tsConfigPathCache.has(fileDirectory)) {\n return tsConfigPathCache.get(fileDirectory);\n }\n\n let resolvedPath: string | undefined;\n try {\n const tsconfigPath = join(\n getPackageJsonPath(fileDirectory).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n resolvedPath = existsSync(tsconfigPath) ? tsconfigPath : undefined;\n } catch {\n // No package.json found up the tree — transpile without a tsconfig\n resolvedPath = undefined;\n }\n\n tsConfigPathCache.set(fileDirectory, resolvedPath);\n\n return resolvedPath;\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: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n // The metafile lists every bundled input, which the transpile cache uses to\n // invalidate when an imported file changes (the entry itself is keyed by hash).\n metafile: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n 'import.meta.env': 'process.env',\n },\n});\n\n/** Fingerprint of a bundled input file, used to detect changes without re-reading it. */\ntype TranspileCacheInput = {\n path: string;\n mtimeMs: number;\n size: number;\n};\n\ntype TranspileCacheEntry = {\n /** Hash of the entry file's source code. */\n codeHash: string;\n /** Hash of the build options, so different option sets don't collide. */\n optionsKey: string;\n /** The transpiled CJS output. */\n output: string;\n /** Fingerprints of every non-entry input bundled into the output. */\n inputs: TranspileCacheInput[];\n};\n\n/**\n * In-memory cache of transpiled outputs keyed by entry file path (one entry\n * per file, so re-transpilations replace rather than accumulate).\n * The entry file is validated by content hash; bundled relative imports are\n * validated by mtime + size so an edited dependency invalidates the cache.\n */\nconst transpileCache = new Map<string, TranspileCacheEntry>();\n\nconst isInputUnchanged = (input: TranspileCacheInput): boolean => {\n try {\n const stats = statSync(input.path);\n return stats.mtimeMs === input.mtimeMs && stats.size === input.size;\n } catch {\n // File removed or unreadable — treat as changed\n return false;\n }\n};\n\nconst getCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string\n): string | undefined => {\n const cacheEntry = transpileCache.get(filePath);\n\n if (!cacheEntry) return undefined;\n if (cacheEntry.codeHash !== codeHash) return undefined;\n if (cacheEntry.optionsKey !== optionsKey) return undefined;\n if (!cacheEntry.inputs.every(isInputUnchanged)) return undefined;\n\n return cacheEntry.output;\n};\n\n/**\n * Extracts the fingerprints of every bundled input from the esbuild metafile.\n * Returns `undefined` when an input cannot be fingerprinted (the result should\n * then not be cached, as invalidation would be unreliable).\n */\nconst getInputFingerprints = (\n metafile: Metafile | undefined,\n entryFilePath: string\n): TranspileCacheInput[] | undefined => {\n if (!metafile) return undefined;\n\n const resolvedEntryFilePath = resolve(entryFilePath);\n const inputs: TranspileCacheInput[] = [];\n\n for (const inputPath of Object.keys(metafile.inputs)) {\n // The entry itself is provided via stdin and validated by content hash.\n // esbuild labels it \"<stdin>\", or with the sourcefile path when set.\n if (inputPath === '<stdin>') continue;\n // Virtual modules from plugins (e.g. \"plugin:...\") cannot be fingerprinted\n if (inputPath.includes(':') && !isAbsolute(inputPath)) return undefined;\n\n const absoluteInputPath = isAbsolute(inputPath)\n ? inputPath\n : resolve(process.cwd(), inputPath);\n\n if (absoluteInputPath === resolvedEntryFilePath) continue;\n\n try {\n const stats = statSync(absoluteInputPath);\n inputs.push({\n path: absoluteInputPath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n });\n } catch {\n return undefined;\n }\n }\n\n return inputs;\n};\n\nconst setCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string,\n moduleResult: BuildResult,\n output: string\n): void => {\n const inputs = getInputFingerprints(moduleResult.metafile, filePath);\n\n // Without a usable metafile the cache cannot be invalidated reliably — skip\n if (!inputs) return;\n\n transpileCache.set(filePath, { codeHash, optionsKey, output, inputs });\n};\n\n/** Clears the in-memory transpilation cache (mainly for tests). */\nexport const clearTranspileCache = (): void => {\n transpileCache.clear();\n tsConfigPathCache.clear();\n};\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;\n\n // esbuild's worker thread service calls `new Worker(__filename, …)` on first use.\n // In Vite's SSR module runner the SSR-optimised chunk is ESM and __filename is\n // never declared (confirmed: accessing it throws ReferenceError, not undefined).\n // Because there is no local declaration the bare `__filename` lookup falls\n // through to globalThis, so we set it there to esbuild's own CJS entry-point –\n // the exact path esbuild would use if it were loaded in a normal CJS context.\n //\n // IMPORTANT: We save/restore the globals so this temporary shim does not leak\n // to other Vite plugins (e.g. `@vitejs/plugin-react-swc`) that check\n // `typeof __dirname !== \"undefined\"` to locate their own assets.\n const g = globalThis as Record<string, unknown>;\n const hadFilename = typeof g.__filename === 'string';\n const prevFilename = g.__filename;\n const prevDirname = g.__dirname;\n\n if (!hadFilename) {\n try {\n const _require = createRequire(import.meta.url);\n const esbuildEntry = _require.resolve('esbuild');\n g.__filename = esbuildEntry;\n g.__dirname = dirname(esbuildEntry);\n } catch {\n // Best-effort: if esbuild can't be resolved the caller's catch handles it\n }\n }\n\n let moduleResult: BuildResult;\n try {\n moduleResult = esbuildBuildSync({\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 ...buildOptions,\n });\n } finally {\n // Always restore the previous values so the globals don't linger.\n if (!hadFilename) {\n if (prevFilename === undefined) {\n // oxlint-disable-next-line typescript/no-dynamic-delete -- the global must be truly absent — assigning undefined would leave the key present and break `typeof __filename` checks in other tools\n delete g.__filename;\n } else {\n g.__filename = prevFilename;\n }\n if (prevDirname === undefined) {\n // oxlint-disable-next-line typescript/no-dynamic-delete -- same as __filename above\n delete g.__dirname;\n } else {\n g.__dirname = prevDirname;\n }\n }\n }\n\n const moduleResultString = moduleResult!.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult!,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n // A one-shot build() releases its Go-side resources on completion and costs a\n // single service round-trip (context()+rebuild()+dispose() costs three).\n const esbuildBuild = esbuildInstance?.build ?? build;\n\n const moduleResult = await esbuildBuild({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath),\n sourcefile: filePath,\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,oCAAoB,IAAI,IAAgC;AAE9D,MAAM,mBAAmB,aAAyC;CAChE,MAAM,gBAAgB,QAAQ,QAAQ;CAEtC,IAAI,kBAAkB,IAAI,aAAa,GACrC,OAAO,kBAAkB,IAAI,aAAa;CAG5C,IAAI;CACJ,IAAI;EACF,MAAM,eAAe,KACnB,mBAAmB,aAAa,CAAC,CAAC,SAClC,eACF;EAGA,eAAe,WAAW,YAAY,IAAI,eAAe;CAC3D,QAAQ;EAEN,eAAe;CACjB;CAEA,kBAAkB,IAAI,eAAe,YAAY;CAEjD,OAAO;AACT;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,QAAQ;CAGR,UAAU;CACV,UAAU,gBAAgB,QAAQ;CAClC,QAAQ;EACN,mBAAmB,KAAK,UAAU,cAAc,QAAQ,CAAC,CAAC,IAAI;EAC9D,mBAAmB;CACrB;AACF;;;;;;;AA0BA,MAAM,iCAAiB,IAAI,IAAiC;AAE5D,MAAM,oBAAoB,UAAwC;CAChE,IAAI;EACF,MAAM,QAAQ,SAAS,MAAM,IAAI;EACjC,OAAO,MAAM,YAAY,MAAM,WAAW,MAAM,SAAS,MAAM;CACjE,QAAQ;EAEN,OAAO;CACT;AACF;AAEA,MA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A,iBAAiB,SAAS,MAER,CAAC;EACtC,OAAO;GACL,UAAU;GACV;GACA,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC;CAED,MAAM,qBAAqB,aAAa,cAAc,EAAE,EAAE;CAE1D,IAAI,OAAO,uBAAuB,UAChC,uBACE,UACA,UACA,YACA,cACA,kBACF;CAGF,OAAO;AACT"}
|
package/dist/esm/logger.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BEIGE, BLUE, GREEN, GREY, GREY_DARK, GREY_LIGHT, RED, RESET, WHITE } from "./colors.mjs";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// src/logger.ts
|
|
4
4
|
let loggerPrefix;
|
|
5
5
|
const setPrefix = (prefix) => {
|
|
6
6
|
loggerPrefix = prefix;
|
|
@@ -135,6 +135,5 @@ const x = colorize("✗", RED);
|
|
|
135
135
|
const v = colorize("✓", GREEN);
|
|
136
136
|
const clock = colorize("⏲", BLUE);
|
|
137
137
|
|
|
138
|
-
//#endregion
|
|
139
138
|
export { clock, colon, colorize, colorizeKey, colorizeLocales, colorizeNumber, colorizeObject, colorizePath, getAppLogger, getPrefix, logger, removeColor, setPrefix, spinnerFrames, v, x };
|
|
140
139
|
//# sourceMappingURL=logger.mjs.map
|
package/dist/esm/logger.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.mjs","names":[],"sources":["../../src/logger.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type {\n CustomIntlayerConfig,\n IntlayerConfig,\n} from '@intlayer/types/config';\nimport type * as ANSIColorsTypes from './colors';\nimport {\n BEIGE,\n BLUE,\n GREEN,\n GREY,\n GREY_DARK,\n GREY_LIGHT,\n RED,\n RESET,\n WHITE,\n} from './colors';\n\nexport type ANSIColorsType =\n (typeof ANSIColorsTypes)[keyof typeof ANSIColorsTypes];\n\nexport type Details = {\n isVerbose?: boolean;\n level?: 'info' | 'warn' | 'error' | 'debug';\n config?: CustomIntlayerConfig['log'];\n};\n\nexport type Logger = (content: any, details?: Details) => void;\n\nlet loggerPrefix: string | undefined;\n\nexport const setPrefix = (prefix: string | undefined) => {\n loggerPrefix = prefix;\n};\n\nexport const getPrefix = (configPrefix?: string): string | undefined => {\n if (typeof loggerPrefix !== 'undefined') {\n return loggerPrefix;\n }\n\n return configPrefix;\n};\n\nexport const logger: Logger = (content, details) => {\n const config = details?.config ?? {};\n const mode = config.mode ?? 'default';\n\n if (mode === 'disabled' || (details?.isVerbose && mode !== 'verbose')) return;\n\n const prefix = getPrefix(config.prefix);\n const flatContent = prefix ? [prefix, ...[content].flat()] : [content].flat();\n const level = details?.level ?? 'info';\n\n const logMethod =\n config[level] ?? console[level] ?? config.log ?? console.log;\n\n logMethod(...flatContent);\n};\n\nexport const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n/**\n * The appLogger function takes the logger and merges it with the configuration from the intlayer config file.\n * It allows overriding the default configuration by passing a config object in the details parameter.\n * The configuration is merged with the default configuration from the intlayer config file.\n */\nexport const getAppLogger =\n (configuration?: Pick<IntlayerConfig, 'log'>, globalDetails?: Details) =>\n (content: any, details?: Details) =>\n logger(content, {\n ...(details ?? {}),\n config: {\n ...configuration?.log,\n ...globalDetails?.config,\n ...(details?.config ?? {}),\n },\n });\n\nexport const colorize = (\n string: string,\n color?: ANSIColorsType,\n reset?: boolean | ANSIColorsType\n): string =>\n color && typeof window === 'undefined'\n ? `${color}${string}${reset ? (typeof reset === 'boolean' ? RESET : reset) : RESET}`\n : string;\n\nexport const colorizeLocales = (\n locales: Locale | Locale[],\n color: ANSIColorsType = GREEN,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [locales]\n .flat()\n .map((locale) => colorize(locale, color, reset))\n .join(`, `);\n\nexport const colorizeKey = (\n keyPath: string | string[],\n color: ANSIColorsType = BEIGE,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [keyPath]\n .flat()\n .map((key) => colorize(key, color, reset))\n .join(`, `);\n\nexport const colorizePath = (\n path: string | string[],\n color: ANSIColorsType = GREY,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [path]\n .flat()\n .map((path) => colorize(path, color, reset))\n .join(`, `);\n\nexport const colorizeNumber = (\n number: number | string,\n options: Partial<Record<Intl.LDMLPluralRule, ANSIColorsType>> = {\n zero: BLUE,\n one: BLUE,\n two: BLUE,\n few: BLUE,\n many: BLUE,\n other: BLUE,\n }\n): string => {\n if (number === 0 || number === '0') {\n const color = options.zero ?? GREEN;\n return colorize(number.toString(), color);\n }\n\n // Kept inside the function. Top-level instantiation of classes/APIs\n // is treated as a side-effect and prevents tree-shaking if the function is unused.\n const rule = new Intl.PluralRules('en').select(Number(number));\n const color = options[rule];\n return colorize(number.toString(), color);\n};\n\nexport const colorizeObject = (\n obj: any,\n indentLevel = 0,\n indentSize = 2,\n key?: string\n): string => {\n const indent = ' '.repeat(indentLevel * indentSize);\n const nextIndent = ' '.repeat((indentLevel + 1) * indentSize);\n\n if (obj === null) {\n return colorize('null', BLUE);\n }\n\n if (typeof obj === 'boolean') {\n return colorize(obj.toString(), BLUE);\n }\n\n if (typeof obj === 'number') {\n return colorize(obj.toString(), BLUE);\n }\n\n if (typeof obj === 'string') {\n const isDateString = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(obj);\n const isUrl = obj.startsWith('http://') || obj.startsWith('https://');\n const isGlob = obj.includes('*') || obj.includes('?') || obj.includes('{');\n const isPath =\n obj.startsWith('/') ||\n obj.startsWith('./') ||\n obj.startsWith('../') ||\n /\\.[a-zA-Z0-9]{2,5}$/.test(obj);\n const isSecret =\n /^[0-9a-fA-F]{24,}$/.test(obj) || (obj.length >= 40 && !/\\s/.test(obj));\n const hasSpaces = /\\s/.test(obj);\n\n if (isDateString) return colorize(`\"${obj}\"`, BEIGE);\n if (isUrl) return colorize(`\"${obj}\"`, GREY_DARK);\n if (isGlob) return colorize(`\"${obj}\"`, GREY);\n if (isPath) return colorize(`\"${obj}\"`, GREY_DARK);\n if (isSecret) return colorize(`\"${obj}\"`, GREY);\n if (hasSpaces) return colorize(`\"${obj}\"`, WHITE);\n return colorize(`\"${obj}\"`, BLUE);\n }\n\n if (Array.isArray(obj)) {\n if (obj.length === 0) {\n return '[]';\n }\n const items = obj\n .map(\n (item) =>\n `${nextIndent}${colorizeObject(item, indentLevel + 1, indentSize, key)}`\n )\n .join(',\\n');\n return `[\\n${items}\\n${indent}]`;\n }\n\n if (typeof obj === 'object') {\n const keys = Object.keys(obj);\n\n if (keys.length === 0) {\n return '{}';\n }\n\n const fields = keys\n .map((key) => {\n const coloredKey = colorize(`\"${key}\"`, GREY_LIGHT);\n const value = obj[key];\n const coloredValue = colorizeObject(\n value,\n indentLevel + 1,\n indentSize,\n key\n );\n return `${nextIndent}${coloredKey}: ${coloredValue}`;\n })\n .join(',\\n');\n return `{\\n${fields}\\n${indent}}`;\n }\n\n return colorize(String(obj), GREY);\n};\n\nexport const removeColor = (text: string) =>\n // biome-ignore lint/suspicious/noControlCharactersInRegex: we need to remove the color codes\n text.replace(/\\x1b\\[[0-9;]*m/g, '');\n\nconst getLength = (length: number | number[] | string | string[]): number => {\n let value: number = 0;\n if (typeof length === 'number') {\n value = length;\n }\n if (typeof length === 'string') {\n value = length.length;\n }\n if (\n Array.isArray(length) &&\n length.every((locale) => typeof locale === 'string')\n ) {\n value = Math.max(...length.map((str) => str.length));\n }\n if (\n Array.isArray(length) &&\n length.every((locale) => typeof locale === 'number')\n ) {\n value = Math.max(...length);\n }\n return Math.max(value, 0);\n};\n\nconst defaultColonOptions = {\n colSize: 0,\n minSize: 0,\n maxSize: Infinity,\n pad: 'right',\n padChar: '0',\n};\n\n/**\n * Create a string of spaces of a given length.\n *\n * @param colSize - The length of the string to create.\n * @returns A string of spaces.\n */\nexport const colon = (\n text: string | string[],\n options?: {\n colSize?: number | number[] | string | string[];\n minSize?: number;\n maxSize?: number;\n pad?: 'left' | 'right';\n padChar?: string;\n }\n): string =>\n [text]\n .flat()\n .map((text) => {\n const { colSize, minSize, maxSize, pad } = {\n ...defaultColonOptions,\n ...(options ?? {}),\n };\n\n const length = getLength(colSize);\n const spacesLength = Math.max(\n minSize!,\n Math.min(maxSize!, length - removeColor(text).length)\n );\n\n if (pad === 'left') {\n return `${' '.repeat(spacesLength)}${text}`;\n }\n\n return `${text}${' '.repeat(spacesLength)}`;\n })\n .join('');\n\nexport const x = colorize('✗', RED);\nexport const v = colorize('✓', GREEN);\nexport const clock = colorize('⏲', BLUE);\n"],"mappings":";;;AA6BA,IAAI;AAEJ,MAAa,aAAa,WAA+B;CACvD,eAAe;AACjB;AAEA,MAAa,aAAa,iBAA8C;CACtE,IAAI,OAAO,iBAAiB,aAC1B,OAAO;CAGT,OAAO;AACT;AAEA,MAAa,UAAkB,SAAS,YAAY;CAClD,MAAM,SAAS,SAAS,UAAU,CAAC;CACnC,MAAM,OAAO,OAAO,QAAQ;CAE5B,IAAI,SAAS,cAAe,SAAS,aAAa,SAAS,WAAY;CAEvE,MAAM,SAAS,UAAU,OAAO,MAAM;CACtC,MAAM,cAAc,SAAS,CAAC,QAAQ,GAAG,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK;CAC5E,MAAM,QAAQ,SAAS,SAAS;CAKhC,CAFE,OAAO,UAAU,QAAQ,UAAU,OAAO,OAAO,QAAQ,IAElD,CAAC,GAAG,WAAW;AAC1B;AAEA,MAAa,gBAAgB;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG;;;;;;AAO9E,MAAa,gBACV,eAA6C,mBAC7C,SAAc,YACb,OAAO,SAAS;CACd,GAAI,WAAW,CAAC;CAChB,QAAQ;EACN,GAAG,eAAe;EAClB,GAAG,eAAe;EAClB,GAAI,SAAS,UAAU,CAAC;C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,CAAC,CAAC,CACD,KAAK,EAAE;AAEZ,MAAa,IAAI,SAAS,KAAK,GAAG;AAClC,MAAa,IAAI,SAAS,KAAK,KAAK;AACpC,MAAa,QAAQ,SAAS,KAAK,IAAI"}
|
|
1
|
+
{"version":3,"file":"logger.mjs","names":[],"sources":["../../src/logger.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type {\n CustomIntlayerConfig,\n IntlayerConfig,\n} from '@intlayer/types/config';\nimport type * as ANSIColorsTypes from './colors';\nimport {\n BEIGE,\n BLUE,\n GREEN,\n GREY,\n GREY_DARK,\n GREY_LIGHT,\n RED,\n RESET,\n WHITE,\n} from './colors';\n\nexport type ANSIColorsType =\n (typeof ANSIColorsTypes)[keyof typeof ANSIColorsTypes];\n\nexport type Details = {\n isVerbose?: boolean;\n level?: 'info' | 'warn' | 'error' | 'debug';\n config?: CustomIntlayerConfig['log'];\n};\n\nexport type Logger = (content: any, details?: Details) => void;\n\nlet loggerPrefix: string | undefined;\n\nexport const setPrefix = (prefix: string | undefined) => {\n loggerPrefix = prefix;\n};\n\nexport const getPrefix = (configPrefix?: string): string | undefined => {\n if (typeof loggerPrefix !== 'undefined') {\n return loggerPrefix;\n }\n\n return configPrefix;\n};\n\nexport const logger: Logger = (content, details) => {\n const config = details?.config ?? {};\n const mode = config.mode ?? 'default';\n\n if (mode === 'disabled' || (details?.isVerbose && mode !== 'verbose')) return;\n\n const prefix = getPrefix(config.prefix);\n const flatContent = prefix ? [prefix, ...[content].flat()] : [content].flat();\n const level = details?.level ?? 'info';\n\n const logMethod =\n config[level] ?? console[level] ?? config.log ?? console.log;\n\n logMethod(...flatContent);\n};\n\nexport const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n/**\n * The appLogger function takes the logger and merges it with the configuration from the intlayer config file.\n * It allows overriding the default configuration by passing a config object in the details parameter.\n * The configuration is merged with the default configuration from the intlayer config file.\n */\nexport const getAppLogger =\n (configuration?: Pick<IntlayerConfig, 'log'>, globalDetails?: Details) =>\n (content: any, details?: Details) =>\n logger(content, {\n ...(details ?? {}),\n config: {\n ...configuration?.log,\n ...globalDetails?.config,\n ...(details?.config ?? {}),\n },\n });\n\nexport const colorize = (\n string: string,\n color?: ANSIColorsType,\n reset?: boolean | ANSIColorsType\n): string =>\n color && typeof window === 'undefined'\n ? `${color}${string}${reset ? (typeof reset === 'boolean' ? RESET : reset) : RESET}`\n : string;\n\nexport const colorizeLocales = (\n locales: Locale | Locale[],\n color: ANSIColorsType = GREEN,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [locales]\n .flat()\n .map((locale) => colorize(locale, color, reset))\n .join(`, `);\n\nexport const colorizeKey = (\n keyPath: string | string[],\n color: ANSIColorsType = BEIGE,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [keyPath]\n .flat()\n .map((key) => colorize(key, color, reset))\n .join(`, `);\n\nexport const colorizePath = (\n path: string | string[],\n color: ANSIColorsType = GREY,\n reset: boolean | ANSIColorsType = RESET\n) =>\n [path]\n .flat()\n .map((path) => colorize(path, color, reset))\n .join(`, `);\n\nexport const colorizeNumber = (\n number: number | string,\n options: Partial<Record<Intl.LDMLPluralRule, ANSIColorsType>> = {\n zero: BLUE,\n one: BLUE,\n two: BLUE,\n few: BLUE,\n many: BLUE,\n other: BLUE,\n }\n): string => {\n if (number === 0 || number === '0') {\n const color = options.zero ?? GREEN;\n return colorize(number.toString(), color);\n }\n\n // Kept inside the function. Top-level instantiation of classes/APIs\n // is treated as a side-effect and prevents tree-shaking if the function is unused.\n const rule = new Intl.PluralRules('en').select(Number(number));\n const color = options[rule];\n return colorize(number.toString(), color);\n};\n\nexport const colorizeObject = (\n obj: any,\n indentLevel = 0,\n indentSize = 2,\n key?: string\n): string => {\n const indent = ' '.repeat(indentLevel * indentSize);\n const nextIndent = ' '.repeat((indentLevel + 1) * indentSize);\n\n if (obj === null) {\n return colorize('null', BLUE);\n }\n\n if (typeof obj === 'boolean') {\n return colorize(obj.toString(), BLUE);\n }\n\n if (typeof obj === 'number') {\n return colorize(obj.toString(), BLUE);\n }\n\n if (typeof obj === 'string') {\n const isDateString = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(obj);\n const isUrl = obj.startsWith('http://') || obj.startsWith('https://');\n const isGlob = obj.includes('*') || obj.includes('?') || obj.includes('{');\n const isPath =\n obj.startsWith('/') ||\n obj.startsWith('./') ||\n obj.startsWith('../') ||\n /\\.[a-zA-Z0-9]{2,5}$/.test(obj);\n const isSecret =\n /^[0-9a-fA-F]{24,}$/.test(obj) || (obj.length >= 40 && !/\\s/.test(obj));\n const hasSpaces = /\\s/.test(obj);\n\n if (isDateString) return colorize(`\"${obj}\"`, BEIGE);\n if (isUrl) return colorize(`\"${obj}\"`, GREY_DARK);\n if (isGlob) return colorize(`\"${obj}\"`, GREY);\n if (isPath) return colorize(`\"${obj}\"`, GREY_DARK);\n if (isSecret) return colorize(`\"${obj}\"`, GREY);\n if (hasSpaces) return colorize(`\"${obj}\"`, WHITE);\n return colorize(`\"${obj}\"`, BLUE);\n }\n\n if (Array.isArray(obj)) {\n if (obj.length === 0) {\n return '[]';\n }\n const items = obj\n .map(\n (item) =>\n `${nextIndent}${colorizeObject(item, indentLevel + 1, indentSize, key)}`\n )\n .join(',\\n');\n return `[\\n${items}\\n${indent}]`;\n }\n\n if (typeof obj === 'object') {\n const keys = Object.keys(obj);\n\n if (keys.length === 0) {\n return '{}';\n }\n\n const fields = keys\n .map((key) => {\n const coloredKey = colorize(`\"${key}\"`, GREY_LIGHT);\n const value = obj[key];\n const coloredValue = colorizeObject(\n value,\n indentLevel + 1,\n indentSize,\n key\n );\n return `${nextIndent}${coloredKey}: ${coloredValue}`;\n })\n .join(',\\n');\n return `{\\n${fields}\\n${indent}}`;\n }\n\n return colorize(String(obj), GREY);\n};\n\nexport const removeColor = (text: string) =>\n // oxlint-disable-next-line no-control-regex -- we need to remove the color codes\n text.replace(/\\x1b\\[[0-9;]*m/g, '');\n\nconst getLength = (length: number | number[] | string | string[]): number => {\n let value: number = 0;\n if (typeof length === 'number') {\n value = length;\n }\n if (typeof length === 'string') {\n value = length.length;\n }\n if (\n Array.isArray(length) &&\n length.every((locale) => typeof locale === 'string')\n ) {\n value = Math.max(...length.map((str) => str.length));\n }\n if (\n Array.isArray(length) &&\n length.every((locale) => typeof locale === 'number')\n ) {\n value = Math.max(...length);\n }\n return Math.max(value, 0);\n};\n\nconst defaultColonOptions = {\n colSize: 0,\n minSize: 0,\n maxSize: Infinity,\n pad: 'right',\n padChar: '0',\n};\n\n/**\n * Create a string of spaces of a given length.\n *\n * @param colSize - The length of the string to create.\n * @returns A string of spaces.\n */\nexport const colon = (\n text: string | string[],\n options?: {\n colSize?: number | number[] | string | string[];\n minSize?: number;\n maxSize?: number;\n pad?: 'left' | 'right';\n padChar?: string;\n }\n): string =>\n [text]\n .flat()\n .map((text) => {\n const { colSize, minSize, maxSize, pad } = {\n ...defaultColonOptions,\n ...(options ?? {}),\n };\n\n const length = getLength(colSize);\n const spacesLength = Math.max(\n minSize!,\n Math.min(maxSize!, length - removeColor(text).length)\n );\n\n if (pad === 'left') {\n return `${' '.repeat(spacesLength)}${text}`;\n }\n\n return `${text}${' '.repeat(spacesLength)}`;\n })\n .join('');\n\nexport const x = colorize('✗', RED);\nexport const v = colorize('✓', GREEN);\nexport const clock = colorize('⏲', BLUE);\n"],"mappings":";;;AA6BA,IAAI;AAEJ,MAAa,aAAa,WAA+B;CACvD,eAAe;AACjB;AAEA,MAAa,aAAa,iBAA8C;CACtE,IAAI,OAAO,iBAAiB,aAC1B,OAAO;CAGT,OAAO;AACT;AAEA,MAAa,UAAkB,SAAS,YAAY;CAClD,MAAM,SAAS,SAAS,UAAU,CAAC;CACnC,MAAM,OAAO,OAAO,QAAQ;CAE5B,IAAI,SAAS,cAAe,SAAS,aAAa,SAAS,WAAY;CAEvE,MAAM,SAAS,UAAU,OAAO,MAAM;CACtC,MAA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MAAM,sBAAsB;CAC1B,SAAS;CACT,SAAS;CACT,SAAS;CACT,KAAK;CACL,SAAS;AACX;;;;;;;AAQA,MAAa,SACX,MACA,YAQA,CAAC,IAAI,CAAC,CACH,KAAK,CAAC,CACN,KAAK,SAAS;CACb,MAAM,EAAE,SAAS,SAAS,SAAS,QAAQ;EACzC,GAAG;EACH,GAAI,WAAW,CAAC;CAClB;CAEA,MAAM,SAAS,UAAU,OAAO;CAChC,MAAM,eAAe,KAAK,IACxB,SACA,KAAK,IAAI,SAAU,SAAS,YAAY,IAAI,CAAC,CAAC,MAAM,CACtD;CAEA,IAAI,QAAQ,QACV,OAAO,GAAG,IAAI,OAAO,YAAY,IAAI;CAGvC,OAAO,GAAG,OAAO,IAAI,OAAO,YAAY;AAC1C,CAAC,CAAC,CACD,KAAK,EAAE;AAEZ,MAAa,IAAI,SAAS,KAAK,GAAG;AAClC,MAAa,IAAI,SAAS,KAAK,KAAK;AACpC,MAAa,QAAQ,SAAS,KAAK,IAAI"}
|
package/dist/esm/node.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, extractBrowserConfiguration } from "./configFile/buildBrowserConfiguration.mjs";
|
|
2
|
-
import { aiSchema, analyticsSchema, buildSchema, compilerSchema, contentSchema, cookiesAttributesSchema, dictionarySchema, editorSchema, internationalizationSchema, intlayerConfigSchema, intlayerConfigSchemaParseContext, logSchema, rewriteObjectSchema, rewriteRuleSchema, rewriteRulesSchema, routingSchema, storageAttributesSchema, storageSchema, systemSchema } from "./configFile/configurationSchema.mjs";
|
|
3
2
|
import { buildConfigurationFields } from "./configFile/buildConfigurationFields.mjs";
|
|
3
|
+
import { aiSchema, analyticsSchema, buildSchema, compilerSchema, contentSchema, cookiesAttributesSchema, dictionarySchema, editorSchema, internationalizationSchema, intlayerConfigSchema, intlayerConfigSchemaParseContext, logSchema, rewriteObjectSchema, rewriteRuleSchema, rewriteRulesSchema, routingSchema, storageAttributesSchema, storageSchema, systemSchema } from "./configFile/configurationSchema.mjs";
|
|
4
4
|
import { EDITOR_SERVER_PORT_ENV_VAR, applyEditorServerOverride, getEditorURLForPort } from "./configFile/editorServerOverride.mjs";
|
|
5
|
-
import { configurationFilesCandidates, searchConfigurationFile } from "./configFile/searchConfigurationFile.mjs";
|
|
6
5
|
import { getConfiguration, getConfigurationAndFilePath } from "./configFile/getConfiguration.mjs";
|
|
6
|
+
import { configurationFilesCandidates, searchConfigurationFile } from "./configFile/searchConfigurationFile.mjs";
|
|
7
7
|
|
|
8
8
|
export { EDITOR_SERVER_PORT_ENV_VAR, aiSchema, analyticsSchema, applyEditorServerOverride, buildAnalyticsFields, buildBrowserConfiguration, buildConfigurationFields, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, buildSchema, compilerSchema, configurationFilesCandidates, contentSchema, cookiesAttributesSchema, dictionarySchema, editorSchema, extractBrowserConfiguration, getConfiguration, getConfigurationAndFilePath, getEditorURLForPort, internationalizationSchema, intlayerConfigSchema, intlayerConfigSchemaParseContext, logSchema, rewriteObjectSchema, rewriteRuleSchema, rewriteRulesSchema, routingSchema, searchConfigurationFile, storageAttributesSchema, storageSchema, systemSchema };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/secrets.browser.ts
|
|
2
2
|
/**
|
|
3
3
|
* Browser stub for {@link file://./secrets.ts}.
|
|
4
4
|
*
|
|
@@ -15,6 +15,5 @@
|
|
|
15
15
|
*/
|
|
16
16
|
const getEditorClientSecret = () => void 0;
|
|
17
17
|
|
|
18
|
-
//#endregion
|
|
19
18
|
export { getEditorClientSecret };
|
|
20
19
|
//# sourceMappingURL=secrets.browser.mjs.map
|
package/dist/esm/secrets.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/secrets.ts
|
|
2
2
|
/**
|
|
3
3
|
* Server-only access to the sensitive parts of the Intlayer configuration.
|
|
4
4
|
*
|
|
@@ -41,6 +41,5 @@
|
|
|
41
41
|
*/
|
|
42
42
|
const getEditorClientSecret = () => typeof process === "undefined" ? void 0 : process.env?.INTLAYER_CLIENT_SECRET;
|
|
43
43
|
|
|
44
|
-
//#endregion
|
|
45
44
|
export { getEditorClientSecret };
|
|
46
45
|
//# sourceMappingURL=secrets.mjs.map
|
|
@@ -2,7 +2,7 @@ import { __require } from "../_virtual/_rolldown/runtime.mjs";
|
|
|
2
2
|
import { getPackageJsonPath } from "./getPackageJsonPath.mjs";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
// src/utils/ESMxCJSHelpers.ts
|
|
6
6
|
const isESModule = typeof import.meta.url === "string";
|
|
7
7
|
/**
|
|
8
8
|
* Require relative to the user project
|
|
@@ -20,6 +20,5 @@ const getProjectRequire = (startDir) => {
|
|
|
20
20
|
*/
|
|
21
21
|
const configESMxCJSRequire = isESModule ? createRequire(import.meta.url) : __require;
|
|
22
22
|
|
|
23
|
-
//#endregion
|
|
24
23
|
export { configESMxCJSRequire, getProjectRequire, isESModule };
|
|
25
24
|
//# sourceMappingURL=ESMxCJSHelpers.mjs.map
|
package/dist/esm/utils/alias.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { normalizePath } from "./normalizePath.mjs";
|
|
2
1
|
import { getExtension } from "./getExtension.mjs";
|
|
2
|
+
import { normalizePath } from "./normalizePath.mjs";
|
|
3
3
|
import { join, relative } from "node:path";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
// src/utils/alias.ts
|
|
6
6
|
/**
|
|
7
7
|
* Generated entry files of `.intlayer/main`, keyed by the
|
|
8
8
|
* `@intlayer/dictionaries-entry` subpath that resolves to them.
|
|
@@ -34,6 +34,5 @@ const getAlias = ({ configuration, format, formatter = (value) => value }) => {
|
|
|
34
34
|
};
|
|
35
35
|
};
|
|
36
36
|
|
|
37
|
-
//#endregion
|
|
38
37
|
export { getAlias };
|
|
39
38
|
//# sourceMappingURL=alias.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alias.mjs","names":[],"sources":["../../../src/utils/alias.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getExtension } from './getExtension';\nimport { normalizePath } from './normalizePath';\n\nexport type GetAliasOptions = {\n configuration: IntlayerConfig;\n format?: 'esm' | 'cjs';\n formatter?: (value: string) => string;\n};\n\n/**\n * Generated entry files of `.intlayer/main`, keyed by the\n * `@intlayer/dictionaries-entry` subpath that resolves to them.\n */\nconst DICTIONARIES_ENTRY_SUBPATH_FILES = {\n unmerged: 'unmerged_dictionaries',\n remote: 'remote_dictionaries',\n dynamic: 'dynamic_dictionaries',\n fetch: 'fetch_dictionaries',\n} as const;\n\ntype DictionariesEntrySubpath = keyof typeof DICTIONARIES_ENTRY_SUBPATH_FILES;\n\ntype DictionariesEntrySubpathAlias = {\n [Subpath in DictionariesEntrySubpath as `@intlayer/dictionaries-entry/${Subpath}
|
|
1
|
+
{"version":3,"file":"alias.mjs","names":[],"sources":["../../../src/utils/alias.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getExtension } from './getExtension';\nimport { normalizePath } from './normalizePath';\n\nexport type GetAliasOptions = {\n configuration: IntlayerConfig;\n format?: 'esm' | 'cjs';\n formatter?: (value: string) => string;\n};\n\n/**\n * Generated entry files of `.intlayer/main`, keyed by the\n * `@intlayer/dictionaries-entry` subpath that resolves to them.\n */\nconst DICTIONARIES_ENTRY_SUBPATH_FILES = {\n unmerged: 'unmerged_dictionaries',\n remote: 'remote_dictionaries',\n dynamic: 'dynamic_dictionaries',\n fetch: 'fetch_dictionaries',\n} as const;\n\ntype DictionariesEntrySubpath = keyof typeof DICTIONARIES_ENTRY_SUBPATH_FILES;\n\ntype DictionariesEntrySubpathAlias = {\n [\n Subpath in DictionariesEntrySubpath as `@intlayer/dictionaries-entry/${Subpath}`\n ]: string;\n};\n\n/**\n * Maps the aliasable Intlayer packages to the generated `.intlayer` files so\n * bundlers (webpack, Vite, Turbopack, esbuild, Metro, …) resolve them to the\n * app's own dictionaries and hot reload on any content change.\n *\n * Key order matters: webpack (enhanced-resolve) and Vite match string aliases\n * by prefix and stop at the first hit, so the bare `@intlayer/dictionaries-entry`\n * key MUST come after its subpaths, otherwise `@intlayer/dictionaries-entry/remote`\n * would be rewritten to `<dictionaries entry>/remote`.\n */\nexport const getAlias = ({\n configuration,\n format,\n formatter = (value: string) => value,\n}: GetAliasOptions) => {\n const extension = getExtension(\n configuration,\n format ?? configuration.build.outputFormat[0] ?? 'esm'\n );\n\n const { baseDir, mainDir, configDir } = configuration.system;\n\n const toAliasPath = (absolutePath: string) =>\n formatter(normalizePath(relative(baseDir, absolutePath)));\n\n const subpathAlias = Object.fromEntries(\n Object.entries(DICTIONARIES_ENTRY_SUBPATH_FILES).map(\n ([subpath, fileName]) => [\n `@intlayer/dictionaries-entry/${subpath}`,\n toAliasPath(join(mainDir, `${fileName}.${extension}`)),\n ]\n )\n ) as DictionariesEntrySubpathAlias;\n\n return {\n ...subpathAlias,\n '@intlayer/dictionaries-entry': toAliasPath(\n join(mainDir, `dictionaries.${extension}`)\n ),\n '@intlayer/config/built': toAliasPath(\n join(configDir, `configuration.${extension}`)\n ),\n };\n};\n"],"mappings":";;;;;;;;;AAeA,MAAM,mCAAmC;CACvC,UAAU;CACV,QAAQ;CACR,SAAS;CACT,OAAO;AACT;;;;;;;;;;;AAoBA,MAAa,YAAY,EACvB,eACA,QACA,aAAa,UAAkB,YACV;CACrB,MAAM,YAAY,aAChB,eACA,UAAU,cAAc,MAAM,aAAa,MAAM,KACnD;CAEA,MAAM,EAAE,SAAS,SAAS,cAAc,cAAc;CAEtD,MAAM,eAAe,iBACnB,UAAU,cAAc,SAAS,SAAS,YAAY,CAAC,CAAC;CAW1D,OAAO;EACL,GAVmB,OAAO,YAC1B,OAAO,QAAQ,gCAAgC,CAAC,CAAC,KAC9C,CAAC,SAAS,cAAc,CACvB,gCAAgC,WAChC,YAAY,KAAK,SAAS,GAAG,SAAS,GAAG,WAAW,CAAC,CACvD,CACF,CAIc;EACd,gCAAgC,YAC9B,KAAK,SAAS,gBAAgB,WAAW,CAC3C;EACA,0BAA0B,YACxB,KAAK,WAAW,iBAAiB,WAAW,CAC9C;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/utils/builtConfigKeys.ts
|
|
2
2
|
/**
|
|
3
3
|
* Canonical list of configuration sections exposed as named exports by
|
|
4
4
|
* `@intlayer/config/built`.
|
|
@@ -31,6 +31,5 @@ const BUILT_CONFIG_KEYS = [
|
|
|
31
31
|
"plugins"
|
|
32
32
|
];
|
|
33
33
|
|
|
34
|
-
//#endregion
|
|
35
34
|
export { BUILT_CONFIG_KEYS };
|
|
36
35
|
//# sourceMappingURL=builtConfigKeys.mjs.map
|
|
@@ -5,7 +5,7 @@ import { deserialize, serialize } from "node:v8";
|
|
|
5
5
|
import { gunzipSync, gzipSync } from "node:zlib";
|
|
6
6
|
import configPackageJson from "@intlayer/types/package.json" with { type: "json" };
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
// src/utils/cacheDisk.ts
|
|
9
9
|
const DEFAULTS = { compress: true };
|
|
10
10
|
const ensureDir = async (dir) => {
|
|
11
11
|
await mkdir(dir, { recursive: true });
|
|
@@ -180,6 +180,5 @@ const cacheDisk = (intlayerConfig, keys, options) => {
|
|
|
180
180
|
};
|
|
181
181
|
};
|
|
182
182
|
|
|
183
|
-
//#endregion
|
|
184
183
|
export { cacheDisk, clearDiskCacheMemory };
|
|
185
184
|
//# sourceMappingURL=cacheDisk.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cacheDisk.mjs","names":[],"sources":["../../../src/utils/cacheDisk.ts"],"sourcesContent":["import {\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { deserialize, serialize } from 'node:v8';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport configPackageJson from '@intlayer/types/package.json' with {\n type: 'json',\n};\nimport { type CacheKey, clearAllCache, computeKeyId } from './cacheMemory';\n\n/** ------------------------- Persistence layer ------------------------- **/\n\n/** Cache envelope structure stored on disk */\ntype CacheEnvelope = {\n /** Version of the config package (for cache invalidation) */\n version: string;\n /** Timestamp when the cache entry was created (in milliseconds) */\n timestamp: number;\n /** Data payload (the actual cached value) */\n data: unknown;\n};\n\ntype LocalCacheOptions = {\n /** Preferred new option name */\n persistent?: boolean;\n /** Time-to-live in ms; if expired, disk entry is ignored. */\n ttlMs?: number;\n /** Max age in ms based on stored creation timestamp; invalidates on exceed. */\n maxTimeMs?: number;\n /** Optional namespace to separate different logical caches. */\n namespace?: string;\n /** Gzip values on disk (on by default for blobs > 1KB). */\n compress?: boolean;\n};\n\nconst DEFAULTS: Required<Pick<LocalCacheOptions, 'compress'>> = {\n compress: true,\n};\n\nconst ensureDir = async (dir: string) => {\n await mkdir(dir, { recursive: true });\n};\n\nconst atomicWriteFile = async (\n file: string,\n data: Buffer,\n tempDir?: string\n) => {\n if (tempDir) {\n try {\n await ensureDir(tempDir);\n } catch {}\n }\n\n const tempFileName = `${basename(file)}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n const tmp = tempDir\n ? join(tempDir, tempFileName)\n : `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n try {\n await writeFile(tmp, data);\n await rename(tmp, file);\n } catch (error) {\n try {\n await rm(tmp, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n};\n\nconst shouldUseCompression = (buf: Buffer, force?: boolean) =>\n force === true || (force !== false && buf.byteLength > 1024);\n\n/** Derive on-disk path from config dir + namespace + key id. */\nconst cachePath = (cacheDir: string, id: string, ns?: string) =>\n join(cacheDir, ns ? join(ns, id) : id);\n\n/** ------------------------- Local cache facade ------------------------- **/\n\nconst cacheMap = new Map<string, any>();\n\n/** Clears the in-memory portion of the disk cache without touching disk files. */\nexport const clearDiskCacheMemory = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheDisk = (\n intlayerConfig: IntlayerConfig,\n keys: CacheKey[],\n options?: LocalCacheOptions\n) => {\n const { cacheDir, tempDir } = intlayerConfig.system;\n const buildCacheEnabled = intlayerConfig.build.cache ?? true;\n const persistent =\n options?.persistent === true ||\n (typeof options?.persistent === 'undefined' && buildCacheEnabled);\n\n const { compress, ttlMs, maxTimeMs, namespace } = {\n ...DEFAULTS,\n ...options,\n };\n\n // single stable id for this key tuple (works for both memory & disk)\n const id = computeKeyId(keys);\n const filePath = cachePath(cacheDir, id, namespace);\n\n const readFromDisk = async (): Promise<unknown | undefined> => {\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n\n if (!statValue) return undefined;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return undefined;\n }\n let raw = await readFile(filePath);\n // header: 1 byte flag (0x00 raw, 0x01 gzip)\n const flag = raw[0];\n\n raw = raw.subarray(1);\n\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n let value: unknown;\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof (maybeObj as any).version === 'string' &&\n typeof (maybeObj as any).timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n\n if (entry.version !== configPackageJson.version) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n\n value = entry.data;\n } else {\n // Backward compatibility: old entries had raw serialized value.\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n value = deserialized;\n }\n\n // hydrate memory cache as well\n cacheMap.set(id, value);\n return value;\n } catch {\n return undefined;\n }\n };\n\n const writeToDisk = async (value: unknown) => {\n try {\n await ensureDir(dirname(filePath));\n const envelope: CacheEnvelope = {\n version: configPackageJson.version,\n timestamp: Date.now(),\n data: value,\n };\n const payload = Buffer.from(serialize(envelope));\n\n const gz = shouldUseCompression(payload, compress)\n ? gzipSync(payload)\n : payload;\n\n // prepend a 1-byte header indicating compression\n const buf = Buffer.concat([\n Buffer.from([gz === payload ? 0x00 : 0x01]),\n gz,\n ]);\n\n await atomicWriteFile(filePath, buf, tempDir);\n } catch {\n // swallow disk errors for cache writes\n }\n };\n\n return {\n /** In-memory first, then disk (if enabled), otherwise undefined. */\n get: async <T>(): Promise<T | undefined> => {\n const mem = cacheMap.get(id);\n\n if (mem !== undefined) return mem as T;\n\n if (persistent && buildCacheEnabled) {\n return (await readFromDisk()) as T | undefined;\n }\n return undefined;\n },\n /** Sets in-memory (always) and persists to disk if enabled. */\n set: async (value: unknown): Promise<void> => {\n cacheMap.set(id, value);\n\n if (persistent && buildCacheEnabled) {\n await writeToDisk(value);\n }\n },\n /** Clears only this entry from memory and disk. */\n clear: async (): Promise<void> => {\n cacheMap.delete(id);\n\n try {\n await unlink(filePath);\n } catch {}\n },\n /** Clears ALL cached entries (memory Map and entire cacheDir namespace if persistent). */\n clearAll: async (): Promise<void> => {\n clearAllCache();\n if (persistent && buildCacheEnabled) {\n // remove only the current namespace (if provided), else the root dir\n const base = namespace ? join(cacheDir, namespace) : cacheDir;\n\n try {\n await rm(base, { recursive: true, force: true });\n } catch {}\n\n try {\n await mkdir(base, { recursive: true });\n } catch {}\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n isValid: async (): Promise<boolean> => {\n const cachedValue = cacheMap.get(id);\n if (cachedValue !== undefined) return true;\n\n // If persistence is disabled or build cache disabled, only memory can be valid\n if (!persistent || !buildCacheEnabled) return false;\n\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n if (!statValue) return false;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return false;\n }\n\n let raw = await readFile(filePath);\n const flag = raw[0];\n raw = raw.subarray(1);\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof maybeObj.version === 'string' &&\n typeof maybeObj.timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n if (entry.version !== configPackageJson.version) return false;\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) return false;\n }\n return true;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) return false;\n }\n return true;\n } catch {\n return false;\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n id,\n /** Expose the absolute file path for debugging. */\n filePath,\n };\n};\n"],"mappings":";;;;;;;;AA2CA,MAAM,WAA0D,EAC9D,UAAU,KACZ;AAEA,MAAM,YAAY,OAAO,QAAgB;CACvC,MAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;AACtC;AAEA,MAAM,kBAAkB,OACtB,MACA,MACA,YACG;CACH,IAAI,SACF,IAAI;EACF,MAAM,UAAU,OAAO;CACzB,QAAQ,CAAC;CAGX,MAAM,eAAe,GAAG,SAAS,IAAI,EAAE,OAAO,QAAQ,IAAI,GA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SAAS,YAAY,YAC5B,OAAO,SAAS,cAAc,YAC9B,OAAO,OAAO,UAAU,MAAM,GAEhB;KACd,MAAM,QAAQ;KACd,IAAI,MAAM,YAAY,kBAAkB,SAAS,OAAO;KAExD,IAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;UADY,KAAK,IAAI,IAAI,MAAM,YACrB,WAAW,OAAO;KAAK;KAEnC,OAAO;IACT;IAEA,IAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;SADY,KAAK,IAAI,IAAI,UAAU,UACzB,WAAW,OAAO;IAAK;IAEnC,OAAO;GACT,QAAQ;IACN,OAAO;GACT;EACF;;EAEA;;EAEA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"cacheDisk.mjs","names":[],"sources":["../../../src/utils/cacheDisk.ts"],"sourcesContent":["import {\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { deserialize, serialize } from 'node:v8';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport configPackageJson from '@intlayer/types/package.json' with { type: 'json' };\nimport { type CacheKey, clearAllCache, computeKeyId } from './cacheMemory';\n\n/** ------------------------- Persistence layer ------------------------- **/\n\n/** Cache envelope structure stored on disk */\ntype CacheEnvelope = {\n /** Version of the config package (for cache invalidation) */\n version: string;\n /** Timestamp when the cache entry was created (in milliseconds) */\n timestamp: number;\n /** Data payload (the actual cached value) */\n data: unknown;\n};\n\ntype LocalCacheOptions = {\n /** Preferred new option name */\n persistent?: boolean;\n /** Time-to-live in ms; if expired, disk entry is ignored. */\n ttlMs?: number;\n /** Max age in ms based on stored creation timestamp; invalidates on exceed. */\n maxTimeMs?: number;\n /** Optional namespace to separate different logical caches. */\n namespace?: string;\n /** Gzip values on disk (on by default for blobs > 1KB). */\n compress?: boolean;\n};\n\nconst DEFAULTS: Required<Pick<LocalCacheOptions, 'compress'>> = {\n compress: true,\n};\n\nconst ensureDir = async (dir: string) => {\n await mkdir(dir, { recursive: true });\n};\n\nconst atomicWriteFile = async (\n file: string,\n data: Buffer,\n tempDir?: string\n) => {\n if (tempDir) {\n try {\n await ensureDir(tempDir);\n } catch {}\n }\n\n const tempFileName = `${basename(file)}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n const tmp = tempDir\n ? join(tempDir, tempFileName)\n : `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n try {\n await writeFile(tmp, data);\n await rename(tmp, file);\n } catch (error) {\n try {\n await rm(tmp, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n};\n\nconst shouldUseCompression = (buf: Buffer, force?: boolean) =>\n force === true || (force !== false && buf.byteLength > 1024);\n\n/** Derive on-disk path from config dir + namespace + key id. */\nconst cachePath = (cacheDir: string, id: string, ns?: string) =>\n join(cacheDir, ns ? join(ns, id) : id);\n\n/** ------------------------- Local cache facade ------------------------- **/\n\nconst cacheMap = new Map<string, any>();\n\n/** Clears the in-memory portion of the disk cache without touching disk files. */\nexport const clearDiskCacheMemory = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheDisk = (\n intlayerConfig: IntlayerConfig,\n keys: CacheKey[],\n options?: LocalCacheOptions\n) => {\n const { cacheDir, tempDir } = intlayerConfig.system;\n const buildCacheEnabled = intlayerConfig.build.cache ?? true;\n const persistent =\n options?.persistent === true ||\n (typeof options?.persistent === 'undefined' && buildCacheEnabled);\n\n const { compress, ttlMs, maxTimeMs, namespace } = {\n ...DEFAULTS,\n ...options,\n };\n\n // single stable id for this key tuple (works for both memory & disk)\n const id = computeKeyId(keys);\n const filePath = cachePath(cacheDir, id, namespace);\n\n const readFromDisk = async (): Promise<unknown | undefined> => {\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n\n if (!statValue) return undefined;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return undefined;\n }\n let raw = await readFile(filePath);\n // header: 1 byte flag (0x00 raw, 0x01 gzip)\n const flag = raw[0];\n\n raw = raw.subarray(1);\n\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n let value: unknown;\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof (maybeObj as any).version === 'string' &&\n typeof (maybeObj as any).timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n\n if (entry.version !== configPackageJson.version) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n\n value = entry.data;\n } else {\n // Backward compatibility: old entries had raw serialized value.\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n value = deserialized;\n }\n\n // hydrate memory cache as well\n cacheMap.set(id, value);\n return value;\n } catch {\n return undefined;\n }\n };\n\n const writeToDisk = async (value: unknown) => {\n try {\n await ensureDir(dirname(filePath));\n const envelope: CacheEnvelope = {\n version: configPackageJson.version,\n timestamp: Date.now(),\n data: value,\n };\n const payload = Buffer.from(serialize(envelope));\n\n const gz = shouldUseCompression(payload, compress)\n ? gzipSync(payload)\n : payload;\n\n // prepend a 1-byte header indicating compression\n const buf = Buffer.concat([\n Buffer.from([gz === payload ? 0x00 : 0x01]),\n gz,\n ]);\n\n await atomicWriteFile(filePath, buf, tempDir);\n } catch {\n // swallow disk errors for cache writes\n }\n };\n\n return {\n /** In-memory first, then disk (if enabled), otherwise undefined. */\n get: async <T>(): Promise<T | undefined> => {\n const mem = cacheMap.get(id);\n\n if (mem !== undefined) return mem as T;\n\n if (persistent && buildCacheEnabled) {\n return (await readFromDisk()) as T | undefined;\n }\n return undefined;\n },\n /** Sets in-memory (always) and persists to disk if enabled. */\n set: async (value: unknown): Promise<void> => {\n cacheMap.set(id, value);\n\n if (persistent && buildCacheEnabled) {\n await writeToDisk(value);\n }\n },\n /** Clears only this entry from memory and disk. */\n clear: async (): Promise<void> => {\n cacheMap.delete(id);\n\n try {\n await unlink(filePath);\n } catch {}\n },\n /** Clears ALL cached entries (memory Map and entire cacheDir namespace if persistent). */\n clearAll: async (): Promise<void> => {\n clearAllCache();\n if (persistent && buildCacheEnabled) {\n // remove only the current namespace (if provided), else the root dir\n const base = namespace ? join(cacheDir, namespace) : cacheDir;\n\n try {\n await rm(base, { recursive: true, force: true });\n } catch {}\n\n try {\n await mkdir(base, { recursive: true });\n } catch {}\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n isValid: async (): Promise<boolean> => {\n const cachedValue = cacheMap.get(id);\n if (cachedValue !== undefined) return true;\n\n // If persistence is disabled or build cache disabled, only memory can be valid\n if (!persistent || !buildCacheEnabled) return false;\n\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n if (!statValue) return false;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return false;\n }\n\n let raw = await readFile(filePath);\n const flag = raw[0];\n raw = raw.subarray(1);\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof maybeObj.version === 'string' &&\n typeof maybeObj.timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n if (entry.version !== configPackageJson.version) return false;\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) return false;\n }\n return true;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) return false;\n }\n return true;\n } catch {\n return false;\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n id,\n /** Expose the absolute file path for debugging. */\n filePath,\n };\n};\n"],"mappings":";;;;;;;;AAyCA,MAAM,WAA0D,EAC9D,UAAU,KACZ;AAEA,MAAM,YAAY,OAAO,QAAgB;CACvC,MAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;AACtC;AAEA,MAAM,kBAAkB,OACtB,MACA,MACA,YACG;CACH,IAAI,SACF,IAAI;EACF,MAAM,UAAU,OAAO;CACzB,QAAQ,CAAC;CAGX,MAAM,eAAe,GAAG,SAAS,IAAI,EAAE,OAAO,QAAQ,IAAI,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;CAC/F,MAAM,MAAM,UACR,KAAK,SAAS,YAAY,IAC1B,GAAG,KAAK,OAAO,QAAQ,IAAI,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;CACpE,IAAI;EACF,MAAM,UAAU,KAAK,IAAI;EACzB,MAAM,OAAO,KAAK,IAAI;CACxB,SAAS,OAAO;EACd,IAAI;GACF,MAAM,GAAG,KAAK,EAAE,OAAO,KAAK,CAAC;EAC/B,QAAQ,CAER;EACA,MAAM;CACR;AACF;AAEA,MAAM,wBAAwB,KAAa,UACzC,UAAU,QAAS,UAAU,SAAS,IAAI,aAAa;;AAGzD,MAAM,aAAa,UAAkB,IAAY,OAC/C,KAAK,UAAU,KAAK,KAAK,IAAI,EAAE,IAAI,EAAE;;AAIvC,MAAM,2BAAW,IAAI,IAAiB;;AAGtC,MAAa,6BAAmC;CAC9C,SAAS,MAAM;AACjB;AAEA,MAAa,aACX,gBACA,MACA,YACG;CACH,MAAM,EAAE,UAAU,YAAY,eAAe;CAC7C,M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,IADoB,SAAS,IAAI,EACnB,MAAM,QAAW,OAAO;GAGtC,IAAI,CAAC,cAAc,CAAC,mBAAmB,OAAO;GAE9C,IAAI;IACF,MAAM,YAAY,MAAM,KAAK,QAAQ,CAAC,CAAC,YAAY,MAAS;IAC5D,IAAI,CAAC,WAAW,OAAO;IAEvB,IAAI,OAAO,UAAU,YAAY,QAAQ,GAEvC;SADY,KAAK,IAAI,IAAI,UAAU,UACzB,OAAO,OAAO;IAAK;IAG/B,IAAI,MAAM,MAAM,SAAS,QAAQ;IACjC,MAAM,OAAO,IAAI;IACjB,MAAM,IAAI,SAAS,CAAC;IACpB,MAAM,UAAU,SAAS,IAAO,WAAW,GAAG,IAAI;IAGlD,MAAM,WAFe,YAAY,OAEL;IAQ5B,IANE,CAAC,CAAC,YACF,OAAO,aAAa,YACpB,OAAO,SAAS,YAAY,YAC5B,OAAO,SAAS,cAAc,YAC9B,OAAO,OAAO,UAAU,MAAM,GAEhB;KACd,MAAM,QAAQ;KACd,IAAI,MAAM,YAAY,kBAAkB,SAAS,OAAO;KAExD,IAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;UADY,KAAK,IAAI,IAAI,MAAM,YACrB,WAAW,OAAO;KAAK;KAEnC,OAAO;IACT;IAEA,IAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;SADY,KAAK,IAAI,IAAI,UAAU,UACzB,WAAW,OAAO;IAAK;IAEnC,OAAO;GACT,QAAQ;IACN,OAAO;GACT;EACF;;EAEA;;EAEA;CACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// src/utils/cacheMemory.ts
|
|
4
4
|
/** ------------------------- Utilities ------------------------- **/
|
|
5
5
|
/** Prefer a fast non-crypto hash if available, then fast crypto, then sha256. */
|
|
6
6
|
const pickHashAlgorithm = () => {
|
|
@@ -257,6 +257,5 @@ const cacheMemory = {
|
|
|
257
257
|
clear: clearCache
|
|
258
258
|
};
|
|
259
259
|
|
|
260
|
-
//#endregion
|
|
261
260
|
export { cacheMemory, clearAllCache, clearCache, computeKeyId, getCache, setCache, stableStringify };
|
|
262
261
|
//# sourceMappingURL=cacheMemory.mjs.map
|