@intlayer/config 9.3.0 → 9.3.1

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.
Files changed (110) hide show
  1. package/README.md +24 -24
  2. package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -2
  3. package/dist/cjs/bundle/index.cjs +1 -1
  4. package/dist/cjs/bundle/index.cjs.map +1 -1
  5. package/dist/cjs/callers/base.cjs +0 -1
  6. package/dist/cjs/callers/base.cjs.map +1 -1
  7. package/dist/cjs/callers/compat/i18next.cjs +0 -1
  8. package/dist/cjs/callers/compat/i18next.cjs.map +1 -1
  9. package/dist/cjs/callers/compat/lingui.cjs +0 -1
  10. package/dist/cjs/callers/compat/lingui.cjs.map +1 -1
  11. package/dist/cjs/callers/compat/nextIntl.cjs +0 -1
  12. package/dist/cjs/callers/compat/nextIntl.cjs.map +1 -1
  13. package/dist/cjs/callers/compat/reactI18next.cjs +0 -1
  14. package/dist/cjs/callers/compat/reactI18next.cjs.map +1 -1
  15. package/dist/cjs/callers/compat/reactIntl.cjs +0 -1
  16. package/dist/cjs/callers/compat/reactIntl.cjs.map +1 -1
  17. package/dist/cjs/callers/compat/useIntl.cjs +0 -1
  18. package/dist/cjs/callers/compat/useIntl.cjs.map +1 -1
  19. package/dist/cjs/callers/compat/vueI18n.cjs +0 -1
  20. package/dist/cjs/callers/compat/vueI18n.cjs.map +1 -1
  21. package/dist/cjs/callers/transform.cjs +0 -1
  22. package/dist/cjs/callers/transform.cjs.map +1 -1
  23. package/dist/cjs/colors.cjs +0 -1
  24. package/dist/cjs/colors.cjs.map +1 -1
  25. package/dist/cjs/configFile/buildConfigurationFields.cjs.map +1 -1
  26. package/dist/cjs/configFile/getConfiguration.cjs +3 -2
  27. package/dist/cjs/configFile/getConfiguration.cjs.map +1 -1
  28. package/dist/cjs/configFile/searchConfigurationFile.cjs.map +1 -1
  29. package/dist/cjs/defaultValues/analytics.cjs +0 -1
  30. package/dist/cjs/defaultValues/analytics.cjs.map +1 -1
  31. package/dist/cjs/defaultValues/build.cjs +0 -1
  32. package/dist/cjs/defaultValues/build.cjs.map +1 -1
  33. package/dist/cjs/defaultValues/compiler.cjs +0 -1
  34. package/dist/cjs/defaultValues/compiler.cjs.map +1 -1
  35. package/dist/cjs/defaultValues/content.cjs +0 -1
  36. package/dist/cjs/defaultValues/content.cjs.map +1 -1
  37. package/dist/cjs/defaultValues/dictionary.cjs +0 -1
  38. package/dist/cjs/defaultValues/dictionary.cjs.map +1 -1
  39. package/dist/cjs/defaultValues/editor.cjs +0 -1
  40. package/dist/cjs/defaultValues/editor.cjs.map +1 -1
  41. package/dist/cjs/defaultValues/internationalization.cjs +0 -1
  42. package/dist/cjs/defaultValues/internationalization.cjs.map +1 -1
  43. package/dist/cjs/defaultValues/routing.cjs +0 -1
  44. package/dist/cjs/defaultValues/routing.cjs.map +1 -1
  45. package/dist/cjs/defaultValues/system.cjs +0 -1
  46. package/dist/cjs/defaultValues/system.cjs.map +1 -1
  47. package/dist/cjs/envVars/envVars.cjs +0 -1
  48. package/dist/cjs/envVars/envVars.cjs.map +1 -1
  49. package/dist/cjs/loadEnvFile.cjs +8 -6
  50. package/dist/cjs/loadEnvFile.cjs.map +1 -1
  51. package/dist/cjs/loadExternalFile/bundleFile.cjs +4 -2
  52. package/dist/cjs/loadExternalFile/bundleFile.cjs.map +1 -1
  53. package/dist/cjs/loadExternalFile/bundleJSFile.cjs.map +1 -1
  54. package/dist/cjs/loadExternalFile/loadExternalFile.cjs +4 -2
  55. package/dist/cjs/loadExternalFile/loadExternalFile.cjs.map +1 -1
  56. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +4 -2
  57. package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
  58. package/dist/cjs/utils/ESMxCJSHelpers.cjs.map +1 -1
  59. package/dist/cjs/utils/alias.cjs +41 -6
  60. package/dist/cjs/utils/alias.cjs.map +1 -1
  61. package/dist/cjs/utils/builtConfigKeys.cjs +0 -1
  62. package/dist/cjs/utils/builtConfigKeys.cjs.map +1 -1
  63. package/dist/cjs/utils/cacheDisk.cjs +4 -2
  64. package/dist/cjs/utils/cacheDisk.cjs.map +1 -1
  65. package/dist/cjs/utils/cacheMemory.cjs.map +1 -1
  66. package/dist/cjs/utils/compareVersions.cjs +0 -1
  67. package/dist/cjs/utils/compareVersions.cjs.map +1 -1
  68. package/dist/cjs/utils/extractErrorMessage.cjs +0 -1
  69. package/dist/cjs/utils/extractErrorMessage.cjs.map +1 -1
  70. package/dist/cjs/utils/getDictionarySelectorUsage.cjs +0 -1
  71. package/dist/cjs/utils/getDictionarySelectorUsage.cjs.map +1 -1
  72. package/dist/cjs/utils/getExtension.cjs +0 -1
  73. package/dist/cjs/utils/getExtension.cjs.map +1 -1
  74. package/dist/cjs/utils/getPackageJsonPath.cjs.map +1 -1
  75. package/dist/cjs/utils/getStorageAttributes.cjs +1 -1
  76. package/dist/cjs/utils/getStorageAttributes.cjs.map +1 -1
  77. package/dist/cjs/utils/normalizePath.cjs +0 -1
  78. package/dist/cjs/utils/normalizePath.cjs.map +1 -1
  79. package/dist/cjs/utils/parseFilePathPattern.cjs +0 -1
  80. package/dist/cjs/utils/parseFilePathPattern.cjs.map +1 -1
  81. package/dist/cjs/utils/pathSecurity.cjs.map +1 -1
  82. package/dist/cjs/utils/setIntlayerIdentifier.cjs +0 -1
  83. package/dist/cjs/utils/setIntlayerIdentifier.cjs.map +1 -1
  84. package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs +0 -1
  85. package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs.map +1 -1
  86. package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs +0 -1
  87. package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs.map +1 -1
  88. package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs +0 -1
  89. package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs.map +1 -1
  90. package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs +0 -1
  91. package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs.map +1 -1
  92. package/dist/esm/bundle/index.mjs +1 -1
  93. package/dist/esm/configFile/getConfiguration.mjs +3 -2
  94. package/dist/esm/configFile/getConfiguration.mjs.map +1 -1
  95. package/dist/esm/loadEnvFile.mjs +8 -6
  96. package/dist/esm/loadEnvFile.mjs.map +1 -1
  97. package/dist/esm/loadExternalFile/bundleFile.mjs +4 -2
  98. package/dist/esm/loadExternalFile/bundleFile.mjs.map +1 -1
  99. package/dist/esm/loadExternalFile/loadExternalFile.mjs +4 -2
  100. package/dist/esm/loadExternalFile/loadExternalFile.mjs.map +1 -1
  101. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs +4 -2
  102. package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
  103. package/dist/esm/utils/ESMxCJSHelpers.mjs.map +1 -1
  104. package/dist/esm/utils/alias.mjs +41 -6
  105. package/dist/esm/utils/alias.mjs.map +1 -1
  106. package/dist/esm/utils/cacheDisk.mjs +4 -2
  107. package/dist/esm/utils/cacheDisk.mjs.map +1 -1
  108. package/dist/esm/utils/getStorageAttributes.mjs +1 -1
  109. package/dist/esm/utils/getStorageAttributes.mjs.map +1 -1
  110. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"getConfiguration.mjs","names":[],"sources":["../../../src/configFile/getConfiguration.ts"],"sourcesContent":["import type {\n CustomIntlayerConfig,\n IntlayerConfig,\n LogFunctions,\n} from '@intlayer/types/config';\nimport { defu } from 'defu';\nimport type { LoadExternalFileOptions } from '../loadExternalFile/loadExternalFile';\nimport type { SandBoxContextOptions } from '../loadExternalFile/parseFileContent';\nimport { cacheMemory } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { buildConfigurationFields } from './buildConfigurationFields';\nimport { loadConfigurationFile } from './loadConfigurationFile';\nimport { searchConfigurationFile } from './searchConfigurationFile';\n\nexport type GetConfigurationOptions = {\n baseDir?: string;\n override?: CustomIntlayerConfig;\n // Dotenv options\n env?: string;\n envFile?: string;\n // Log functions\n logFunctions?: LogFunctions;\n // Require function\n require?: NodeJS.Require;\n // cache\n cache?: boolean;\n // Build options for TypeScript transpilation (e.g. custom esbuild instance)\n buildOptions?: LoadExternalFileOptions['buildOptions'];\n} & Omit<SandBoxContextOptions, 'projectRequire'>;\n\nexport type GetConfigurationAndFilePathResult = {\n configuration: IntlayerConfig;\n customConfiguration: CustomIntlayerConfig | undefined;\n numCustomConfiguration: number;\n configurationFilePath: string | undefined;\n};\n\n/**\n * Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)\n */\nexport const getConfigurationAndFilePath = (\n options?: GetConfigurationOptions\n): GetConfigurationAndFilePathResult => {\n let baseDir: string | undefined;\n\n try {\n // Can fail in some environments (e.g. MCP server, VScode extension)\n baseDir = options?.baseDir ?? getPackageJsonPath().baseDir;\n } catch (_err) {\n // Return default config if the package.json is not found\n return {\n configuration: buildConfigurationFields(\n {},\n options?.baseDir,\n options?.logFunctions\n ),\n customConfiguration: undefined,\n numCustomConfiguration: 0,\n configurationFilePath: undefined,\n };\n }\n\n const cachedConfiguration =\n cacheMemory.get<GetConfigurationAndFilePathResult>(options);\n\n if (cachedConfiguration) return cachedConfiguration;\n\n // Search for configuration files\n const { configurationFilePath, numCustomConfiguration } =\n searchConfigurationFile(baseDir);\n\n let storedConfiguration: IntlayerConfig;\n let customConfiguration: CustomIntlayerConfig | undefined;\n\n if (configurationFilePath) {\n // Load the custom configuration\n customConfiguration = loadConfigurationFile(configurationFilePath, {\n projectRequire: options?.require,\n // Dotenv options\n envVarOptions: {\n env: options?.env,\n envFile: options?.envFile,\n },\n // Sandbox context additional variables\n additionalEnvVars: options?.additionalEnvVars,\n aliases: options?.aliases,\n // Build options for TypeScript transpilation (e.g. custom esbuild instance)\n buildOptions: options?.buildOptions,\n });\n\n // Save the configuration to avoid reading the file again\n storedConfiguration = buildConfigurationFields(\n customConfiguration,\n options?.baseDir,\n options?.logFunctions\n );\n } else {\n // No configuration file found, use default configuration\n storedConfiguration = buildConfigurationFields(\n {},\n options?.baseDir,\n options?.logFunctions\n );\n }\n\n // Log warning if multiple configuration files are found\n const projectRequireConfig: CustomIntlayerConfig = options?.require\n ? {\n build: {\n require: options?.require,\n cache: options?.cache,\n },\n }\n : {};\n\n const configWithProjectRequire = defu(\n projectRequireConfig,\n storedConfiguration\n ) as IntlayerConfig;\n\n const configuration = defu(\n options?.override ?? {},\n configWithProjectRequire\n ) as IntlayerConfig;\n\n cacheMemory.set(options, {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n });\n\n return {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n };\n};\n\n/**\n * Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)\n */\nexport const getConfiguration = (\n options?: GetConfigurationOptions\n): IntlayerConfig => getConfigurationAndFilePath(options).configuration;\n"],"mappings":";;;;;;;;;;;AAwCA,MAAa,+BACX,YACsC;CACtC,IAAI;CAEJ,IAAI;EAEF,UAAU,SAAS,WAAW,mBAAmB,CAAC,CAAC;CACrD,SAAS,MAAM;EAEb,OAAO;GACL,eAAe,yBACb,CAAC,GACD,SAAS,SACT,SAAS,YACX;GACA,qBAAqB;GACrB,wBAAwB;GACxB,uBAAuB;EACzB;CACF;CAEA,MAAM,sBACJ,YAAY,IAAuC,OAAO;CAE5D,IAAI,qBAAqB,OAAO;CAGhC,MAAM,EAAE,uBAAuB,2BAC7B,wBAAwB,OAAO;CAEjC,IAAI;CACJ,IAAI;CAEJ,IAAI,uBAAuB;EAEzB,sBAAsB,sBAAsB,uBAAuB;GACjE,gBAAgB,SAAS;GAEzB,eAAe;IACb,KAAK,SAAS;IACd,SAAS,SAAS;GACpB;GAEA,mBAAmB,SAAS;GAC5B,SAAS,SAAS;GAElB,cAAc,SAAS;EACzB,CAAC;EAGD,sBAAsB,yBACpB,qBACA,SAAS,SACT,SAAS,YACX;CACF,OAEE,sBAAsB,yBACpB,CAAC,GACD,SAAS,SACT,SAAS,YACX;CAaF,MAAM,2BAA2B,KATkB,SAAS,UACxD,EACE,OAAO;EACL,SAAS,SAAS;EAClB,OAAO,SAAS;CAClB,EACF,IACA,CAAC,GAIH,mBACF;CAEA,MAAM,gBAAgB,KACpB,SAAS,YAAY,CAAC,GACtB,wBACF;CAEA,YAAY,IAAI,SAAS;EACvB;EACA;EACA;EACA;CACF,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;CACF;AACF;;;;AAKA,MAAa,oBACX,YACmB,4BAA4B,OAAO,CAAC,CAAC"}
1
+ {"version":3,"file":"getConfiguration.mjs","names":[],"sources":["../../../src/configFile/getConfiguration.ts"],"sourcesContent":["import type {\n CustomIntlayerConfig,\n IntlayerConfig,\n LogFunctions,\n} from '@intlayer/types/config';\nimport { defu } from 'defu';\nimport type { LoadExternalFileOptions } from '../loadExternalFile/loadExternalFile';\nimport type { SandBoxContextOptions } from '../loadExternalFile/parseFileContent';\nimport { cacheMemory } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { buildConfigurationFields } from './buildConfigurationFields';\nimport { loadConfigurationFile } from './loadConfigurationFile';\nimport { searchConfigurationFile } from './searchConfigurationFile';\n\nexport type GetConfigurationOptions = {\n baseDir?: string;\n override?: CustomIntlayerConfig;\n // Dotenv options\n env?: string;\n envFile?: string;\n // Log functions\n logFunctions?: LogFunctions;\n // Require function\n require?: NodeJS.Require;\n // cache\n cache?: boolean;\n // Build options for TypeScript transpilation (e.g. custom esbuild instance)\n buildOptions?: LoadExternalFileOptions['buildOptions'];\n} & Omit<SandBoxContextOptions, 'projectRequire'>;\n\nexport type GetConfigurationAndFilePathResult = {\n configuration: IntlayerConfig;\n customConfiguration: CustomIntlayerConfig | undefined;\n numCustomConfiguration: number;\n configurationFilePath: string | undefined;\n};\n\n/**\n * Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)\n */\nexport const getConfigurationAndFilePath = (\n options?: GetConfigurationOptions\n): GetConfigurationAndFilePathResult => {\n let baseDir: string | undefined;\n\n try {\n // Can fail in some environments (e.g. MCP server, VScode extension)\n baseDir = options?.baseDir ?? getPackageJsonPath().baseDir;\n } catch (_err) {\n // Return default config if the package.json is not found\n return {\n configuration: buildConfigurationFields(\n {},\n options?.baseDir,\n options?.logFunctions\n ),\n customConfiguration: undefined,\n numCustomConfiguration: 0,\n configurationFilePath: undefined,\n };\n }\n\n const cachedConfiguration =\n cacheMemory.get<GetConfigurationAndFilePathResult>(options);\n\n if (cachedConfiguration) return cachedConfiguration;\n\n // Search for configuration files\n const { configurationFilePath, numCustomConfiguration } =\n searchConfigurationFile(baseDir);\n\n let storedConfiguration: IntlayerConfig;\n let customConfiguration: CustomIntlayerConfig | undefined;\n\n if (configurationFilePath) {\n // Load the custom configuration\n customConfiguration = loadConfigurationFile(configurationFilePath, {\n projectRequire: options?.require,\n // Dotenv options\n envVarOptions: {\n env: options?.env,\n envFile: options?.envFile,\n },\n // Sandbox context additional variables\n additionalEnvVars: options?.additionalEnvVars,\n aliases: options?.aliases,\n // Build options for TypeScript transpilation (e.g. custom esbuild instance)\n buildOptions: options?.buildOptions,\n });\n\n // Save the configuration to avoid reading the file again\n storedConfiguration = buildConfigurationFields(\n customConfiguration,\n options?.baseDir,\n options?.logFunctions\n );\n } else {\n // No configuration file found, use default configuration\n storedConfiguration = buildConfigurationFields(\n {},\n options?.baseDir,\n options?.logFunctions\n );\n }\n\n // Log warning if multiple configuration files are found\n const projectRequireConfig: CustomIntlayerConfig = options?.require\n ? {\n build: {\n require: options?.require,\n cache: options?.cache,\n },\n }\n : {};\n\n const configWithProjectRequire = defu(\n projectRequireConfig,\n storedConfiguration\n ) as IntlayerConfig;\n\n const configuration = defu(\n options?.override ?? {},\n configWithProjectRequire\n ) as IntlayerConfig;\n\n cacheMemory.set(options, {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n });\n\n return {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n };\n};\n\n/**\n * Get the configuration for the intlayer by reading the configuration file (e.g. intlayer.config.js)\n */\nexport const getConfiguration = (\n options?: GetConfigurationOptions\n): IntlayerConfig => getConfigurationAndFilePath(options).configuration;\n"],"mappings":";;;;;;;;;;;AAwCA,MAAa,+BACX,YACsC;CACtC,IAAI;CAEJ,IAAI;EAEF,UAAU,SAAS,WAAW,mBAAmB,CAAC,CAAC;CACrD,SAAS,MAAM;EAEb,OAAO;GACL,eAAe,yBACb,CAAC,GACD,SAAS,SACT,SAAS,YACX;GACA,qBAAqB;GACrB,wBAAwB;GACxB,uBAAuB;EACzB;CACF;CAEA,MAAM,sBACJ,YAAY,IAAuC,OAAO;CAE5D,IAAI,qBAAqB,OAAO;CAGhC,MAAM,EAAE,uBAAuB,2BAC7B,wBAAwB,OAAO;CAEjC,IAAI;CACJ,IAAI;CAEJ,IAAI,uBAAuB;EAEzB,sBAAsB,sBAAsB,uBAAuB;GACjE,gBAAgB,SAAS;GAEzB,eAAe;IACb,KAAK,SAAS;IACd,SAAS,SAAS;GACpB;GAEA,mBAAmB,SAAS;GAC5B,SAAS,SAAS;GAElB,cAAc,SAAS;EACzB,CAAC;EAGD,sBAAsB,yBACpB,qBACA,SAAS,SACT,SAAS,YACX;CACF,OAEE,sBAAsB,yBACpB,CAAC,GACD,SAAS,SACT,SAAS,YACX;CAIF,MAAM,uBAA6C,SAAS,UACxD,EACE,OAAO;EACL,SAAS,SAAS;EAClB,OAAO,SAAS;CAClB,EACF,IACA,CAAC;CAEL,MAAM,2BAA2B,KAC/B,sBACA,mBACF;CAEA,MAAM,gBAAgB,KACpB,SAAS,YAAY,CAAC,GACtB,wBACF;CAEA,YAAY,IAAI,SAAS;EACvB;EACA;EACA;EACA;CACF,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;CACF;AACF;;;;AAKA,MAAa,oBACX,YACmB,4BAA4B,OAAO,CAAC,CAAC"}
@@ -31,12 +31,14 @@ const loadEnvFile = (options) => {
31
31
  const env = options?.env ?? DEFAULT_ENV;
32
32
  const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ""}`;
33
33
  const cachedEntry = envFileCache.get(cacheKey);
34
- if (cachedEntry) if (cachedEntry.envFilePath === void 0) {
35
- if (!getEnvFilePath(env, options?.envFile)) return cachedEntry.parsedEnv;
36
- } else try {
37
- const stats = statSync(cachedEntry.envFilePath);
38
- if (stats.mtimeMs === cachedEntry.mtimeMs && stats.size === cachedEntry.size) return cachedEntry.parsedEnv;
39
- } catch {}
34
+ if (cachedEntry) {
35
+ if (cachedEntry.envFilePath === void 0) {
36
+ if (!getEnvFilePath(env, options?.envFile)) return cachedEntry.parsedEnv;
37
+ } else try {
38
+ const stats = statSync(cachedEntry.envFilePath);
39
+ if (stats.mtimeMs === cachedEntry.mtimeMs && stats.size === cachedEntry.size) return cachedEntry.parsedEnv;
40
+ } catch {}
41
+ }
40
42
  const envFilePath = getEnvFilePath(env, options?.envFile);
41
43
  if (!envFilePath) {
42
44
  envFileCache.set(cacheKey, {
@@ -1 +1 @@
1
- {"version":3,"file":"loadEnvFile.mjs","names":[],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\ntype EnvFileCacheEntry = {\n /** The env file that was resolved and parsed (undefined if none exists). */\n envFilePath: string | undefined;\n /** Fingerprint of the parsed file, used to detect edits. */\n mtimeMs: number;\n size: number;\n /** The parsed env variables. */\n parsedEnv: Record<string, string>;\n};\n\n/**\n * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content\n * declarations calls `loadEnvFile` once per file; without this every call pays\n * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is\n * validated with a single `stat` so edits to the env file are still picked up.\n */\nconst envFileCache = new Map<string, EnvFileCacheEntry>();\n\nconst parseEnvFile = (envFilePath: string): Record<string, string> => {\n const parsedEnv: Record<string, string> = {};\n\n dotenv.config({\n path: envFilePath,\n processEnv: parsedEnv,\n quiet: true,\n });\n\n return parsedEnv;\n};\n\nexport const loadEnvFile = (\n options?: Partial<LoadEnvFileOptions>\n): Record<string, string> => {\n const env = options?.env ?? DEFAULT_ENV;\n\n // Env file candidates are resolved relative to the working directory\n const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ''}`;\n\n const cachedEntry = envFileCache.get(cacheKey);\n\n if (cachedEntry) {\n if (cachedEntry.envFilePath === undefined) {\n // No env file existed. Re-probe cheaply in case one was created since.\n const envFilePath = getEnvFilePath(env, options?.envFile);\n if (!envFilePath) return cachedEntry.parsedEnv;\n } else {\n try {\n const stats = statSync(cachedEntry.envFilePath);\n if (\n stats.mtimeMs === cachedEntry.mtimeMs &&\n stats.size === cachedEntry.size\n ) {\n return cachedEntry.parsedEnv;\n }\n } catch {\n // File was removed — fall through and re-resolve\n }\n }\n }\n\n const envFilePath = getEnvFilePath(env, options?.envFile);\n\n if (!envFilePath) {\n envFileCache.set(cacheKey, {\n envFilePath: undefined,\n mtimeMs: 0,\n size: 0,\n parsedEnv: {},\n });\n return {};\n }\n\n const parsedEnv = parseEnvFile(envFilePath);\n\n try {\n const stats = statSync(envFilePath);\n envFileCache.set(cacheKey, {\n envFilePath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n parsedEnv,\n });\n } catch {\n // Race: file removed between parse and stat — skip caching this round\n }\n\n return parsedEnv; // Return the parsed env object\n};\n"],"mappings":";;;;AAGA,MAAM;AAON,MAAa,kBACX,qBACA,YACuB;CAKvB,QAJiB,UACb,CAAC,OAAO,IACR;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;CAAM,EAE9C,CAAC,KAAK,UAAU;AACjC;;;;;;;AAkBA,MAAM,+BAAe,IAAI,IAA+B;AAExD,MAAM,gBAAgB,gBAAgD;CACpE,MAAM,YAAoC,CAAC;CAE3C,OAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;CACT,CAAC;CAED,OAAO;AACT;AAEA,MAAa,eACX,YAC2B;CAC3B,MAAM,MAAM,SAAS,OAAO;CAG5B,MAAM,WAAW,GAAG,QAAQ,IAAI,EAAE,GAAG,IAAI,GAAG,SAAS,WAAW;CAEhE,MAAM,cAAc,aAAa,IAAI,QAAQ;CAE7C,IAAI,aACF,IAAI,YAAY,gBAAgB,QAG9B;MAAI,CADgB,eAAe,KAAK,SAAS,OAClC,GAAG,OAAO,YAAY;CAAS,OAE9C,IAAI;EACF,MAAM,QAAQ,SAAS,YAAY,WAAW;EAC9C,IACE,MAAM,YAAY,YAAY,WAC9B,MAAM,SAAS,YAAY,MAE3B,OAAO,YAAY;CAEvB,QAAQ,CAER;CAIJ,MAAM,cAAc,eAAe,KAAK,SAAS,OAAO;CAExD,IAAI,CAAC,aAAa;EAChB,aAAa,IAAI,UAAU;GACzB,aAAa;GACb,SAAS;GACT,MAAM;GACN,WAAW,CAAC;EACd,CAAC;EACD,OAAO,CAAC;CACV;CAEA,MAAM,YAAY,aAAa,WAAW;CAE1C,IAAI;EACF,MAAM,QAAQ,SAAS,WAAW;EAClC,aAAa,IAAI,UAAU;GACzB;GACA,SAAS,MAAM;GACf,MAAM,MAAM;GACZ;EACF,CAAC;CACH,QAAQ,CAER;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"loadEnvFile.mjs","names":[],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\ntype EnvFileCacheEntry = {\n /** The env file that was resolved and parsed (undefined if none exists). */\n envFilePath: string | undefined;\n /** Fingerprint of the parsed file, used to detect edits. */\n mtimeMs: number;\n size: number;\n /** The parsed env variables. */\n parsedEnv: Record<string, string>;\n};\n\n/**\n * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content\n * declarations calls `loadEnvFile` once per file; without this every call pays\n * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is\n * validated with a single `stat` so edits to the env file are still picked up.\n */\nconst envFileCache = new Map<string, EnvFileCacheEntry>();\n\nconst parseEnvFile = (envFilePath: string): Record<string, string> => {\n const parsedEnv: Record<string, string> = {};\n\n dotenv.config({\n path: envFilePath,\n processEnv: parsedEnv,\n quiet: true,\n });\n\n return parsedEnv;\n};\n\nexport const loadEnvFile = (\n options?: Partial<LoadEnvFileOptions>\n): Record<string, string> => {\n const env = options?.env ?? DEFAULT_ENV;\n\n // Env file candidates are resolved relative to the working directory\n const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ''}`;\n\n const cachedEntry = envFileCache.get(cacheKey);\n\n if (cachedEntry) {\n if (cachedEntry.envFilePath === undefined) {\n // No env file existed. Re-probe cheaply in case one was created since.\n const envFilePath = getEnvFilePath(env, options?.envFile);\n if (!envFilePath) return cachedEntry.parsedEnv;\n } else {\n try {\n const stats = statSync(cachedEntry.envFilePath);\n if (\n stats.mtimeMs === cachedEntry.mtimeMs &&\n stats.size === cachedEntry.size\n ) {\n return cachedEntry.parsedEnv;\n }\n } catch {\n // File was removed — fall through and re-resolve\n }\n }\n }\n\n const envFilePath = getEnvFilePath(env, options?.envFile);\n\n if (!envFilePath) {\n envFileCache.set(cacheKey, {\n envFilePath: undefined,\n mtimeMs: 0,\n size: 0,\n parsedEnv: {},\n });\n return {};\n }\n\n const parsedEnv = parseEnvFile(envFilePath);\n\n try {\n const stats = statSync(envFilePath);\n envFileCache.set(cacheKey, {\n envFilePath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n parsedEnv,\n });\n } catch {\n // Race: file removed between parse and stat — skip caching this round\n }\n\n return parsedEnv; // Return the parsed env object\n};\n"],"mappings":";;;;AAGA,MAAM;AAON,MAAa,kBACX,qBACA,YACuB;CAKvB,QAJiB,UACb,CAAC,OAAO,IACR;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;CAAM,EAE9C,CAAC,KAAK,UAAU;AACjC;;;;;;;AAkBA,MAAM,+BAAe,IAAI,IAA+B;AAExD,MAAM,gBAAgB,gBAAgD;CACpE,MAAM,YAAoC,CAAC;CAE3C,OAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;CACT,CAAC;CAED,OAAO;AACT;AAEA,MAAa,eACX,YAC2B;CAC3B,MAAM,MAAM,SAAS,OAAO;CAG5B,MAAM,WAAW,GAAG,QAAQ,IAAI,EAAE,GAAG,IAAI,GAAG,SAAS,WAAW;CAEhE,MAAM,cAAc,aAAa,IAAI,QAAQ;CAE7C,IAAI,aAAa;EACf,IAAI,YAAY,gBAAgB,QAG9B;OAAI,CADgB,eAAe,KAAK,SAAS,OAClC,GAAG,OAAO,YAAY;EAAS,OAE9C,IAAI;GACF,MAAM,QAAQ,SAAS,YAAY,WAAW;GAC9C,IACE,MAAM,YAAY,YAAY,WAC9B,MAAM,SAAS,YAAY,MAE3B,OAAO,YAAY;EAEvB,QAAQ,CAER;CAEJ;CAEA,MAAM,cAAc,eAAe,KAAK,SAAS,OAAO;CAExD,IAAI,CAAC,aAAa;EAChB,aAAa,IAAI,UAAU;GACzB,aAAa;GACb,SAAS;GACT,MAAM;GACN,WAAW,CAAC;EACd,CAAC;EACD,OAAO,CAAC;CACV;CAEA,MAAM,YAAY,aAAa,WAAW;CAE1C,IAAI;EACF,MAAM,QAAQ,SAAS,WAAW;EAClC,aAAa,IAAI,UAAU;GACzB;GACA,SAAS,MAAM;GACf,MAAM,MAAM;GACZ;EACF,CAAC;CACH,QAAQ,CAER;CAEA,OAAO;AACT"}
@@ -40,10 +40,11 @@ const getTransformationOptions = (filePath) => ({
40
40
  });
41
41
  const bundleFileSync = (code, filePath, options) => {
42
42
  const extension = extname(filePath);
43
+ const loader = getLoader(extension);
43
44
  return buildSync({
44
45
  stdin: {
45
46
  contents: code,
46
- loader: getLoader(extension),
47
+ loader,
47
48
  resolveDir: dirname(filePath),
48
49
  sourcefile: filePath
49
50
  },
@@ -53,10 +54,11 @@ const bundleFileSync = (code, filePath, options) => {
53
54
  };
54
55
  const bundleFile = async (code, filePath, options) => {
55
56
  const extension = extname(filePath);
57
+ const loader = getLoader(extension);
56
58
  return (await build({
57
59
  stdin: {
58
60
  contents: code,
59
- loader: getLoader(extension),
61
+ loader,
60
62
  resolveDir: dirname(filePath),
61
63
  sourcefile: filePath
62
64
  },
@@ -1 +1 @@
1
- {"version":3,"file":"bundleFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleFile.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Loader,\n type Plugin,\n} from 'esbuild';\n\nexport type ESBuildPlugin = Plugin;\n\nexport const getLoader = (extension: string): Loader => {\n switch (extension) {\n case '.js':\n return 'js';\n case '.jsx':\n return 'jsx';\n case '.mjs':\n return 'js';\n case '.ts':\n return 'ts';\n case '.tsx':\n return 'tsx';\n case '.cjs':\n return 'js';\n case '.json':\n return 'json';\n case '.md':\n return 'text';\n case '.mdx':\n return 'text';\n default:\n return 'js';\n }\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node16',\n platform: 'neutral',\n write: false,\n packages: 'bundle',\n external: ['esbuild'],\n bundle: true,\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const bundleFileSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const bundleFile = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":";;;;;AAaA,MAAa,aAAa,cAA8B;CACtD,QAAQ,WAAR;EACE,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;CACA,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,UAAU,CAAC,SAAS;CACpB,QAAQ;CACR,QAAQ,EACN,mBAAmB,KAAK,UAAU,cAAc,QAAQ,CAAC,CAAC,IAAI,EAChE;AACF;AAEA,MAAa,kBACX,MACA,UACA,YACuB;CACvB,MAAM,YAAY,QAAQ,QAAQ;CAgBlC,OAbkC,UAAU;EAC1C,OAAO;GACL,UAAU;GACV,QALW,UAAU,SAKhB;GACL,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAEsC,CAAC,CAAC,cAAc,EAAE,CAAC;AAG3D;AAEA,MAAa,aAAa,OACxB,MACA,UACA,YACgC;CAChC,MAAM,YAAY,QAAQ,QAAQ;CAgBlC,QAF2B,MAXa,MAAM;EAC5C,OAAO;GACL,UAAU;GACV,QALW,UAAU,SAKhB;GACL,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC,EAEsC,CAAC,cAAc,EAAE,CAAC;AAG3D"}
1
+ {"version":3,"file":"bundleFile.mjs","names":[],"sources":["../../../src/loadExternalFile/bundleFile.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Loader,\n type Plugin,\n} from 'esbuild';\n\nexport type ESBuildPlugin = Plugin;\n\nexport const getLoader = (extension: string): Loader => {\n switch (extension) {\n case '.js':\n return 'js';\n case '.jsx':\n return 'jsx';\n case '.mjs':\n return 'js';\n case '.ts':\n return 'ts';\n case '.tsx':\n return 'tsx';\n case '.cjs':\n return 'js';\n case '.json':\n return 'json';\n case '.md':\n return 'text';\n case '.mdx':\n return 'text';\n default:\n return 'js';\n }\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node16',\n platform: 'neutral',\n write: false,\n packages: 'bundle',\n external: ['esbuild'],\n bundle: true,\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const bundleFileSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const bundleFile = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":";;;;;AAaA,MAAa,aAAa,cAA8B;CACtD,QAAQ,WAAR;EACE,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;CACA,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,UAAU,CAAC,SAAS;CACpB,QAAQ;CACR,QAAQ,EACN,mBAAmB,KAAK,UAAU,cAAc,QAAQ,CAAC,CAAC,IAAI,EAChE;AACF;AAEA,MAAa,kBACX,MACA,UACA,YACuB;CACvB,MAAM,YAAY,QAAQ,QAAQ;CAClC,MAAM,SAAS,UAAU,SAAS;CAelC,OAbkC,UAAU;EAC1C,OAAO;GACL,UAAU;GACV;GACA,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAEsC,CAAC,CAAC,cAAc,EAAE,CAAC;AAG3D;AAEA,MAAa,aAAa,OACxB,MACA,UACA,YACgC;CAChC,MAAM,YAAY,QAAQ,QAAQ;CAClC,MAAM,SAAS,UAAU,SAAS;CAelC,QAF2B,MAXa,MAAM;EAC5C,OAAO;GACL,UAAU;GACV;GACA,YAAY,QAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC,EAEsC,CAAC,cAAc,EAAE,CAAC;AAG3D"}
@@ -17,7 +17,8 @@ const loadExternalFileSync = (filePath, options) => {
17
17
  const fileExtension = extname(filePath) || ".json";
18
18
  try {
19
19
  if (fileExtension === ".json" || fileExtension === ".json5" || fileExtension === ".jsonc") return parseJSON5(readFileSync(filePath, "utf-8"));
20
- const moduleResultString = transpileTSToCJSSync(readFileSync(filePath, "utf-8"), filePath, options?.buildOptions);
20
+ const code = readFileSync(filePath, "utf-8");
21
+ const moduleResultString = transpileTSToCJSSync(code, filePath, options?.buildOptions);
21
22
  if (!moduleResultString) {
22
23
  logger("File could not be loaded.", { level: "error" });
23
24
  return;
@@ -67,7 +68,8 @@ const loadExternalFile = async (filePath, options) => {
67
68
  const fileContent = await readFile(filePath, "utf-8");
68
69
  return parseJSON5(fileContent);
69
70
  }
70
- const moduleResultString = await transpileTSToCJS(await readFile(filePath, "utf-8"), filePath, options?.buildOptions);
71
+ const code = await readFile(filePath, "utf-8");
72
+ const moduleResultString = await transpileTSToCJS(code, filePath, options?.buildOptions);
71
73
  if (!moduleResultString) {
72
74
  logger("File could not be loaded.", { level: "error" });
73
75
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"loadExternalFile.mjs","names":[],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // fully restores the globals before returning.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const previousValues: Record<string, unknown> = {};\n const previouslyPresent: Record<string, boolean> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n previouslyPresent[key] = key in globalVars;\n previousValues[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n // `in` check (not `!== undefined`) so a global that legitimately held\n // `undefined` is restored rather than deleted.\n if (previouslyPresent[key]) {\n globalVars[key] = previousValues[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAiBA,MAAM,aAAa,MAAM,SAAU,MAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,gBAAgB,QAAQ,QAAQ,KAAK;CAE3C,IAAI;EACF,IACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,UAGlB,OAAO,WAAW,aAAa,UAAU,OAAO,CAAC;EAMnD,MAAM,qBAAyC,qBAFlC,aAAa,UAAU,OAG/B,GACH,UACA,SAAS,YACX;EAEA,IAAI,CAAC,oBAAoB;GACvB,OAAO,6BAA6B,EAAE,OAAO,QAAQ,CAAC;GACtD;EACF;EAIA,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SA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CAAC,CACH;EAEA,IAAI,OAAO,gBAAgB,aAAa;GACtC,OAAO,oCAAoC,aAAa,QAAQ,GAAG;GACnE;EACF;EAEA,OAAO;CACT,SAAS,OAAO;EACd,IAAI,SAAS,YAAY,MACvB,OACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,CAAC,CAChD,GACA,EACE,OAAO,QACT,CACF;CAEJ;AACF"}
1
+ {"version":3,"file":"loadExternalFile.mjs","names":[],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // fully restores the globals before returning.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const previousValues: Record<string, unknown> = {};\n const previouslyPresent: Record<string, boolean> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n previouslyPresent[key] = key in globalVars;\n previousValues[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n // `in` check (not `!== undefined`) so a global that legitimately held\n // `undefined` is restored rather than deleted.\n if (previouslyPresent[key]) {\n globalVars[key] = previousValues[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;AAiBA,MAAM,aAAa,MAAM,SAAU,MAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,gBAAgB,QAAQ,QAAQ,KAAK;CAE3C,IAAI;EACF,IACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,UAGlB,OAAO,WAAW,aAAa,UAAU,OAAO,CAAC;EAInD,MAAM,OAAO,aAAa,UAAU,OAAO;EAE3C,MAAM,qBAAyC,qBAC7C,MACA,UACA,SAAS,YACX;EAEA,IAAI,CAAC,oBAAoB;GACvB,OAAO,6BAA6B,EAAE,OAAO,QAAQ,CAAC;GACtD;EACF;EAIA,MAAM,cAAc,qBAAqB,SAAS,sBAChD,iBAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,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GAChB,SAAS,SAAS;EACpB,CAAC,CACH;EAEA,IAAI,OAAO,gBAAgB,aAAa;GACtC,OAAO,oCAAoC,aAAa,QAAQ,GAAG;GACnE;EACF;EAEA,OAAO;CACT,SAAS,OAAO;EACd,IAAI,SAAS,YAAY,MACvB,OACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,CAAC,CAChD,GACA,EACE,OAAO,QACT,CACF;CAEJ;AACF"}
@@ -117,7 +117,8 @@ const clearTranspileCache = () => {
117
117
  tsConfigPathCache.clear();
118
118
  };
119
119
  const transpileTSToCJSSync = (code, filePath, options) => {
120
- const loader = getLoader(extname(filePath));
120
+ const extension = extname(filePath);
121
+ const loader = getLoader(extension);
121
122
  const { esbuildInstance, ...buildOptions } = options ?? {};
122
123
  const codeHash = computeKeyId([code]);
123
124
  const optionsKey = computeKeyId([buildOptions]);
@@ -158,7 +159,8 @@ const transpileTSToCJSSync = (code, filePath, options) => {
158
159
  return moduleResultString;
159
160
  };
160
161
  const transpileTSToCJS = async (code, filePath, options) => {
161
- const loader = getLoader(extname(filePath));
162
+ const extension = extname(filePath);
163
+ const loader = getLoader(extension);
162
164
  const { esbuildInstance, ...buildOptions } = options ?? {};
163
165
  const codeHash = computeKeyId([code]);
164
166
  const optionsKey = computeKeyId([buildOptions]);
@@ -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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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 // 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;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;;;;;;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AiB,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 +1 @@
1
- {"version":3,"file":"ESMxCJSHelpers.mjs","names":[],"sources":["../../../src/utils/ESMxCJSHelpers.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { getPackageJsonPath } from './getPackageJsonPath';\n\nexport const isESModule = typeof import.meta.url === 'string';\n\n/**\n * Require relative to the user project\n *\n * Note: Can resolve package that are installed in the user project, ex `'intlayer'`\n */\nexport const getProjectRequire = (startDir?: string): NodeJS.Require => {\n // Can fail on VSCode extensions\n const { packageJsonPath } = getPackageJsonPath(startDir);\n\n return createRequire(packageJsonPath);\n};\n\n/**\n * Require relative to the @intlayer/config package\n *\n * Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`\n */\nexport const configESMxCJSRequire: NodeJS.Require = isESModule\n ? createRequire(import.meta.url)\n : require;\n"],"mappings":";;;;;AAGA,MAAa,aAAa,OAAO,OAAO,KAAK,QAAQ;;;;;;AAOrD,MAAa,qBAAqB,aAAsC;CAEtE,MAAM,EAAE,oBAAoB,mBAAmB,QAAQ;CAEvD,OAAO,cAAc,eAAe;AACtC;;;;;;AAOA,MAAa,uBAAuC,aAChD,cAAc,OAAO,KAAK,GAAG"}
1
+ {"version":3,"file":"ESMxCJSHelpers.mjs","names":[],"sources":["../../../src/utils/ESMxCJSHelpers.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { getPackageJsonPath } from './getPackageJsonPath';\n\nexport const isESModule = typeof import.meta.url === 'string';\n\n/**\n * Require relative to the user project\n *\n * Note: Can resolve package that are installed in the user project, ex `'intlayer'`\n */\nexport const getProjectRequire = (startDir?: string): NodeJS.Require => {\n // Can fail on VSCode extensions\n const { packageJsonPath } = getPackageJsonPath(startDir);\n\n return createRequire(packageJsonPath);\n};\n\n/**\n * Require relative to the @intlayer/config package\n *\n * Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`\n */\nexport const configESMxCJSRequire: NodeJS.Require = isESModule\n ? createRequire(import.meta.url)\n : require;\n"],"mappings":";;;;;AAGA,MAAa,aAAa,OAAO,YAAY,QAAQ;;;;;;AAOrD,MAAa,qBAAqB,aAAsC;CAEtE,MAAM,EAAE,oBAAoB,mBAAmB,QAAQ;CAEvD,OAAO,cAAc,eAAe;AACtC;;;;;;AAOA,MAAa,uBAAuC,aAChD,cAAc,YAAY,GAAG"}
@@ -7,13 +7,48 @@ const getAlias = ({ configuration, format, formatter = (value) => value }) => {
7
7
  const extension = getExtension(configuration, format ?? configuration.build.outputFormat[0] ?? "esm");
8
8
  const { baseDir } = configuration.system;
9
9
  const { mainDir, configDir } = configuration.system;
10
+ /**
11
+ * Dictionaries
12
+ */
13
+ const dictionariesPath = join(mainDir, `dictionaries.${extension}`);
14
+ const relativeDictionariesPath = relative(baseDir, dictionariesPath);
15
+ const fixedDictionariesPath = formatter(normalizePath(relativeDictionariesPath));
16
+ /**
17
+ * Unmerged dictionaries
18
+ */
19
+ const unmergedDictionariesPath = join(mainDir, `unmerged_dictionaries.${extension}`);
20
+ const relativeUnmergedDictionariesPath = relative(baseDir, unmergedDictionariesPath);
21
+ const fixedUnmergedDictionariesPath = formatter(normalizePath(relativeUnmergedDictionariesPath));
22
+ /**
23
+ * Remote dictionaries
24
+ */
25
+ const remoteDictionariesPath = join(mainDir, `remote_dictionaries.${extension}`);
26
+ const relativeRemoteDictionariesPath = relative(baseDir, remoteDictionariesPath);
27
+ const fixedRemoteDictionariesPath = formatter(normalizePath(relativeRemoteDictionariesPath));
28
+ /**
29
+ * Dynamic dictionaries
30
+ */
31
+ const dynamicDictionariesPath = join(mainDir, `dynamic_dictionaries.${extension}`);
32
+ const relativeDynamicDictionariesPath = relative(baseDir, dynamicDictionariesPath);
33
+ const fixedDynamicDictionariesPath = formatter(normalizePath(relativeDynamicDictionariesPath));
34
+ /**
35
+ * Fetch dictionaries
36
+ */
37
+ const fetchDictionariesPath = join(mainDir, `fetch_dictionaries.${extension}`);
38
+ const relativeFetchDictionariesPath = relative(baseDir, fetchDictionariesPath);
39
+ const fixedFetchDictionariesPath = formatter(normalizePath(relativeFetchDictionariesPath));
40
+ /**
41
+ * Configuration
42
+ */
43
+ const configurationPath = join(configDir, `configuration.${extension}`);
44
+ const relativeConfigurationPath = relative(baseDir, configurationPath);
10
45
  return {
11
- "@intlayer/dictionaries-entry": formatter(normalizePath(relative(baseDir, join(mainDir, `dictionaries.${extension}`)))),
12
- "@intlayer/unmerged-dictionaries-entry": formatter(normalizePath(relative(baseDir, join(mainDir, `unmerged_dictionaries.${extension}`)))),
13
- "@intlayer/remote-dictionaries-entry": formatter(normalizePath(relative(baseDir, join(mainDir, `remote_dictionaries.${extension}`)))),
14
- "@intlayer/dynamic-dictionaries-entry": formatter(normalizePath(relative(baseDir, join(mainDir, `dynamic_dictionaries.${extension}`)))),
15
- "@intlayer/fetch-dictionaries-entry": formatter(normalizePath(relative(baseDir, join(mainDir, `fetch_dictionaries.${extension}`)))),
16
- "@intlayer/config/built": formatter(normalizePath(relative(baseDir, join(configDir, `configuration.${extension}`))))
46
+ "@intlayer/dictionaries-entry": fixedDictionariesPath,
47
+ "@intlayer/unmerged-dictionaries-entry": fixedUnmergedDictionariesPath,
48
+ "@intlayer/remote-dictionaries-entry": fixedRemoteDictionariesPath,
49
+ "@intlayer/dynamic-dictionaries-entry": fixedDynamicDictionariesPath,
50
+ "@intlayer/fetch-dictionaries-entry": fixedFetchDictionariesPath,
51
+ "@intlayer/config/built": formatter(normalizePath(relativeConfigurationPath))
17
52
  };
18
53
  };
19
54
 
@@ -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\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 } = configuration.system;\n const { mainDir, configDir } = configuration.system;\n\n /**\n * Dictionaries\n */\n const dictionariesPath = join(mainDir, `dictionaries.${extension}`);\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n const fixedDictionariesPath = formatter(\n normalizePath(relativeDictionariesPath)\n );\n\n /**\n * Unmerged dictionaries\n */\n const unmergedDictionariesPath = join(\n mainDir,\n `unmerged_dictionaries.${extension}`\n );\n const relativeUnmergedDictionariesPath = relative(\n baseDir,\n unmergedDictionariesPath\n );\n const fixedUnmergedDictionariesPath = formatter(\n normalizePath(relativeUnmergedDictionariesPath)\n );\n\n /**\n * Remote dictionaries\n */\n const remoteDictionariesPath = join(\n mainDir,\n `remote_dictionaries.${extension}`\n );\n const relativeRemoteDictionariesPath = relative(\n baseDir,\n remoteDictionariesPath\n );\n const fixedRemoteDictionariesPath = formatter(\n normalizePath(relativeRemoteDictionariesPath)\n );\n\n /**\n * Dynamic dictionaries\n */\n const dynamicDictionariesPath = join(\n mainDir,\n `dynamic_dictionaries.${extension}`\n );\n const relativeDynamicDictionariesPath = relative(\n baseDir,\n dynamicDictionariesPath\n );\n const fixedDynamicDictionariesPath = formatter(\n normalizePath(relativeDynamicDictionariesPath)\n );\n\n /**\n * Fetch dictionaries\n */\n const fetchDictionariesPath = join(\n mainDir,\n `fetch_dictionaries.${extension}`\n );\n const relativeFetchDictionariesPath = relative(\n baseDir,\n fetchDictionariesPath\n );\n const fixedFetchDictionariesPath = formatter(\n normalizePath(relativeFetchDictionariesPath)\n );\n\n /**\n * Configuration\n */\n const configurationPath = join(configDir, `configuration.${extension}`);\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n const fixedConfigurationPath = formatter(\n normalizePath(relativeConfigurationPath)\n );\n\n return {\n '@intlayer/dictionaries-entry': fixedDictionariesPath,\n '@intlayer/unmerged-dictionaries-entry': fixedUnmergedDictionariesPath,\n '@intlayer/remote-dictionaries-entry': fixedRemoteDictionariesPath,\n '@intlayer/dynamic-dictionaries-entry': fixedDynamicDictionariesPath,\n '@intlayer/fetch-dictionaries-entry': fixedFetchDictionariesPath,\n '@intlayer/config/built': fixedConfigurationPath,\n } as const;\n};\n"],"mappings":";;;;;AAWA,MAAa,YAAY,EACvB,eACA,QACA,aAAa,UAAkB,YACV;CACrB,MAAM,YAAY,aAChB,eACA,UAAU,cAAc,MAAM,aAAa,MAAM,KACnD;CAEA,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,SAAS,cAAc,cAAc;CAgF7C,OAAO;EACL,gCA1E4B,UAC5B,cAF+B,SAAS,SADjB,KAAK,SAAS,gBAAgB,WACW,CAE3B,CAAC,CAyEc;EACpD,yCA5DoC,UACpC,cALuC,SACvC,SAL+B,KAC/B,SACA,yBAAyB,WAIF,CAGsB,CAAC,CA2DuB;EACrE,uCA9CkC,UAClC,cALqC,SACrC,SAL6B,KAC7B,SACA,uBAAuB,WAIF,CAGsB,CAAC,CA6CqB;EACjE,wCAhCmC,UACnC,cALsC,SACtC,SAL8B,KAC9B,SACA,wBAAwB,WAIF,CAGsB,CAAC,CA+BsB;EACnE,sCAlBiC,UACjC,cALoC,SACpC,SAL4B,KAC5B,SACA,sBAAsB,WAIF,CAGsB,CAAC,CAiBoB;EAC/D,0BAV6B,UAC7B,cAFgC,SAAS,SADjB,KAAK,WAAW,iBAAiB,WACS,CAE5B,CAAC,CASQ;CACjD;AACF"}
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\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 } = configuration.system;\n const { mainDir, configDir } = configuration.system;\n\n /**\n * Dictionaries\n */\n const dictionariesPath = join(mainDir, `dictionaries.${extension}`);\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n const fixedDictionariesPath = formatter(\n normalizePath(relativeDictionariesPath)\n );\n\n /**\n * Unmerged dictionaries\n */\n const unmergedDictionariesPath = join(\n mainDir,\n `unmerged_dictionaries.${extension}`\n );\n const relativeUnmergedDictionariesPath = relative(\n baseDir,\n unmergedDictionariesPath\n );\n const fixedUnmergedDictionariesPath = formatter(\n normalizePath(relativeUnmergedDictionariesPath)\n );\n\n /**\n * Remote dictionaries\n */\n const remoteDictionariesPath = join(\n mainDir,\n `remote_dictionaries.${extension}`\n );\n const relativeRemoteDictionariesPath = relative(\n baseDir,\n remoteDictionariesPath\n );\n const fixedRemoteDictionariesPath = formatter(\n normalizePath(relativeRemoteDictionariesPath)\n );\n\n /**\n * Dynamic dictionaries\n */\n const dynamicDictionariesPath = join(\n mainDir,\n `dynamic_dictionaries.${extension}`\n );\n const relativeDynamicDictionariesPath = relative(\n baseDir,\n dynamicDictionariesPath\n );\n const fixedDynamicDictionariesPath = formatter(\n normalizePath(relativeDynamicDictionariesPath)\n );\n\n /**\n * Fetch dictionaries\n */\n const fetchDictionariesPath = join(\n mainDir,\n `fetch_dictionaries.${extension}`\n );\n const relativeFetchDictionariesPath = relative(\n baseDir,\n fetchDictionariesPath\n );\n const fixedFetchDictionariesPath = formatter(\n normalizePath(relativeFetchDictionariesPath)\n );\n\n /**\n * Configuration\n */\n const configurationPath = join(configDir, `configuration.${extension}`);\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n const fixedConfigurationPath = formatter(\n normalizePath(relativeConfigurationPath)\n );\n\n return {\n '@intlayer/dictionaries-entry': fixedDictionariesPath,\n '@intlayer/unmerged-dictionaries-entry': fixedUnmergedDictionariesPath,\n '@intlayer/remote-dictionaries-entry': fixedRemoteDictionariesPath,\n '@intlayer/dynamic-dictionaries-entry': fixedDynamicDictionariesPath,\n '@intlayer/fetch-dictionaries-entry': fixedFetchDictionariesPath,\n '@intlayer/config/built': fixedConfigurationPath,\n } as const;\n};\n"],"mappings":";;;;;AAWA,MAAa,YAAY,EACvB,eACA,QACA,aAAa,UAAkB,YACV;CACrB,MAAM,YAAY,aAChB,eACA,UAAU,cAAc,MAAM,aAAa,MAAM,KACnD;CAEA,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,SAAS,cAAc,cAAc;;;;CAK7C,MAAM,mBAAmB,KAAK,SAAS,gBAAgB,WAAW;CAClE,MAAM,2BAA2B,SAAS,SAAS,gBAAgB;CACnE,MAAM,wBAAwB,UAC5B,cAAc,wBAAwB,CACxC;;;;CAKA,MAAM,2BAA2B,KAC/B,SACA,yBAAyB,WAC3B;CACA,MAAM,mCAAmC,SACvC,SACA,wBACF;CACA,MAAM,gCAAgC,UACpC,cAAc,gCAAgC,CAChD;;;;CAKA,MAAM,yBAAyB,KAC7B,SACA,uBAAuB,WACzB;CACA,MAAM,iCAAiC,SACrC,SACA,sBACF;CACA,MAAM,8BAA8B,UAClC,cAAc,8BAA8B,CAC9C;;;;CAKA,MAAM,0BAA0B,KAC9B,SACA,wBAAwB,WAC1B;CACA,MAAM,kCAAkC,SACtC,SACA,uBACF;CACA,MAAM,+BAA+B,UACnC,cAAc,+BAA+B,CAC/C;;;;CAKA,MAAM,wBAAwB,KAC5B,SACA,sBAAsB,WACxB;CACA,MAAM,gCAAgC,SACpC,SACA,qBACF;CACA,MAAM,6BAA6B,UACjC,cAAc,6BAA6B,CAC7C;;;;CAKA,MAAM,oBAAoB,KAAK,WAAW,iBAAiB,WAAW;CACtE,MAAM,4BAA4B,SAAS,SAAS,iBAAiB;CAKrE,OAAO;EACL,gCAAgC;EAChC,yCAAyC;EACzC,uCAAuC;EACvC,wCAAwC;EACxC,sCAAsC;EACtC,0BAV6B,UAC7B,cAAc,yBAAyB,CASQ;CACjD;AACF"}
@@ -55,7 +55,8 @@ const cacheDisk = (intlayerConfig, keys, options) => {
55
55
  let raw = await readFile(filePath);
56
56
  const flag = raw[0];
57
57
  raw = raw.subarray(1);
58
- const deserialized = deserialize(flag === 1 ? gunzipSync(raw) : raw);
58
+ const payload = flag === 1 ? gunzipSync(raw) : raw;
59
+ const deserialized = deserialize(payload);
59
60
  let value;
60
61
  const maybeObj = deserialized;
61
62
  if (!!maybeObj && typeof maybeObj === "object" && typeof maybeObj.version === "string" && typeof maybeObj.timestamp === "number" && Object.hasOwn(maybeObj, "data")) {
@@ -154,7 +155,8 @@ const cacheDisk = (intlayerConfig, keys, options) => {
154
155
  let raw = await readFile(filePath);
155
156
  const flag = raw[0];
156
157
  raw = raw.subarray(1);
157
- const maybeObj = deserialize(flag === 1 ? gunzipSync(raw) : raw);
158
+ const payload = flag === 1 ? gunzipSync(raw) : raw;
159
+ const maybeObj = deserialize(payload);
158
160
  if (!!maybeObj && typeof maybeObj === "object" && typeof maybeObj.version === "string" && typeof maybeObj.timestamp === "number" && Object.hasOwn(maybeObj, "data")) {
159
161
  const entry = maybeObj;
160
162
  if (entry.version !== configPackageJson.version) return false;
@@ -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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tB;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
+ {"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,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,gBAC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;IACvC,QAAQ,CAAC;GACX;EACF;;EAEA,SAAS,YAA8B;GAErC,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"}
@@ -2,7 +2,7 @@ import { COOKIE_NAME, HEADER_NAME, LOCALE_STORAGE_NAME } from "../defaultValues/
2
2
 
3
3
  //#region src/utils/getStorageAttributes.ts
4
4
  /** Number of seconds in a day, used to convert a `number` of days. */
5
- const SECONDS_PER_DAY = 3600 * 24;
5
+ const SECONDS_PER_DAY = 86400;
6
6
  /**
7
7
  * Merges the user-facing `expires` and `maxAge` into a single, normalized and
8
8
  * serialization-safe expiry consumed by the client runtime.
@@ -1 +1 @@
1
- {"version":3,"file":"getStorageAttributes.mjs","names":[],"sources":["../../../src/utils/getStorageAttributes.ts"],"sourcesContent":["import type {\n CookiesAttributes,\n ProcessedCookieAttributes,\n ProcessedStorageAttributes,\n RoutingStorageInput,\n StorageAttributes,\n} from '@intlayer/types/config';\nimport {\n COOKIE_NAME,\n HEADER_NAME,\n LOCALE_STORAGE_NAME,\n} from '../defaultValues/routing';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype CookieEntry = {\n name: string;\n attributes: ProcessedCookieAttributes;\n};\n\n/** Number of seconds in a day, used to convert a `number` of days. */\nconst SECONDS_PER_DAY = 60 * 60 * 24;\n\ntype WebStorageEntry = {\n name: string;\n};\n\ntype HeaderEntry = {\n name: string;\n};\n\ntype StorageEntry =\n | 'cookie'\n | 'localStorage'\n | 'sessionStorage'\n | 'header'\n | CookiesAttributes\n | StorageAttributes;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Merges the user-facing `expires` and `maxAge` into a single, normalized and\n * serialization-safe expiry consumed by the client runtime.\n *\n * Precedence and normalization:\n * - `maxAge` (seconds) wins when set and is the internal unit (relative);\n * - `expires` as a `number` is interpreted as **days** and converted to\n * seconds (relative);\n * - `expires` as a `Date` (possibly a cross-realm instance, since config files\n * run in a `node:vm` sandbox) or an ISO string becomes an ISO **string**\n * (absolute). Strings survive `JSON.stringify`, unlike a `Date`.\n *\n * The result is therefore: a `number` = seconds from creation, a `string` =\n * absolute ISO date, or `undefined` for a session cookie.\n */\nconst normalizeCookieExpiry = (\n expires: CookiesAttributes['expires'],\n maxAge: CookiesAttributes['maxAge']\n): number | string | undefined => {\n if (typeof maxAge === 'number') return maxAge;\n if (expires === undefined) return undefined;\n if (\n expires instanceof Date ||\n Object.prototype.toString.call(expires) === '[object Date]'\n ) {\n return (expires as Date).toISOString();\n }\n if (typeof expires === 'string') return expires;\n return expires * SECONDS_PER_DAY;\n};\n\nconst createCookieEntry = (\n options?: Partial<CookiesAttributes>\n): CookieEntry => {\n const {\n name,\n path = '/',\n expires,\n maxAge,\n domain,\n secure,\n sameSite,\n httpOnly,\n } = options ?? {};\n return {\n name: name ?? COOKIE_NAME,\n attributes: {\n path,\n expires: normalizeCookieExpiry(expires, maxAge),\n domain,\n secure,\n sameSite,\n httpOnly,\n },\n };\n};\n\nconst createWebStorageEntry = (\n options?: Partial<StorageAttributes>\n): WebStorageEntry => ({\n name: options?.name ?? LOCALE_STORAGE_NAME,\n});\n\nconst createHeaderEntry = (\n options?: Partial<StorageAttributes>\n): HeaderEntry => ({\n name: options?.name ?? HEADER_NAME,\n});\n\nconst isCookieEntry = (entry: unknown): boolean => {\n if (typeof entry !== 'object' || entry === null) return false;\n const e = entry as Record<string, unknown>;\n return (\n e['type'] === 'cookie' ||\n 'sameSite' in e ||\n 'httpOnly' in e ||\n 'secure' in e\n );\n};\n\nconst isStorageType = (\n value: string\n): value is 'cookie' | 'localStorage' | 'sessionStorage' | 'header' =>\n value === 'cookie' ||\n value === 'localStorage' ||\n value === 'sessionStorage' ||\n value === 'header';\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\nconst processStorageEntry = (\n entry: StorageEntry\n): Partial<ProcessedStorageAttributes> => {\n if (typeof entry === 'string') {\n if (!isStorageType(entry)) {\n return { cookies: [], localStorage: [], sessionStorage: [], headers: [] };\n }\n if (entry === 'cookie') return { cookies: [createCookieEntry()] };\n if (entry === 'localStorage')\n return { localStorage: [createWebStorageEntry()] };\n if (entry === 'sessionStorage')\n return { sessionStorage: [createWebStorageEntry()] };\n if (entry === 'header') return { headers: [createHeaderEntry()] };\n }\n\n if (typeof entry === 'object' && entry !== null) {\n const typedEntry = entry as CookiesAttributes | StorageAttributes;\n\n if (isCookieEntry(typedEntry)) {\n return { cookies: [createCookieEntry(typedEntry as CookiesAttributes)] };\n }\n if ('type' in typedEntry && typedEntry.type === 'localStorage') {\n return {\n localStorage: [createWebStorageEntry(typedEntry as StorageAttributes)],\n };\n }\n if ('type' in typedEntry && typedEntry.type === 'sessionStorage') {\n return {\n sessionStorage: [\n createWebStorageEntry(typedEntry as StorageAttributes),\n ],\n };\n }\n if ('type' in typedEntry && typedEntry.type === 'header') {\n return { headers: [createHeaderEntry(typedEntry as StorageAttributes)] };\n }\n // Default to localStorage for ambiguous objects\n return {\n localStorage: [\n createWebStorageEntry(typedEntry as Omit<StorageAttributes, 'type'>),\n ],\n };\n }\n\n return { cookies: [], localStorage: [], sessionStorage: [], headers: [] };\n};\n\nconst mergeStorageAttributes = (\n accumulated: ProcessedStorageAttributes,\n partial: Partial<ProcessedStorageAttributes>\n): ProcessedStorageAttributes => ({\n cookies: [...(accumulated.cookies ?? []), ...(partial.cookies ?? [])],\n localStorage: [\n ...(accumulated.localStorage ?? []),\n ...(partial.localStorage ?? []),\n ],\n sessionStorage: [\n ...(accumulated.sessionStorage ?? []),\n ...(partial.sessionStorage ?? []),\n ],\n headers: [...(accumulated.headers ?? []), ...(partial.headers ?? [])],\n});\n\n/**\n * Extracts and normalizes storage configuration into separate arrays for each storage type.\n * Called at config-build time so the result is pre-computed and stored in the config.\n *\n * @param options - The storage configuration from IntlayerConfig\n * @returns An object containing arrays for cookies, localStorage, sessionStorage and headers\n */\nexport const getStorageAttributes = (\n options: RoutingStorageInput\n): ProcessedStorageAttributes => {\n const emptyResult: ProcessedStorageAttributes = {\n cookies: [],\n localStorage: [],\n sessionStorage: [],\n headers: [],\n };\n\n if (options === false || options === undefined) return {};\n\n const result = Array.isArray(options)\n ? options.reduce<ProcessedStorageAttributes>((acc, entry) => {\n const partial = processStorageEntry(entry);\n return mergeStorageAttributes(acc, partial);\n }, emptyResult)\n : mergeStorageAttributes(emptyResult, processStorageEntry(options));\n\n // Remove empty arrays\n const cleanedResult: ProcessedStorageAttributes = {};\n\n if (result.cookies && result.cookies.length > 0) {\n cleanedResult.cookies = result.cookies;\n }\n\n if (result.localStorage && result.localStorage.length > 0) {\n cleanedResult.localStorage = result.localStorage;\n }\n\n if (result.sessionStorage && result.sessionStorage.length > 0) {\n cleanedResult.sessionStorage = result.sessionStorage;\n }\n\n if (result.headers && result.headers.length > 0) {\n cleanedResult.headers = result.headers;\n }\n\n return cleanedResult;\n};\n"],"mappings":";;;;AAuBA,MAAM,kBAAkB,OAAU;;;;;;;;;;;;;;;;AAqClC,MAAM,yBACJ,SACA,WACgC;CAChC,IAAI,OAAO,WAAW,UAAU,OAAO;CACvC,IAAI,YAAY,QAAW,OAAO;CAClC,IACE,mBAAmB,QACnB,OAAO,UAAU,SAAS,KAAK,OAAO,MAAM,iBAE5C,OAAQ,QAAiB,YAAY;CAEvC,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,OAAO,UAAU;AACnB;AAEA,MAAM,qBACJ,YACgB;CAChB,MAAM,EACJ,MACA,OAAO,KACP,SACA,QACA,QACA,QACA,UACA,aACE,WAAW,CAAC;CAChB,OAAO;EACL,MAAM;EACN,YAAY;GACV;GACA,SAAS,sBAAsB,SAAS,MAAM;GAC9C;GACA;GACA;GACA;EACF;CACF;AACF;AAEA,MAAM,yBACJ,aACqB,EACrB,MAAM,SAAS,0BACjB;AAEA,MAAM,qBACJ,aACiB,EACjB,MAAM,SAAS,4BACjB;AAEA,MAAM,iBAAiB,UAA4B;CACjD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,IAAI;CACV,OACE,EAAE,YAAY,YACd,cAAc,KACd,cAAc,KACd,YAAY;AAEhB;AAEA,MAAM,iBACJ,UAEA,UAAU,YACV,UAAU,kBACV,UAAU,oBACV,UAAU;AAMZ,MAAM,uBACJ,UACwC;CACxC,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,cAAc,KAAK,GACtB,OAAO;GAAE,SAAS,CAAC;GAAG,cAAc,CAAC;GAAG,gBAAgB,CAAC;GAAG,SAAS,CAAC;EAAE;EAE1E,IAAI,UAAU,UAAU,OAAO,EAAE,SAAS,CAA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/B,MAAM,cAA0C;EAC9C,SAAS,CAAC;EACV,cAAc,CAAC;EACf,gBAAgB,CAAC;EACjB,SAAS,CAAC;CACZ;CAEA,IAAI,YAAY,SAAS,YAAY,QAAW,OAAO,CAAC;CAExD,MAAM,SAAS,MAAM,QAAQ,OAAO,IAChC,QAAQ,QAAoC,KAAK,UAAU;EACzD,MAAM,UAAU,oBAAoB,KAAK;EACzC,OAAO,uBAAuB,KAAK,OAAO;CAC5C,GAAG,WAAW,IACd,uBAAuB,aAAa,oBAAoB,OAAO,CAAC;CAGpE,MAAM,gBAA4C,CAAC;CAEnD,IAAI,OAAO,WAAW,OAAO,QAAQ,SAAS,GAC5C,cAAc,UAAU,OAAO;CAGjC,IAAI,OAAO,gBAAgB,OAAO,aAAa,SAAS,GACtD,cAAc,eAAe,OAAO;CAGtC,IAAI,OAAO,kBAAkB,OAAO,eAAe,SAAS,GAC1D,cAAc,iBAAiB,OAAO;CAGxC,IAAI,OAAO,WAAW,OAAO,QAAQ,SAAS,GAC5C,cAAc,UAAU,OAAO;CAGjC,OAAO;AACT"}
1
+ {"version":3,"file":"getStorageAttributes.mjs","names":[],"sources":["../../../src/utils/getStorageAttributes.ts"],"sourcesContent":["import type {\n CookiesAttributes,\n ProcessedCookieAttributes,\n ProcessedStorageAttributes,\n RoutingStorageInput,\n StorageAttributes,\n} from '@intlayer/types/config';\nimport {\n COOKIE_NAME,\n HEADER_NAME,\n LOCALE_STORAGE_NAME,\n} from '../defaultValues/routing';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype CookieEntry = {\n name: string;\n attributes: ProcessedCookieAttributes;\n};\n\n/** Number of seconds in a day, used to convert a `number` of days. */\nconst SECONDS_PER_DAY = 60 * 60 * 24;\n\ntype WebStorageEntry = {\n name: string;\n};\n\ntype HeaderEntry = {\n name: string;\n};\n\ntype StorageEntry =\n | 'cookie'\n | 'localStorage'\n | 'sessionStorage'\n | 'header'\n | CookiesAttributes\n | StorageAttributes;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Merges the user-facing `expires` and `maxAge` into a single, normalized and\n * serialization-safe expiry consumed by the client runtime.\n *\n * Precedence and normalization:\n * - `maxAge` (seconds) wins when set and is the internal unit (relative);\n * - `expires` as a `number` is interpreted as **days** and converted to\n * seconds (relative);\n * - `expires` as a `Date` (possibly a cross-realm instance, since config files\n * run in a `node:vm` sandbox) or an ISO string becomes an ISO **string**\n * (absolute). Strings survive `JSON.stringify`, unlike a `Date`.\n *\n * The result is therefore: a `number` = seconds from creation, a `string` =\n * absolute ISO date, or `undefined` for a session cookie.\n */\nconst normalizeCookieExpiry = (\n expires: CookiesAttributes['expires'],\n maxAge: CookiesAttributes['maxAge']\n): number | string | undefined => {\n if (typeof maxAge === 'number') return maxAge;\n if (expires === undefined) return undefined;\n if (\n expires instanceof Date ||\n Object.prototype.toString.call(expires) === '[object Date]'\n ) {\n return (expires as Date).toISOString();\n }\n if (typeof expires === 'string') return expires;\n return expires * SECONDS_PER_DAY;\n};\n\nconst createCookieEntry = (\n options?: Partial<CookiesAttributes>\n): CookieEntry => {\n const {\n name,\n path = '/',\n expires,\n maxAge,\n domain,\n secure,\n sameSite,\n httpOnly,\n } = options ?? {};\n return {\n name: name ?? COOKIE_NAME,\n attributes: {\n path,\n expires: normalizeCookieExpiry(expires, maxAge),\n domain,\n secure,\n sameSite,\n httpOnly,\n },\n };\n};\n\nconst createWebStorageEntry = (\n options?: Partial<StorageAttributes>\n): WebStorageEntry => ({\n name: options?.name ?? LOCALE_STORAGE_NAME,\n});\n\nconst createHeaderEntry = (\n options?: Partial<StorageAttributes>\n): HeaderEntry => ({\n name: options?.name ?? HEADER_NAME,\n});\n\nconst isCookieEntry = (entry: unknown): boolean => {\n if (typeof entry !== 'object' || entry === null) return false;\n const e = entry as Record<string, unknown>;\n return (\n e['type'] === 'cookie' ||\n 'sameSite' in e ||\n 'httpOnly' in e ||\n 'secure' in e\n );\n};\n\nconst isStorageType = (\n value: string\n): value is 'cookie' | 'localStorage' | 'sessionStorage' | 'header' =>\n value === 'cookie' ||\n value === 'localStorage' ||\n value === 'sessionStorage' ||\n value === 'header';\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\nconst processStorageEntry = (\n entry: StorageEntry\n): Partial<ProcessedStorageAttributes> => {\n if (typeof entry === 'string') {\n if (!isStorageType(entry)) {\n return { cookies: [], localStorage: [], sessionStorage: [], headers: [] };\n }\n if (entry === 'cookie') return { cookies: [createCookieEntry()] };\n if (entry === 'localStorage')\n return { localStorage: [createWebStorageEntry()] };\n if (entry === 'sessionStorage')\n return { sessionStorage: [createWebStorageEntry()] };\n if (entry === 'header') return { headers: [createHeaderEntry()] };\n }\n\n if (typeof entry === 'object' && entry !== null) {\n const typedEntry = entry as CookiesAttributes | StorageAttributes;\n\n if (isCookieEntry(typedEntry)) {\n return { cookies: [createCookieEntry(typedEntry as CookiesAttributes)] };\n }\n if ('type' in typedEntry && typedEntry.type === 'localStorage') {\n return {\n localStorage: [createWebStorageEntry(typedEntry as StorageAttributes)],\n };\n }\n if ('type' in typedEntry && typedEntry.type === 'sessionStorage') {\n return {\n sessionStorage: [\n createWebStorageEntry(typedEntry as StorageAttributes),\n ],\n };\n }\n if ('type' in typedEntry && typedEntry.type === 'header') {\n return { headers: [createHeaderEntry(typedEntry as StorageAttributes)] };\n }\n // Default to localStorage for ambiguous objects\n return {\n localStorage: [\n createWebStorageEntry(typedEntry as Omit<StorageAttributes, 'type'>),\n ],\n };\n }\n\n return { cookies: [], localStorage: [], sessionStorage: [], headers: [] };\n};\n\nconst mergeStorageAttributes = (\n accumulated: ProcessedStorageAttributes,\n partial: Partial<ProcessedStorageAttributes>\n): ProcessedStorageAttributes => ({\n cookies: [...(accumulated.cookies ?? []), ...(partial.cookies ?? [])],\n localStorage: [\n ...(accumulated.localStorage ?? []),\n ...(partial.localStorage ?? []),\n ],\n sessionStorage: [\n ...(accumulated.sessionStorage ?? []),\n ...(partial.sessionStorage ?? []),\n ],\n headers: [...(accumulated.headers ?? []), ...(partial.headers ?? [])],\n});\n\n/**\n * Extracts and normalizes storage configuration into separate arrays for each storage type.\n * Called at config-build time so the result is pre-computed and stored in the config.\n *\n * @param options - The storage configuration from IntlayerConfig\n * @returns An object containing arrays for cookies, localStorage, sessionStorage and headers\n */\nexport const getStorageAttributes = (\n options: RoutingStorageInput\n): ProcessedStorageAttributes => {\n const emptyResult: ProcessedStorageAttributes = {\n cookies: [],\n localStorage: [],\n sessionStorage: [],\n headers: [],\n };\n\n if (options === false || options === undefined) return {};\n\n const result = Array.isArray(options)\n ? options.reduce<ProcessedStorageAttributes>((acc, entry) => {\n const partial = processStorageEntry(entry);\n return mergeStorageAttributes(acc, partial);\n }, emptyResult)\n : mergeStorageAttributes(emptyResult, processStorageEntry(options));\n\n // Remove empty arrays\n const cleanedResult: ProcessedStorageAttributes = {};\n\n if (result.cookies && result.cookies.length > 0) {\n cleanedResult.cookies = result.cookies;\n }\n\n if (result.localStorage && result.localStorage.length > 0) {\n cleanedResult.localStorage = result.localStorage;\n }\n\n if (result.sessionStorage && result.sessionStorage.length > 0) {\n cleanedResult.sessionStorage = result.sessionStorage;\n }\n\n if (result.headers && result.headers.length > 0) {\n cleanedResult.headers = result.headers;\n }\n\n return cleanedResult;\n};\n"],"mappings":";;;;AAuBA,MAAM,kBAAkB;;;;;;;;;;;;;;;;AAqCxB,MAAM,yBACJ,SACA,WACgC;CAChC,IAAI,OAAO,WAAW,UAAU,OAAO;CACvC,IAAI,YAAY,QAAW,OAAO;CAClC,IACE,mBAAmB,QACnB,OAAO,UAAU,SAAS,KAAK,OAAO,MAAM,iBAE5C,OAAQ,QAAiB,YAAY;CAEvC,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,OAAO,UAAU;AACnB;AAEA,MAAM,qBACJ,YACgB;CAChB,MAAM,EACJ,MACA,OAAO,KACP,SACA,QACA,QACA,QACA,UACA,aACE,WAAW,CAAC;CAChB,OAAO;EACL,MAAM;EACN,YAAY;GACV;GACA,SAAS,sBAAsB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Ac,UAAU,OAAO;CAGjC,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/config",
3
- "version": "9.3.0",
3
+ "version": "9.3.1",
4
4
  "private": false,
5
5
  "description": "Retrieve Intlayer configurations and manage environment variables for both server-side and client-side environments.",
6
6
  "keywords": [
@@ -164,7 +164,7 @@
164
164
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
165
165
  },
166
166
  "dependencies": {
167
- "@intlayer/types": "9.3.0",
167
+ "@intlayer/types": "9.3.1",
168
168
  "defu": "6.1.7",
169
169
  "dotenv": "17.4.2",
170
170
  "esbuild": "0.28.2",