@intlayer/config 8.3.1 → 8.3.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"buildConfigurationFields.cjs","names":["LOCALES","REQUIRED_LOCALES","DEFAULT_LOCALE","STORAGE","getProjectRequire","normalizePath","FILE_EXTENSIONS","CONTENT_DIR","CODE_DIR","EXCLUDED_PATHS","PREFIX","TRAVERSE_PATTERN","OUTPUT_FORMAT","packageJson"],"sources":["../../../src/configFile/buildConfigurationFields.ts"],"sourcesContent":["import { statSync } from 'node:fs';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport type {\n AiConfig,\n BuildConfig,\n CompilerConfig,\n ContentConfig,\n CustomIntlayerConfig,\n DictionaryConfig,\n EditorConfig,\n InternationalizationConfig,\n IntlayerConfig,\n LogConfig,\n LogFunctions,\n RoutingConfig,\n SystemConfig,\n} from '@intlayer/types/config';\nimport packageJson from '@intlayer/types/package.json' with { type: 'json' };\nimport {\n BUILD_MODE,\n CACHE,\n OUTPUT_FORMAT,\n TRAVERSE_PATTERN,\n TYPE_CHECKING,\n} from '../defaultValues/build';\nimport {\n COMPILER_DICTIONARY_KEY_PREFIX,\n COMPILER_ENABLED,\n COMPILER_NO_METADATA,\n COMPILER_SAVE_COMPONENTS,\n} from '../defaultValues/compiler';\nimport {\n CODE_DIR,\n CONTENT_DIR,\n EXCLUDED_PATHS,\n FILE_EXTENSIONS,\n WATCH,\n} from '../defaultValues/content';\nimport {\n CONTENT_AUTO_TRANSFORMATION,\n FILL,\n IMPORT_MODE,\n LOCATION,\n} from '../defaultValues/dictionary';\nimport {\n APPLICATION_URL,\n BACKEND_URL,\n CMS_URL,\n DICTIONARY_PRIORITY_STRATEGY,\n EDITOR_URL,\n IS_ENABLED,\n LIVE_SYNC,\n LIVE_SYNC_PORT,\n PORT,\n} from '../defaultValues/editor';\nimport {\n DEFAULT_LOCALE,\n LOCALES,\n REQUIRED_LOCALES,\n STRICT_MODE,\n} from '../defaultValues/internationalization';\nimport { MODE, PREFIX } from '../defaultValues/log';\nimport { BASE_PATH, ROUTING_MODE, STORAGE } from '../defaultValues/routing';\nimport {\n CACHE_DIR,\n CONFIG_DIR,\n DICTIONARIES_DIR,\n DYNAMIC_DICTIONARIES_DIR,\n FETCH_DICTIONARIES_DIR,\n MAIN_DIR,\n MODULE_AUGMENTATION_DIR,\n REMOTE_DICTIONARIES_DIR,\n TEMP_DIR,\n TYPES_DIR,\n UNMERGED_DICTIONARIES_DIR,\n} from '../defaultValues/system';\nimport { getProjectRequire } from '../utils';\nimport { normalizePath } from '../utils/normalizePath';\n\nlet storedConfiguration: IntlayerConfig;\n\nconst buildInternationalizationFields = (\n customConfiguration?: Partial<InternationalizationConfig>\n): InternationalizationConfig => ({\n /**\n * Locales available in the application\n *\n * Default: ['en']\n *\n */\n locales: customConfiguration?.locales ?? LOCALES,\n\n /**\n * Locales required by TypeScript to ensure strong implementations of internationalized content using typescript.\n *\n * Default: []\n *\n * If empty, all locales are required in `strict` mode.\n *\n * Ensure required locales are also defined in the `locales` field.\n */\n requiredLocales:\n customConfiguration?.requiredLocales ??\n customConfiguration?.locales ??\n REQUIRED_LOCALES,\n\n /**\n * Ensure strong implementations of internationalized content using typescript.\n * - If set to \"strict\", the translation `t` function will require each declared locales to be defined. If one locale is missing, or if a locale is not declared in your config, it will throw an error.\n * - If set to \"inclusive\", the translation `t` function will require each declared locales to be defined. If one locale is missing, it will throw a warning. But will accept if a locale is not declared in your config, but exist.\n * - If set to \"loose\", the translation `t` function will accept any existing locale.\n *\n * Default: \"inclusive\"\n */\n strictMode: customConfiguration?.strictMode ?? STRICT_MODE,\n\n /**\n * Default locale of the application for fallback\n *\n * Default: 'en'\n */\n defaultLocale: customConfiguration?.defaultLocale ?? DEFAULT_LOCALE,\n});\n\nconst buildRoutingFields = (\n customConfiguration?: Partial<RoutingConfig>\n): RoutingConfig => ({\n /**\n * URL routing mode for locale handling\n *\n * Controls how locales are represented in application URLs:\n * - 'prefix-no-default': Prefix all locales except the default locale (default)\n * - en → /dashboard\n * - fr → /fr/dashboard\n *\n * - 'prefix-all': Prefix all locales including the default locale\n * - en → /en/dashboard\n * - fr → /fr/dashboard\n *\n * - 'search-params': Use search parameters for locale handling\n * - en → /dashboard?locale=en\n * - fr → /fr/dashboard?locale=fr\n *\n * - 'no-prefix': No locale prefixing in URLs\n * - en → /dashboard\n * - fr → /dashboard\n *\n * Default: 'prefix-no-default'\n */\n mode: customConfiguration?.mode ?? ROUTING_MODE,\n\n /**\n * Configuration for storing the locale in the client (localStorage or sessionStorage)\n *\n * If false, the locale will not be stored by the middleware.\n * If true, the locale storage will consider all default values. (cookie and header)\n *\n * Default: ['cookie', 'header']\n *\n */\n storage: customConfiguration?.storage ?? STORAGE,\n\n /**\n * Base path of the application URL\n *\n * Default: ''\n *\n * Example:\n * - If the application is hosted at https://example.com/my-app\n * - The base path is '/my-app'\n * - The URL will be https://example.com/my-app/en\n * - If the base path is not set, the URL will be https://example.com/en\n */\n basePath: customConfiguration?.basePath ?? BASE_PATH,\n\n /**\n * Custom URL rewriting rules that override the default routing mode for specific paths.\n * Allows you to define locale-specific paths that differ from the standard routing behavior.\n * Supports dynamic route parameters using `[param]` syntax.\n *\n * Default: undefined\n *\n * Example:\n * ```typescript\n * rewrite: {\n * \"/about\": {\n * en: \"/about\",\n * fr: \"/a-propos\",\n * },\n * \"/product/[slug]\": {\n * en: \"/product/[slug]\",\n * fr: \"/produit/[slug]\",\n * },\n * }\n * ```\n *\n * Note:\n * - The rewrite rules take precedence over the default `mode` behavior.\n * - If a path matches a rewrite rule, the localized path from the rewrite configuration will be used.\n * - Dynamic route parameters are supported using bracket notation (e.g., `[slug]`, `[id]`).\n * - Works with both Next.js and Vite applications.\n */\n rewrite: customConfiguration?.rewrite,\n});\n\nconst buildSystemFields = (\n baseDir?: string,\n customConfiguration?: Partial<SystemConfig>\n): SystemConfig => {\n const projectBaseDir = baseDir ?? process.cwd();\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n const requireFunction = getProjectRequire(projectBaseDir);\n\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [projectBaseDir],\n });\n } catch {\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(projectBaseDir, pathInput);\n }\n\n try {\n const stats = statSync(absolutePath);\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n return absolutePath;\n };\n\n const dictionariesDir = optionalJoinBaseDir(\n customConfiguration?.dictionariesDir ?? DICTIONARIES_DIR\n );\n\n return {\n baseDir: projectBaseDir,\n moduleAugmentationDir: optionalJoinBaseDir(\n customConfiguration?.moduleAugmentationDir ?? MODULE_AUGMENTATION_DIR\n ),\n unmergedDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.unmergedDictionariesDir ?? UNMERGED_DICTIONARIES_DIR\n ),\n remoteDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.remoteDictionariesDir ?? REMOTE_DICTIONARIES_DIR\n ),\n dictionariesDir,\n dynamicDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.dynamicDictionariesDir ?? DYNAMIC_DICTIONARIES_DIR\n ),\n fetchDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.fetchDictionariesDir ?? FETCH_DICTIONARIES_DIR\n ),\n typesDir: optionalJoinBaseDir(customConfiguration?.typesDir ?? TYPES_DIR),\n mainDir: optionalJoinBaseDir(customConfiguration?.mainDir ?? MAIN_DIR),\n configDir: optionalJoinBaseDir(\n customConfiguration?.configDir ?? CONFIG_DIR\n ),\n cacheDir: optionalJoinBaseDir(customConfiguration?.cacheDir ?? CACHE_DIR),\n tempDir: optionalJoinBaseDir(customConfiguration?.tempDir ?? TEMP_DIR),\n outputFilesPatternWithPath: `${normalizePath(dictionariesDir)}/**/*.json`,\n };\n};\n\nconst buildContentFields = (\n systemConfig: SystemConfig,\n customConfiguration?: Partial<ContentConfig>\n): ContentConfig => {\n const fileExtensions = customConfiguration?.fileExtensions ?? FILE_EXTENSIONS;\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n // Try resolving as a Node module first\n const requireFunction = getProjectRequire(systemConfig.baseDir);\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch {\n try {\n // Fall back to native require.resolve if the custom require fails\n absolutePath = require.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch {\n // If all resolution fails, fall back to standard path joining\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(systemConfig.baseDir, pathInput);\n }\n }\n\n try {\n // Smart Detection: File vs Directory\n const stats = statSync(absolutePath);\n\n // If it resolved to a file (like package.json \"main\" or index.js),\n // we want the FOLDER containing that file.\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n // Safety Fallback:\n // If statSync fails but it looks like a file (has an extension), strip it.\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n // Return the calculated path (usually a directory)\n return absolutePath;\n };\n\n const contentDir = (customConfiguration?.contentDir ?? CONTENT_DIR).map(\n optionalJoinBaseDir\n );\n\n const codeDirInput = customConfiguration?.codeDir;\n\n const codeDir = (codeDirInput ?? CODE_DIR).map(optionalJoinBaseDir);\n\n return {\n fileExtensions,\n contentDir,\n codeDir,\n excludedPath: customConfiguration?.excludedPath ?? EXCLUDED_PATHS,\n watch: customConfiguration?.watch ?? WATCH,\n formatCommand: customConfiguration?.formatCommand,\n watchedFilesPattern: fileExtensions.map((ext) => `/**/*${ext}`),\n watchedFilesPatternWithPath: fileExtensions.flatMap((ext) =>\n contentDir.map((dir) => `${normalizePath(dir)}/**/*${ext}`)\n ),\n };\n};\n\nconst buildEditorFields = (\n customConfiguration?: Partial<EditorConfig>\n): EditorConfig => ({\n /**\n * URL of the application. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n applicationURL: customConfiguration?.applicationURL || APPLICATION_URL,\n\n /**\n * URL of the editor server. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n editorURL: customConfiguration?.editorURL || EDITOR_URL,\n\n /**\n * URL of the CMS server. Used to restrict the origin of the editor for security reasons.\n */\n cmsURL: customConfiguration?.cmsURL || CMS_URL,\n\n /**\n * URL of the editor server\n *\n * Default: 'https://back.intlayer.org'\n */\n backendURL: customConfiguration?.backendURL || BACKEND_URL,\n\n /** Port of the editor server\n *\n * Default: 8000\n */\n port: customConfiguration?.port ?? PORT,\n\n /**\n * Indicates if the application interact with the visual editor\n *\n * Default: true;\n *\n * If true, the editor will be able to interact with the application.\n * If false, the editor will not be able to interact with the application.\n * In any case, the editor can only be enabled by the visual editor.\n * Disabling the editor for specific environments is a way to enforce the security.\n *\n * Usage:\n * ```js\n * {\n * // Other configurations\n * editor: {\n * enabled: process.env.NODE_ENV !== 'production',\n * }\n * };\n * ```\n */\n enabled: customConfiguration?.enabled ?? IS_ENABLED,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientId: customConfiguration?.clientId ?? undefined,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientSecret: customConfiguration?.clientSecret ?? undefined,\n\n /**\n * Strategy for prioritizing dictionaries. If a dictionary is both present online and locally, the content will be merge.\n * However, is a field is defined in both dictionary, this setting determines which fields takes the priority over the other.\n *\n * Default: 'local_first'\n *\n * The strategy for prioritizing dictionaries. It can be either 'local_first' or 'distant_first'.\n * - 'local_first': The first dictionary found in the locale is used.\n * - 'distant_first': The first dictionary found in the distant locales is used.\n */\n dictionaryPriorityStrategy:\n customConfiguration?.dictionaryPriorityStrategy ??\n DICTIONARY_PRIORITY_STRATEGY,\n\n /**\n * Indicates if the application should hot reload the locale configurations when a change is detected.\n * For example, when a new dictionary is added or updated, the application will update the content tu display in the page.\n *\n * The hot reload is only available for clients of the `enterprise` plan.\n *\n * Default: false\n */\n liveSync: customConfiguration?.liveSync ?? LIVE_SYNC,\n\n /**\n * Port of the live sync server\n *\n * Default: 4000\n */\n liveSyncPort: customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT,\n\n /**\n * URL of the live sync server in case of remote live sync server\n *\n * Default: `http://localhost:${LIVE_SYNC_PORT}`\n */\n liveSyncURL:\n customConfiguration?.liveSyncURL ??\n `http://localhost:${customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT}`,\n});\n\nconst buildLogFields = (\n customConfiguration?: Partial<LogConfig>,\n logFunctions?: LogFunctions\n): LogConfig => ({\n /**\n * Indicates if the logger is enabled\n *\n * Default: 'prefix-no-default'\n *\n * If 'default', the logger is enabled and can be used.\n * If 'verbose', the logger will be enabled and can be used, but will log more information.\n * If 'disabled', the logger is disabled and cannot be used.\n */\n mode: customConfiguration?.mode ?? MODE,\n\n /**\n * Prefix of the logger\n *\n * Default: '[intlayer]'\n *\n * The prefix of the logger.\n */\n prefix: customConfiguration?.prefix ?? PREFIX,\n\n /**\n * Functions to log\n */\n error: logFunctions?.error,\n log: logFunctions?.log,\n info: logFunctions?.info,\n warn: logFunctions?.warn,\n});\n\nconst buildAiFields = (customConfiguration?: Partial<AiConfig>): AiConfig => ({\n /**\n * AI configuration\n */\n provider: customConfiguration?.provider,\n\n /**\n * API key\n */\n apiKey: customConfiguration?.apiKey,\n\n /**\n * API model\n */\n model: customConfiguration?.model,\n\n /**\n * Temperature\n */\n temperature: customConfiguration?.temperature,\n\n /**\n * Application context\n *\n * Default: undefined\n *\n * The application context.\n *\n * Example: `'My application context'`\n *\n * Note: Can be used to provide additional context about the application to the AI model. You can add more rules (e.g. \"You should not transform urls\").\n */\n applicationContext: customConfiguration?.applicationContext,\n\n /**\n * Base URL for the AI API\n *\n * Default: undefined\n *\n * The base URL for the AI API.\n *\n * Example: `'http://localhost:5000'`\n *\n * Note: Can be used to point to a local, or custom AI API endpoint.\n */\n baseURL: customConfiguration?.baseURL,\n\n /**\n * Data serialization\n *\n * Options:\n * - \"json\": The industry standard. Highly reliable and structured, but consumes more tokens.\n * - \"toon\": An optimized format designed to reduce token consumption (cost-effective). However, it may slightly increase the risk of output inconsistency compared to standard JSON\n *\n * Default: \"json\"\n */\n dataSerialization: customConfiguration?.dataSerialization,\n});\n\nconst buildBuildFields = (\n customConfiguration?: Partial<BuildConfig>\n): BuildConfig => ({\n /**\n * Indicates the mode of the build\n *\n * Default: 'auto'\n *\n * If 'auto', the build will be enabled automatically when the application is built.\n * If 'manual', the build will be set only when the build command is executed.\n *\n * Can be used to disable dictionaries build, for instance when execution on Node.js environment should be avoided.\n */\n mode: customConfiguration?.mode ?? BUILD_MODE,\n\n /**\n * Indicates if the build should be optimized\n *\n * Default: process.env.NODE_ENV === 'production'\n *\n * If true, the build will be optimized.\n * If false, the build will not be optimized.\n *\n * Intlayer will replace all calls of dictionaries to optimize chunking. That way the final bundle will import only the dictionaries that are used.\n * All imports will stay as static import to avoid async processing when loading the dictionaries.\n *\n * Note:\n * - Intlayer will replace all call of `useIntlayer` with the defined mode by the `importMode` option.\n * - Intlayer will replace all call of `getIntlayer` with `getDictionary`.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - In most cases, \"dynamic\" will be used for React applications, \"async\" for Vue.js applications.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n */\n optimize: customConfiguration?.optimize,\n\n /**\n * Indicates the mode of import to use for the dictionaries.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionary`.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * Live mode will use the live sync API to fetch the dictionaries. If the API call fails, the dictionaries will be imported dynamically as \"dynamic\" mode.\n *\n * Default: \"static\"\n *\n * By default, when a dictionary is loaded, it imports content for all locales as it's imported statically.\n *\n * Note:\n * - Dynamic imports rely on Suspense and may slightly impact rendering performance.\n * - If disabled all locales will be loaded at once, even if they are not used.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n * - This option will be ignored if `optimize` is disabled.\n * - This option will not impact the `getIntlayer`, `getDictionary`, `useDictionary`, `useDictionaryAsync` and `useDictionaryDynamic` functions. You can still use them to refine you code on manual optimization.\n * - The \"live\" allows to sync the dictionaries to the live sync server.\n *\n * @deprecated Use `dictionary.importMode` instead.\n */\n importMode: customConfiguration?.importMode,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * Allows to avoid to traverse the code that is not relevant to the optimization.\n * Improve build performance.\n *\n * Default: ['**\\/*.{js,ts,mjs,cjs,jsx,tsx}', '!**\\/node_modules/**']\n *\n * Example: `['src/**\\/*.{ts,tsx}', '../ui-library/**\\/*.{ts,tsx}']`\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - Use glob pattern.\n */\n traversePattern: customConfiguration?.traversePattern ?? TRAVERSE_PATTERN,\n\n /**\n * Output format of the dictionaries\n *\n * Can be set on large projects to improve build performance.\n *\n * Default: ['cjs', 'esm']\n *\n * The output format of the dictionaries. It can be either 'cjs' or 'esm'.\n * - 'cjs': The dictionaries are outputted as CommonJS modules.\n * - 'esm': The dictionaries are outputted as ES modules.\n */\n outputFormat: customConfiguration?.outputFormat ?? OUTPUT_FORMAT,\n\n /**\n * Cache\n */\n cache: customConfiguration?.cache ?? CACHE,\n\n /**\n * Require function\n */\n require: customConfiguration?.require,\n\n /**\n * Indicates if the build should check TypeScript types\n *\n * Default: false\n *\n * If true, the build will check TypeScript types and log errors.\n * Note: This can slow down the build.\n */\n checkTypes: customConfiguration?.checkTypes ?? TYPE_CHECKING,\n});\n\nconst buildCompilerFields = (\n customConfiguration?: Partial<CompilerConfig>\n): CompilerConfig => ({\n /**\n * Indicates if the compiler should be enabled\n */\n enabled: customConfiguration?.enabled ?? COMPILER_ENABLED,\n\n /**\n * Prefix for the extracted dictionary keys\n */\n dictionaryKeyPrefix:\n customConfiguration?.dictionaryKeyPrefix ?? COMPILER_DICTIONARY_KEY_PREFIX,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * @deprecated use build.traversePattern instead\n */\n transformPattern: customConfiguration?.transformPattern,\n\n /**\n * Pattern to exclude from the optimization.\n *\n * @deprecated use build.traversePattern instead\n */\n excludePattern: customConfiguration?.excludePattern,\n\n /**\n * Defines the output files path. Replaces `outputDir`.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - Including the `{{locale}}` variable in the path will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * output: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // output: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * output: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // output: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n output: customConfiguration?.output,\n\n /**\n * Indicates if the metadata should be saved in the file.\n *\n * If true, the compiler will not save the metadata of the dictionaries.\n *\n * If true:\n *\n * ```json\n * {\n * \"key\": \"value\"\n * }\n * ```\n *\n * If false:\n *\n * ```json\n * {\n * \"key\": \"value\",\n * \"content\": {\n * \"key\": \"value\"\n * }\n * }\n * ```\n *\n * Default: false\n *\n * Note: Useful if used with loadJSON plugin\n */\n noMetadata: customConfiguration?.noMetadata ?? COMPILER_NO_METADATA,\n\n /**\n * Indicates if the components should be saved after being transformed.\n */\n saveComponents:\n customConfiguration?.saveComponents ?? COMPILER_SAVE_COMPONENTS,\n});\n\nconst buildDictionaryFields = (\n customConfiguration?: Partial<DictionaryConfig>\n): DictionaryConfig => {\n const contentAutoTransformation =\n customConfiguration?.contentAutoTransformation ??\n CONTENT_AUTO_TRANSFORMATION;\n\n return {\n /**\n * Indicate how the dictionary should be filled using AI.\n *\n * Default: `true`\n *\n * - If `true`, will consider the `compiler.output` field.\n * - If `false`, will skip the fill process.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - If includes `{{locale}}` variable in the path, will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * fill: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // fill: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * fill: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // fill: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create custom output based on the locale\n * fill: {\n * en: ({ key }) => `/locales/en/${key}.content.json`,\n * fr: '/locales/fr/{{key}}.content.json',\n * es: false,\n * de: true,\n * },\n * }\n * ```\n *\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n fill: customConfiguration?.fill ?? FILL,\n\n /**\n * Indicates if the content of the dictionary should be automatically transformed.\n *\n * Default: false\n */\n contentAutoTransformation:\n typeof contentAutoTransformation === 'object'\n ? {\n markdown: contentAutoTransformation.markdown ?? false,\n html: contentAutoTransformation.html ?? false,\n insertion: contentAutoTransformation.insertion ?? false,\n }\n : contentAutoTransformation,\n\n /**\n * The location of the dictionary.\n *\n * Default: 'local'\n */\n location: customConfiguration?.location ?? LOCATION,\n\n /**\n * Transform the dictionary in a per-locale dictionary.\n * Each field declared in a per-locale dictionary will be transformed in a translation node.\n * If missing, the dictionary will be treated as a multilingual dictionary.\n */\n locale: customConfiguration?.locale,\n\n /**\n * The title of the dictionary.\n */\n title: customConfiguration?.title,\n\n /**\n * The description of the dictionary.\n */\n description: customConfiguration?.description,\n\n /**\n * Tags to categorize the dictionaries.\n */\n tags: customConfiguration?.tags,\n\n /**\n * The priority of the dictionary.\n */\n priority: customConfiguration?.priority,\n\n /**\n * Indicates the mode of import to use for the dictionary.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n *\n * Default: 'static'\n */\n importMode: customConfiguration?.importMode ?? IMPORT_MODE,\n };\n};\n\n/**\n * Build the configuration fields by merging the default values with the custom configuration\n */\nexport const buildConfigurationFields = (\n customConfiguration?: CustomIntlayerConfig,\n baseDir?: string,\n logFunctions?: LogFunctions\n): IntlayerConfig => {\n const internationalizationConfig = buildInternationalizationFields(\n customConfiguration?.internationalization\n );\n\n const routingConfig = buildRoutingFields(customConfiguration?.routing);\n\n const systemConfig = buildSystemFields(baseDir, customConfiguration?.system);\n\n const contentConfig = buildContentFields(\n systemConfig,\n customConfiguration?.content\n );\n\n const editorConfig = buildEditorFields(customConfiguration?.editor);\n\n const logConfig = buildLogFields(customConfiguration?.log, logFunctions);\n\n const aiConfig = buildAiFields(customConfiguration?.ai);\n\n const buildConfig = buildBuildFields(customConfiguration?.build);\n\n const compilerConfig = buildCompilerFields(customConfiguration?.compiler);\n\n const dictionaryConfig = buildDictionaryFields(\n customConfiguration?.dictionary\n );\n\n storedConfiguration = {\n internationalization: internationalizationConfig,\n routing: routingConfig,\n content: contentConfig,\n system: systemConfig,\n editor: editorConfig,\n log: logConfig,\n ai: aiConfig,\n build: buildConfig,\n compiler: compilerConfig,\n dictionary: dictionaryConfig,\n plugins: customConfiguration?.plugins,\n schemas: customConfiguration?.schemas,\n metadata: {\n name: 'Intlayer',\n version: packageJson.version,\n doc: `https://intlayer.org/docs`,\n },\n } as IntlayerConfig;\n\n return storedConfiguration;\n};\n"],"mappings":"+rBA+EA,IAAI,EAEJ,MAAM,EACJ,IACgC,CAOhC,QAAS,GAAqB,SAAWA,EAAAA,QAWzC,gBACE,GAAqB,iBACrB,GAAqB,SACrBC,EAAAA,iBAUF,WAAY,GAAqB,YAAA,YAOjC,cAAe,GAAqB,eAAiBC,EAAAA,eACtD,EAEK,EACJ,IACmB,CAuBnB,KAAM,GAAqB,MAAA,oBAW3B,QAAS,GAAqB,SAAWC,EAAAA,QAazC,SAAU,GAAqB,UAAA,GA6B/B,QAAS,GAAqB,QAC/B,EAEK,GACJ,EACA,IACiB,CACjB,IAAM,EAAiB,GAAW,QAAQ,KAAK,CAEzC,EAAuB,GAAsB,CACjD,IAAI,EAEJ,GAAI,CAGF,EAFwBC,EAAAA,kBAAkB,EAAe,CAE1B,QAAQ,EAAW,CAChD,M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B,GAAqB,MAAM,CAiB9D,SAfqB,EAAoB,GAAqB,SAAS,CAgBvE,WAduB,EACvB,GAAqB,WACtB,CAaC,QAAS,GAAqB,QAC9B,QAAS,GAAqB,QAC9B,SAAU,CACR,KAAM,WACN,QAASC,EAAAA,QAAY,QACrB,IAAK,4BACN,CACF,CAEM"}
1
+ {"version":3,"file":"buildConfigurationFields.cjs","names":["LOCALES","REQUIRED_LOCALES","DEFAULT_LOCALE","STORAGE","getProjectRequire","normalizePath","FILE_EXTENSIONS","CONTENT_DIR","CODE_DIR","EXCLUDED_PATHS","PREFIX","TRAVERSE_PATTERN","OUTPUT_FORMAT","packageJson"],"sources":["../../../src/configFile/buildConfigurationFields.ts"],"sourcesContent":["import { statSync } from 'node:fs';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport type {\n AiConfig,\n BuildConfig,\n CompilerConfig,\n ContentConfig,\n CustomIntlayerConfig,\n DictionaryConfig,\n EditorConfig,\n InternationalizationConfig,\n IntlayerConfig,\n LogConfig,\n LogFunctions,\n RoutingConfig,\n SystemConfig,\n} from '@intlayer/types/config';\nimport packageJson from '@intlayer/types/package.json' with { type: 'json' };\nimport {\n BUILD_MODE,\n CACHE,\n OUTPUT_FORMAT,\n TRAVERSE_PATTERN,\n TYPE_CHECKING,\n} from '../defaultValues/build';\nimport {\n COMPILER_DICTIONARY_KEY_PREFIX,\n COMPILER_ENABLED,\n COMPILER_NO_METADATA,\n COMPILER_SAVE_COMPONENTS,\n} from '../defaultValues/compiler';\nimport {\n CODE_DIR,\n CONTENT_DIR,\n EXCLUDED_PATHS,\n FILE_EXTENSIONS,\n WATCH,\n} from '../defaultValues/content';\nimport {\n CONTENT_AUTO_TRANSFORMATION,\n FILL,\n IMPORT_MODE,\n LOCATION,\n} from '../defaultValues/dictionary';\nimport {\n APPLICATION_URL,\n BACKEND_URL,\n CMS_URL,\n DICTIONARY_PRIORITY_STRATEGY,\n EDITOR_URL,\n IS_ENABLED,\n LIVE_SYNC,\n LIVE_SYNC_PORT,\n PORT,\n} from '../defaultValues/editor';\nimport {\n DEFAULT_LOCALE,\n LOCALES,\n REQUIRED_LOCALES,\n STRICT_MODE,\n} from '../defaultValues/internationalization';\nimport { MODE, PREFIX } from '../defaultValues/log';\nimport { BASE_PATH, ROUTING_MODE, STORAGE } from '../defaultValues/routing';\nimport {\n CACHE_DIR,\n CONFIG_DIR,\n DICTIONARIES_DIR,\n DYNAMIC_DICTIONARIES_DIR,\n FETCH_DICTIONARIES_DIR,\n MAIN_DIR,\n MODULE_AUGMENTATION_DIR,\n REMOTE_DICTIONARIES_DIR,\n TEMP_DIR,\n TYPES_DIR,\n UNMERGED_DICTIONARIES_DIR,\n} from '../defaultValues/system';\nimport { getProjectRequire } from '../utils';\nimport { normalizePath } from '../utils/normalizePath';\n\nlet storedConfiguration: IntlayerConfig;\n\nconst buildInternationalizationFields = (\n customConfiguration?: Partial<InternationalizationConfig>\n): InternationalizationConfig => ({\n /**\n * Locales available in the application\n *\n * Default: ['en']\n *\n */\n locales: customConfiguration?.locales ?? LOCALES,\n\n /**\n * Locales required by TypeScript to ensure strong implementations of internationalized content using typescript.\n *\n * Default: []\n *\n * If empty, all locales are required in `strict` mode.\n *\n * Ensure required locales are also defined in the `locales` field.\n */\n requiredLocales:\n customConfiguration?.requiredLocales ??\n customConfiguration?.locales ??\n REQUIRED_LOCALES,\n\n /**\n * Ensure strong implementations of internationalized content using typescript.\n * - If set to \"strict\", the translation `t` function will require each declared locales to be defined. If one locale is missing, or if a locale is not declared in your config, it will throw an error.\n * - If set to \"inclusive\", the translation `t` function will require each declared locales to be defined. If one locale is missing, it will throw a warning. But will accept if a locale is not declared in your config, but exist.\n * - If set to \"loose\", the translation `t` function will accept any existing locale.\n *\n * Default: \"inclusive\"\n */\n strictMode: customConfiguration?.strictMode ?? STRICT_MODE,\n\n /**\n * Default locale of the application for fallback\n *\n * Default: 'en'\n */\n defaultLocale: customConfiguration?.defaultLocale ?? DEFAULT_LOCALE,\n});\n\nconst buildRoutingFields = (\n customConfiguration?: Partial<RoutingConfig>\n): RoutingConfig => ({\n /**\n * URL routing mode for locale handling\n *\n * Controls how locales are represented in application URLs:\n * - 'prefix-no-default': Prefix all locales except the default locale (default)\n * - en → /dashboard\n * - fr → /fr/dashboard\n *\n * - 'prefix-all': Prefix all locales including the default locale\n * - en → /en/dashboard\n * - fr → /fr/dashboard\n *\n * - 'search-params': Use search parameters for locale handling\n * - en → /dashboard?locale=en\n * - fr → /fr/dashboard?locale=fr\n *\n * - 'no-prefix': No locale prefixing in URLs\n * - en → /dashboard\n * - fr → /dashboard\n *\n * Default: 'prefix-no-default'\n */\n mode: customConfiguration?.mode ?? ROUTING_MODE,\n\n /**\n * Configuration for storing the locale in the client (localStorage or sessionStorage)\n *\n * If false, the locale will not be stored by the middleware.\n * If true, the locale storage will consider all default values. (cookie and header)\n *\n * Default: ['cookie', 'header']\n *\n */\n storage: customConfiguration?.storage ?? STORAGE,\n\n /**\n * Base path of the application URL\n *\n * Default: ''\n *\n * Example:\n * - If the application is hosted at https://example.com/my-app\n * - The base path is '/my-app'\n * - The URL will be https://example.com/my-app/en\n * - If the base path is not set, the URL will be https://example.com/en\n */\n basePath: customConfiguration?.basePath ?? BASE_PATH,\n\n /**\n * Custom URL rewriting rules that override the default routing mode for specific paths.\n * Allows you to define locale-specific paths that differ from the standard routing behavior.\n * Supports dynamic route parameters using `[param]` syntax.\n *\n * Default: undefined\n *\n * Example:\n * ```typescript\n * rewrite: {\n * \"/about\": {\n * en: \"/about\",\n * fr: \"/a-propos\",\n * },\n * \"/product/[slug]\": {\n * en: \"/product/[slug]\",\n * fr: \"/produit/[slug]\",\n * },\n * }\n * ```\n *\n * Note:\n * - The rewrite rules take precedence over the default `mode` behavior.\n * - If a path matches a rewrite rule, the localized path from the rewrite configuration will be used.\n * - Dynamic route parameters are supported using bracket notation (e.g., `[slug]`, `[id]`).\n * - Works with both Next.js and Vite applications.\n */\n rewrite: customConfiguration?.rewrite,\n});\n\nconst buildSystemFields = (\n baseDir?: string,\n customConfiguration?: Partial<SystemConfig>\n): SystemConfig => {\n const projectBaseDir = baseDir ?? process.cwd();\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n const requireFunction = getProjectRequire(projectBaseDir);\n\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [projectBaseDir],\n });\n } catch {\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(projectBaseDir, pathInput);\n }\n\n try {\n const stats = statSync(absolutePath);\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n return absolutePath;\n };\n\n const dictionariesDir = optionalJoinBaseDir(\n customConfiguration?.dictionariesDir ?? DICTIONARIES_DIR\n );\n\n return {\n baseDir: projectBaseDir,\n moduleAugmentationDir: optionalJoinBaseDir(\n customConfiguration?.moduleAugmentationDir ?? MODULE_AUGMENTATION_DIR\n ),\n unmergedDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.unmergedDictionariesDir ?? UNMERGED_DICTIONARIES_DIR\n ),\n remoteDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.remoteDictionariesDir ?? REMOTE_DICTIONARIES_DIR\n ),\n dictionariesDir,\n dynamicDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.dynamicDictionariesDir ?? DYNAMIC_DICTIONARIES_DIR\n ),\n fetchDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.fetchDictionariesDir ?? FETCH_DICTIONARIES_DIR\n ),\n typesDir: optionalJoinBaseDir(customConfiguration?.typesDir ?? TYPES_DIR),\n mainDir: optionalJoinBaseDir(customConfiguration?.mainDir ?? MAIN_DIR),\n configDir: optionalJoinBaseDir(\n customConfiguration?.configDir ?? CONFIG_DIR\n ),\n cacheDir: optionalJoinBaseDir(customConfiguration?.cacheDir ?? CACHE_DIR),\n tempDir: optionalJoinBaseDir(customConfiguration?.tempDir ?? TEMP_DIR),\n outputFilesPatternWithPath: `${normalizePath(dictionariesDir)}/**/*.json`,\n };\n};\n\nconst buildContentFields = (\n systemConfig: SystemConfig,\n customConfiguration?: Partial<ContentConfig>\n): ContentConfig => {\n const fileExtensions = customConfiguration?.fileExtensions ?? FILE_EXTENSIONS;\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n // Try resolving as a Node module first\n const requireFunction = getProjectRequire(systemConfig.baseDir);\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch {\n try {\n // Fall back to native require.resolve if the custom require fails\n absolutePath = require.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch {\n // If all resolution fails, fall back to standard path joining\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(systemConfig.baseDir, pathInput);\n }\n }\n\n try {\n // Smart Detection: File vs Directory\n const stats = statSync(absolutePath);\n\n // If it resolved to a file (like package.json \"main\" or index.js),\n // we want the FOLDER containing that file.\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n // Safety Fallback:\n // If statSync fails but it looks like a file (has an extension), strip it.\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n // Return the calculated path (usually a directory)\n return absolutePath;\n };\n\n const contentDir = (customConfiguration?.contentDir ?? CONTENT_DIR).map(\n optionalJoinBaseDir\n );\n\n const codeDirInput = customConfiguration?.codeDir;\n\n const codeDir = (codeDirInput ?? CODE_DIR).map(optionalJoinBaseDir);\n\n return {\n fileExtensions,\n contentDir,\n codeDir,\n excludedPath: customConfiguration?.excludedPath ?? EXCLUDED_PATHS,\n watch: customConfiguration?.watch ?? WATCH,\n formatCommand: customConfiguration?.formatCommand,\n watchedFilesPattern: fileExtensions.map((ext) => `/**/*${ext}`),\n watchedFilesPatternWithPath: fileExtensions.flatMap((ext) =>\n contentDir.map((dir) => `${normalizePath(dir)}/**/*${ext}`)\n ),\n };\n};\n\nconst buildEditorFields = (\n customConfiguration?: Partial<EditorConfig>\n): EditorConfig => ({\n /**\n * URL of the application. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n applicationURL: customConfiguration?.applicationURL || APPLICATION_URL,\n\n /**\n * URL of the editor server. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n editorURL: customConfiguration?.editorURL || EDITOR_URL,\n\n /**\n * URL of the CMS server. Used to restrict the origin of the editor for security reasons.\n */\n cmsURL: customConfiguration?.cmsURL || CMS_URL,\n\n /**\n * URL of the editor server\n *\n * Default: 'https://back.intlayer.org'\n */\n backendURL: customConfiguration?.backendURL || BACKEND_URL,\n\n /** Port of the editor server\n *\n * Default: 8000\n */\n port: customConfiguration?.port ?? PORT,\n\n /**\n * Indicates if the application interact with the visual editor\n *\n * Default: false;\n *\n * If true, the editor will be able to interact with the application.\n * If false, the editor will not be able to interact with the application.\n * In any case, the editor can only be enabled by the visual editor.\n * Disabling the editor for specific environments is a way to enforce the security.\n *\n * Usage:\n * ```js\n * {\n * // Other configurations\n * editor: {\n * enabled: process.env.NODE_ENV !== 'production',\n * }\n * };\n * ```\n */\n enabled: customConfiguration?.enabled ?? IS_ENABLED,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientId: customConfiguration?.clientId ?? undefined,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientSecret: customConfiguration?.clientSecret ?? undefined,\n\n /**\n * Strategy for prioritizing dictionaries. If a dictionary is both present online and locally, the content will be merge.\n * However, is a field is defined in both dictionary, this setting determines which fields takes the priority over the other.\n *\n * Default: 'local_first'\n *\n * The strategy for prioritizing dictionaries. It can be either 'local_first' or 'distant_first'.\n * - 'local_first': The first dictionary found in the locale is used.\n * - 'distant_first': The first dictionary found in the distant locales is used.\n */\n dictionaryPriorityStrategy:\n customConfiguration?.dictionaryPriorityStrategy ??\n DICTIONARY_PRIORITY_STRATEGY,\n\n /**\n * Indicates if the application should hot reload the locale configurations when a change is detected.\n * For example, when a new dictionary is added or updated, the application will update the content tu display in the page.\n *\n * The hot reload is only available for clients of the `enterprise` plan.\n *\n * Default: false\n */\n liveSync: customConfiguration?.liveSync ?? LIVE_SYNC,\n\n /**\n * Port of the live sync server\n *\n * Default: 4000\n */\n liveSyncPort: customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT,\n\n /**\n * URL of the live sync server in case of remote live sync server\n *\n * Default: `http://localhost:${LIVE_SYNC_PORT}`\n */\n liveSyncURL:\n customConfiguration?.liveSyncURL ??\n `http://localhost:${customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT}`,\n});\n\nconst buildLogFields = (\n customConfiguration?: Partial<LogConfig>,\n logFunctions?: LogFunctions\n): LogConfig => ({\n /**\n * Indicates if the logger is enabled\n *\n * Default: 'prefix-no-default'\n *\n * If 'default', the logger is enabled and can be used.\n * If 'verbose', the logger will be enabled and can be used, but will log more information.\n * If 'disabled', the logger is disabled and cannot be used.\n */\n mode: customConfiguration?.mode ?? MODE,\n\n /**\n * Prefix of the logger\n *\n * Default: '[intlayer]'\n *\n * The prefix of the logger.\n */\n prefix: customConfiguration?.prefix ?? PREFIX,\n\n /**\n * Functions to log\n */\n error: logFunctions?.error,\n log: logFunctions?.log,\n info: logFunctions?.info,\n warn: logFunctions?.warn,\n});\n\nconst buildAiFields = (customConfiguration?: Partial<AiConfig>): AiConfig => ({\n /**\n * AI configuration\n */\n provider: customConfiguration?.provider,\n\n /**\n * API key\n */\n apiKey: customConfiguration?.apiKey,\n\n /**\n * API model\n */\n model: customConfiguration?.model,\n\n /**\n * Temperature\n */\n temperature: customConfiguration?.temperature,\n\n /**\n * Application context\n *\n * Default: undefined\n *\n * The application context.\n *\n * Example: `'My application context'`\n *\n * Note: Can be used to provide additional context about the application to the AI model. You can add more rules (e.g. \"You should not transform urls\").\n */\n applicationContext: customConfiguration?.applicationContext,\n\n /**\n * Base URL for the AI API\n *\n * Default: undefined\n *\n * The base URL for the AI API.\n *\n * Example: `'http://localhost:5000'`\n *\n * Note: Can be used to point to a local, or custom AI API endpoint.\n */\n baseURL: customConfiguration?.baseURL,\n\n /**\n * Data serialization\n *\n * Options:\n * - \"json\": The industry standard. Highly reliable and structured, but consumes more tokens.\n * - \"toon\": An optimized format designed to reduce token consumption (cost-effective). However, it may slightly increase the risk of output inconsistency compared to standard JSON\n *\n * Default: \"json\"\n */\n dataSerialization: customConfiguration?.dataSerialization,\n});\n\nconst buildBuildFields = (\n customConfiguration?: Partial<BuildConfig>\n): BuildConfig => ({\n /**\n * Indicates the mode of the build\n *\n * Default: 'auto'\n *\n * If 'auto', the build will be enabled automatically when the application is built.\n * If 'manual', the build will be set only when the build command is executed.\n *\n * Can be used to disable dictionaries build, for instance when execution on Node.js environment should be avoided.\n */\n mode: customConfiguration?.mode ?? BUILD_MODE,\n\n /**\n * Indicates if the build should be optimized\n *\n * Default: process.env.NODE_ENV === 'production'\n *\n * If true, the build will be optimized.\n * If false, the build will not be optimized.\n *\n * Intlayer will replace all calls of dictionaries to optimize chunking. That way the final bundle will import only the dictionaries that are used.\n * All imports will stay as static import to avoid async processing when loading the dictionaries.\n *\n * Note:\n * - Intlayer will replace all call of `useIntlayer` with the defined mode by the `importMode` option.\n * - Intlayer will replace all call of `getIntlayer` with `getDictionary`.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - In most cases, \"dynamic\" will be used for React applications, \"async\" for Vue.js applications.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n */\n optimize: customConfiguration?.optimize,\n\n /**\n * Indicates the mode of import to use for the dictionaries.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionary`.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * Live mode will use the live sync API to fetch the dictionaries. If the API call fails, the dictionaries will be imported dynamically as \"dynamic\" mode.\n *\n * Default: \"static\"\n *\n * By default, when a dictionary is loaded, it imports content for all locales as it's imported statically.\n *\n * Note:\n * - Dynamic imports rely on Suspense and may slightly impact rendering performance.\n * - If disabled all locales will be loaded at once, even if they are not used.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n * - This option will be ignored if `optimize` is disabled.\n * - This option will not impact the `getIntlayer`, `getDictionary`, `useDictionary`, `useDictionaryAsync` and `useDictionaryDynamic` functions. You can still use them to refine you code on manual optimization.\n * - The \"live\" allows to sync the dictionaries to the live sync server.\n *\n * @deprecated Use `dictionary.importMode` instead.\n */\n importMode: customConfiguration?.importMode,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * Allows to avoid to traverse the code that is not relevant to the optimization.\n * Improve build performance.\n *\n * Default: ['**\\/*.{js,ts,mjs,cjs,jsx,tsx}', '!**\\/node_modules/**']\n *\n * Example: `['src/**\\/*.{ts,tsx}', '../ui-library/**\\/*.{ts,tsx}']`\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - Use glob pattern.\n */\n traversePattern: customConfiguration?.traversePattern ?? TRAVERSE_PATTERN,\n\n /**\n * Output format of the dictionaries\n *\n * Can be set on large projects to improve build performance.\n *\n * Default: ['cjs', 'esm']\n *\n * The output format of the dictionaries. It can be either 'cjs' or 'esm'.\n * - 'cjs': The dictionaries are outputted as CommonJS modules.\n * - 'esm': The dictionaries are outputted as ES modules.\n */\n outputFormat: customConfiguration?.outputFormat ?? OUTPUT_FORMAT,\n\n /**\n * Cache\n */\n cache: customConfiguration?.cache ?? CACHE,\n\n /**\n * Require function\n */\n require: customConfiguration?.require,\n\n /**\n * Indicates if the build should check TypeScript types\n *\n * Default: false\n *\n * If true, the build will check TypeScript types and log errors.\n * Note: This can slow down the build.\n */\n checkTypes: customConfiguration?.checkTypes ?? TYPE_CHECKING,\n});\n\nconst buildCompilerFields = (\n customConfiguration?: Partial<CompilerConfig>\n): CompilerConfig => ({\n /**\n * Indicates if the compiler should be enabled\n */\n enabled: customConfiguration?.enabled ?? COMPILER_ENABLED,\n\n /**\n * Prefix for the extracted dictionary keys\n */\n dictionaryKeyPrefix:\n customConfiguration?.dictionaryKeyPrefix ?? COMPILER_DICTIONARY_KEY_PREFIX,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * @deprecated use build.traversePattern instead\n */\n transformPattern: customConfiguration?.transformPattern,\n\n /**\n * Pattern to exclude from the optimization.\n *\n * @deprecated use build.traversePattern instead\n */\n excludePattern: customConfiguration?.excludePattern,\n\n /**\n * Defines the output files path. Replaces `outputDir`.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - Including the `{{locale}}` variable in the path will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * output: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // output: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * output: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // output: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n output: customConfiguration?.output,\n\n /**\n * Indicates if the metadata should be saved in the file.\n *\n * If true, the compiler will not save the metadata of the dictionaries.\n *\n * If true:\n *\n * ```json\n * {\n * \"key\": \"value\"\n * }\n * ```\n *\n * If false:\n *\n * ```json\n * {\n * \"key\": \"value\",\n * \"content\": {\n * \"key\": \"value\"\n * }\n * }\n * ```\n *\n * Default: false\n *\n * Note: Useful if used with loadJSON plugin\n */\n noMetadata: customConfiguration?.noMetadata ?? COMPILER_NO_METADATA,\n\n /**\n * Indicates if the components should be saved after being transformed.\n */\n saveComponents:\n customConfiguration?.saveComponents ?? COMPILER_SAVE_COMPONENTS,\n});\n\nconst buildDictionaryFields = (\n customConfiguration?: Partial<DictionaryConfig>\n): DictionaryConfig => {\n const contentAutoTransformation =\n customConfiguration?.contentAutoTransformation ??\n CONTENT_AUTO_TRANSFORMATION;\n\n return {\n /**\n * Indicate how the dictionary should be filled using AI.\n *\n * Default: `true`\n *\n * - If `true`, will consider the `compiler.output` field.\n * - If `false`, will skip the fill process.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - If includes `{{locale}}` variable in the path, will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * fill: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // fill: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * fill: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // fill: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create custom output based on the locale\n * fill: {\n * en: ({ key }) => `/locales/en/${key}.content.json`,\n * fr: '/locales/fr/{{key}}.content.json',\n * es: false,\n * de: true,\n * },\n * }\n * ```\n *\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n fill: customConfiguration?.fill ?? FILL,\n\n /**\n * Indicates if the content of the dictionary should be automatically transformed.\n *\n * Default: false\n */\n contentAutoTransformation:\n typeof contentAutoTransformation === 'object'\n ? {\n markdown: contentAutoTransformation.markdown ?? false,\n html: contentAutoTransformation.html ?? false,\n insertion: contentAutoTransformation.insertion ?? false,\n }\n : contentAutoTransformation,\n\n /**\n * The location of the dictionary.\n *\n * Default: 'local'\n */\n location: customConfiguration?.location ?? LOCATION,\n\n /**\n * Transform the dictionary in a per-locale dictionary.\n * Each field declared in a per-locale dictionary will be transformed in a translation node.\n * If missing, the dictionary will be treated as a multilingual dictionary.\n */\n locale: customConfiguration?.locale,\n\n /**\n * The title of the dictionary.\n */\n title: customConfiguration?.title,\n\n /**\n * The description of the dictionary.\n */\n description: customConfiguration?.description,\n\n /**\n * Tags to categorize the dictionaries.\n */\n tags: customConfiguration?.tags,\n\n /**\n * The priority of the dictionary.\n */\n priority: customConfiguration?.priority,\n\n /**\n * Indicates the mode of import to use for the dictionary.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n *\n * Default: 'static'\n */\n importMode: customConfiguration?.importMode ?? IMPORT_MODE,\n };\n};\n\n/**\n * Build the configuration fields by merging the default values with the custom configuration\n */\nexport const buildConfigurationFields = (\n customConfiguration?: CustomIntlayerConfig,\n baseDir?: string,\n logFunctions?: LogFunctions\n): IntlayerConfig => {\n const internationalizationConfig = buildInternationalizationFields(\n customConfiguration?.internationalization\n );\n\n const routingConfig = buildRoutingFields(customConfiguration?.routing);\n\n const systemConfig = buildSystemFields(baseDir, customConfiguration?.system);\n\n const contentConfig = buildContentFields(\n systemConfig,\n customConfiguration?.content\n );\n\n const editorConfig = buildEditorFields(customConfiguration?.editor);\n\n const logConfig = buildLogFields(customConfiguration?.log, logFunctions);\n\n const aiConfig = buildAiFields(customConfiguration?.ai);\n\n const buildConfig = buildBuildFields(customConfiguration?.build);\n\n const compilerConfig = buildCompilerFields(customConfiguration?.compiler);\n\n const dictionaryConfig = buildDictionaryFields(\n customConfiguration?.dictionary\n );\n\n storedConfiguration = {\n internationalization: internationalizationConfig,\n routing: routingConfig,\n content: contentConfig,\n system: systemConfig,\n editor: editorConfig,\n log: logConfig,\n ai: aiConfig,\n build: buildConfig,\n compiler: compilerConfig,\n dictionary: dictionaryConfig,\n plugins: customConfiguration?.plugins,\n schemas: customConfiguration?.schemas,\n metadata: {\n name: 'Intlayer',\n version: packageJson.version,\n doc: `https://intlayer.org/docs`,\n },\n } as IntlayerConfig;\n\n return storedConfiguration;\n};\n"],"mappings":"+rBA+EA,IAAI,EAEJ,MAAM,EACJ,IACgC,CAOhC,QAAS,GAAqB,SAAWA,EAAAA,QAWzC,gBACE,GAAqB,iBACrB,GAAqB,SACrBC,EAAAA,iBAUF,WAAY,GAAqB,YAAA,YAOjC,cAAe,GAAqB,eAAiBC,EAAAA,eACtD,EAEK,EACJ,IACmB,CAuBnB,KAAM,GAAqB,MAAA,oBAW3B,QAAS,GAAqB,SAAWC,EAAAA,QAazC,SAAU,GAAqB,UAAA,GA6B/B,QAAS,GAAqB,QAC/B,EAEK,GACJ,EACA,IACiB,CACjB,IAAM,EAAiB,GAAW,QAAQ,KAAK,CAEzC,EAAuB,GAAsB,CACjD,I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EAAe,GAAqB,IAAK,EAAa,CAmBtE,GAjBe,EAAc,GAAqB,GAAG,CAkBrD,MAhBkB,EAAiB,GAAqB,MAAM,CAiB9D,SAfqB,EAAoB,GAAqB,SAAS,CAgBvE,WAduB,EACvB,GAAqB,WACtB,CAaC,QAAS,GAAqB,QAC9B,QAAS,GAAqB,QAC9B,SAAU,CACR,KAAM,WACN,QAASC,EAAAA,QAAY,QACrB,IAAK,4BACN,CACF,CAEM"}
@@ -1 +1 @@
1
- {"version":3,"file":"buildConfigurationFields.mjs","names":[],"sources":["../../../src/configFile/buildConfigurationFields.ts"],"sourcesContent":["import { statSync } from 'node:fs';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport type {\n AiConfig,\n BuildConfig,\n CompilerConfig,\n ContentConfig,\n CustomIntlayerConfig,\n DictionaryConfig,\n EditorConfig,\n InternationalizationConfig,\n IntlayerConfig,\n LogConfig,\n LogFunctions,\n RoutingConfig,\n SystemConfig,\n} from '@intlayer/types/config';\nimport packageJson from '@intlayer/types/package.json' with { type: 'json' };\nimport {\n BUILD_MODE,\n CACHE,\n OUTPUT_FORMAT,\n TRAVERSE_PATTERN,\n TYPE_CHECKING,\n} from '../defaultValues/build';\nimport {\n COMPILER_DICTIONARY_KEY_PREFIX,\n COMPILER_ENABLED,\n COMPILER_NO_METADATA,\n COMPILER_SAVE_COMPONENTS,\n} from '../defaultValues/compiler';\nimport {\n CODE_DIR,\n CONTENT_DIR,\n EXCLUDED_PATHS,\n FILE_EXTENSIONS,\n WATCH,\n} from '../defaultValues/content';\nimport {\n CONTENT_AUTO_TRANSFORMATION,\n FILL,\n IMPORT_MODE,\n LOCATION,\n} from '../defaultValues/dictionary';\nimport {\n APPLICATION_URL,\n BACKEND_URL,\n CMS_URL,\n DICTIONARY_PRIORITY_STRATEGY,\n EDITOR_URL,\n IS_ENABLED,\n LIVE_SYNC,\n LIVE_SYNC_PORT,\n PORT,\n} from '../defaultValues/editor';\nimport {\n DEFAULT_LOCALE,\n LOCALES,\n REQUIRED_LOCALES,\n STRICT_MODE,\n} from '../defaultValues/internationalization';\nimport { MODE, PREFIX } from '../defaultValues/log';\nimport { BASE_PATH, ROUTING_MODE, STORAGE } from '../defaultValues/routing';\nimport {\n CACHE_DIR,\n CONFIG_DIR,\n DICTIONARIES_DIR,\n DYNAMIC_DICTIONARIES_DIR,\n FETCH_DICTIONARIES_DIR,\n MAIN_DIR,\n MODULE_AUGMENTATION_DIR,\n REMOTE_DICTIONARIES_DIR,\n TEMP_DIR,\n TYPES_DIR,\n UNMERGED_DICTIONARIES_DIR,\n} from '../defaultValues/system';\nimport { getProjectRequire } from '../utils';\nimport { normalizePath } from '../utils/normalizePath';\n\nlet storedConfiguration: IntlayerConfig;\n\nconst buildInternationalizationFields = (\n customConfiguration?: Partial<InternationalizationConfig>\n): InternationalizationConfig => ({\n /**\n * Locales available in the application\n *\n * Default: ['en']\n *\n */\n locales: customConfiguration?.locales ?? LOCALES,\n\n /**\n * Locales required by TypeScript to ensure strong implementations of internationalized content using typescript.\n *\n * Default: []\n *\n * If empty, all locales are required in `strict` mode.\n *\n * Ensure required locales are also defined in the `locales` field.\n */\n requiredLocales:\n customConfiguration?.requiredLocales ??\n customConfiguration?.locales ??\n REQUIRED_LOCALES,\n\n /**\n * Ensure strong implementations of internationalized content using typescript.\n * - If set to \"strict\", the translation `t` function will require each declared locales to be defined. If one locale is missing, or if a locale is not declared in your config, it will throw an error.\n * - If set to \"inclusive\", the translation `t` function will require each declared locales to be defined. If one locale is missing, it will throw a warning. But will accept if a locale is not declared in your config, but exist.\n * - If set to \"loose\", the translation `t` function will accept any existing locale.\n *\n * Default: \"inclusive\"\n */\n strictMode: customConfiguration?.strictMode ?? STRICT_MODE,\n\n /**\n * Default locale of the application for fallback\n *\n * Default: 'en'\n */\n defaultLocale: customConfiguration?.defaultLocale ?? DEFAULT_LOCALE,\n});\n\nconst buildRoutingFields = (\n customConfiguration?: Partial<RoutingConfig>\n): RoutingConfig => ({\n /**\n * URL routing mode for locale handling\n *\n * Controls how locales are represented in application URLs:\n * - 'prefix-no-default': Prefix all locales except the default locale (default)\n * - en → /dashboard\n * - fr → /fr/dashboard\n *\n * - 'prefix-all': Prefix all locales including the default locale\n * - en → /en/dashboard\n * - fr → /fr/dashboard\n *\n * - 'search-params': Use search parameters for locale handling\n * - en → /dashboard?locale=en\n * - fr → /fr/dashboard?locale=fr\n *\n * - 'no-prefix': No locale prefixing in URLs\n * - en → /dashboard\n * - fr → /dashboard\n *\n * Default: 'prefix-no-default'\n */\n mode: customConfiguration?.mode ?? ROUTING_MODE,\n\n /**\n * Configuration for storing the locale in the client (localStorage or sessionStorage)\n *\n * If false, the locale will not be stored by the middleware.\n * If true, the locale storage will consider all default values. (cookie and header)\n *\n * Default: ['cookie', 'header']\n *\n */\n storage: customConfiguration?.storage ?? STORAGE,\n\n /**\n * Base path of the application URL\n *\n * Default: ''\n *\n * Example:\n * - If the application is hosted at https://example.com/my-app\n * - The base path is '/my-app'\n * - The URL will be https://example.com/my-app/en\n * - If the base path is not set, the URL will be https://example.com/en\n */\n basePath: customConfiguration?.basePath ?? BASE_PATH,\n\n /**\n * Custom URL rewriting rules that override the default routing mode for specific paths.\n * Allows you to define locale-specific paths that differ from the standard routing behavior.\n * Supports dynamic route parameters using `[param]` syntax.\n *\n * Default: undefined\n *\n * Example:\n * ```typescript\n * rewrite: {\n * \"/about\": {\n * en: \"/about\",\n * fr: \"/a-propos\",\n * },\n * \"/product/[slug]\": {\n * en: \"/product/[slug]\",\n * fr: \"/produit/[slug]\",\n * },\n * }\n * ```\n *\n * Note:\n * - The rewrite rules take precedence over the default `mode` behavior.\n * - If a path matches a rewrite rule, the localized path from the rewrite configuration will be used.\n * - Dynamic route parameters are supported using bracket notation (e.g., `[slug]`, `[id]`).\n * - Works with both Next.js and Vite applications.\n */\n rewrite: customConfiguration?.rewrite,\n});\n\nconst buildSystemFields = (\n baseDir?: string,\n customConfiguration?: Partial<SystemConfig>\n): SystemConfig => {\n const projectBaseDir = baseDir ?? process.cwd();\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n const requireFunction = getProjectRequire(projectBaseDir);\n\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [projectBaseDir],\n });\n } catch {\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(projectBaseDir, pathInput);\n }\n\n try {\n const stats = statSync(absolutePath);\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n return absolutePath;\n };\n\n const dictionariesDir = optionalJoinBaseDir(\n customConfiguration?.dictionariesDir ?? DICTIONARIES_DIR\n );\n\n return {\n baseDir: projectBaseDir,\n moduleAugmentationDir: optionalJoinBaseDir(\n customConfiguration?.moduleAugmentationDir ?? MODULE_AUGMENTATION_DIR\n ),\n unmergedDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.unmergedDictionariesDir ?? UNMERGED_DICTIONARIES_DIR\n ),\n remoteDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.remoteDictionariesDir ?? REMOTE_DICTIONARIES_DIR\n ),\n dictionariesDir,\n dynamicDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.dynamicDictionariesDir ?? DYNAMIC_DICTIONARIES_DIR\n ),\n fetchDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.fetchDictionariesDir ?? FETCH_DICTIONARIES_DIR\n ),\n typesDir: optionalJoinBaseDir(customConfiguration?.typesDir ?? TYPES_DIR),\n mainDir: optionalJoinBaseDir(customConfiguration?.mainDir ?? MAIN_DIR),\n configDir: optionalJoinBaseDir(\n customConfiguration?.configDir ?? CONFIG_DIR\n ),\n cacheDir: optionalJoinBaseDir(customConfiguration?.cacheDir ?? CACHE_DIR),\n tempDir: optionalJoinBaseDir(customConfiguration?.tempDir ?? TEMP_DIR),\n outputFilesPatternWithPath: `${normalizePath(dictionariesDir)}/**/*.json`,\n };\n};\n\nconst buildContentFields = (\n systemConfig: SystemConfig,\n customConfiguration?: Partial<ContentConfig>\n): ContentConfig => {\n const fileExtensions = customConfiguration?.fileExtensions ?? FILE_EXTENSIONS;\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n // Try resolving as a Node module first\n const requireFunction = getProjectRequire(systemConfig.baseDir);\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch {\n try {\n // Fall back to native require.resolve if the custom require fails\n absolutePath = require.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch {\n // If all resolution fails, fall back to standard path joining\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(systemConfig.baseDir, pathInput);\n }\n }\n\n try {\n // Smart Detection: File vs Directory\n const stats = statSync(absolutePath);\n\n // If it resolved to a file (like package.json \"main\" or index.js),\n // we want the FOLDER containing that file.\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n // Safety Fallback:\n // If statSync fails but it looks like a file (has an extension), strip it.\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n // Return the calculated path (usually a directory)\n return absolutePath;\n };\n\n const contentDir = (customConfiguration?.contentDir ?? CONTENT_DIR).map(\n optionalJoinBaseDir\n );\n\n const codeDirInput = customConfiguration?.codeDir;\n\n const codeDir = (codeDirInput ?? CODE_DIR).map(optionalJoinBaseDir);\n\n return {\n fileExtensions,\n contentDir,\n codeDir,\n excludedPath: customConfiguration?.excludedPath ?? EXCLUDED_PATHS,\n watch: customConfiguration?.watch ?? WATCH,\n formatCommand: customConfiguration?.formatCommand,\n watchedFilesPattern: fileExtensions.map((ext) => `/**/*${ext}`),\n watchedFilesPatternWithPath: fileExtensions.flatMap((ext) =>\n contentDir.map((dir) => `${normalizePath(dir)}/**/*${ext}`)\n ),\n };\n};\n\nconst buildEditorFields = (\n customConfiguration?: Partial<EditorConfig>\n): EditorConfig => ({\n /**\n * URL of the application. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n applicationURL: customConfiguration?.applicationURL || APPLICATION_URL,\n\n /**\n * URL of the editor server. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n editorURL: customConfiguration?.editorURL || EDITOR_URL,\n\n /**\n * URL of the CMS server. Used to restrict the origin of the editor for security reasons.\n */\n cmsURL: customConfiguration?.cmsURL || CMS_URL,\n\n /**\n * URL of the editor server\n *\n * Default: 'https://back.intlayer.org'\n */\n backendURL: customConfiguration?.backendURL || BACKEND_URL,\n\n /** Port of the editor server\n *\n * Default: 8000\n */\n port: customConfiguration?.port ?? PORT,\n\n /**\n * Indicates if the application interact with the visual editor\n *\n * Default: true;\n *\n * If true, the editor will be able to interact with the application.\n * If false, the editor will not be able to interact with the application.\n * In any case, the editor can only be enabled by the visual editor.\n * Disabling the editor for specific environments is a way to enforce the security.\n *\n * Usage:\n * ```js\n * {\n * // Other configurations\n * editor: {\n * enabled: process.env.NODE_ENV !== 'production',\n * }\n * };\n * ```\n */\n enabled: customConfiguration?.enabled ?? IS_ENABLED,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientId: customConfiguration?.clientId ?? undefined,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientSecret: customConfiguration?.clientSecret ?? undefined,\n\n /**\n * Strategy for prioritizing dictionaries. If a dictionary is both present online and locally, the content will be merge.\n * However, is a field is defined in both dictionary, this setting determines which fields takes the priority over the other.\n *\n * Default: 'local_first'\n *\n * The strategy for prioritizing dictionaries. It can be either 'local_first' or 'distant_first'.\n * - 'local_first': The first dictionary found in the locale is used.\n * - 'distant_first': The first dictionary found in the distant locales is used.\n */\n dictionaryPriorityStrategy:\n customConfiguration?.dictionaryPriorityStrategy ??\n DICTIONARY_PRIORITY_STRATEGY,\n\n /**\n * Indicates if the application should hot reload the locale configurations when a change is detected.\n * For example, when a new dictionary is added or updated, the application will update the content tu display in the page.\n *\n * The hot reload is only available for clients of the `enterprise` plan.\n *\n * Default: false\n */\n liveSync: customConfiguration?.liveSync ?? LIVE_SYNC,\n\n /**\n * Port of the live sync server\n *\n * Default: 4000\n */\n liveSyncPort: customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT,\n\n /**\n * URL of the live sync server in case of remote live sync server\n *\n * Default: `http://localhost:${LIVE_SYNC_PORT}`\n */\n liveSyncURL:\n customConfiguration?.liveSyncURL ??\n `http://localhost:${customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT}`,\n});\n\nconst buildLogFields = (\n customConfiguration?: Partial<LogConfig>,\n logFunctions?: LogFunctions\n): LogConfig => ({\n /**\n * Indicates if the logger is enabled\n *\n * Default: 'prefix-no-default'\n *\n * If 'default', the logger is enabled and can be used.\n * If 'verbose', the logger will be enabled and can be used, but will log more information.\n * If 'disabled', the logger is disabled and cannot be used.\n */\n mode: customConfiguration?.mode ?? MODE,\n\n /**\n * Prefix of the logger\n *\n * Default: '[intlayer]'\n *\n * The prefix of the logger.\n */\n prefix: customConfiguration?.prefix ?? PREFIX,\n\n /**\n * Functions to log\n */\n error: logFunctions?.error,\n log: logFunctions?.log,\n info: logFunctions?.info,\n warn: logFunctions?.warn,\n});\n\nconst buildAiFields = (customConfiguration?: Partial<AiConfig>): AiConfig => ({\n /**\n * AI configuration\n */\n provider: customConfiguration?.provider,\n\n /**\n * API key\n */\n apiKey: customConfiguration?.apiKey,\n\n /**\n * API model\n */\n model: customConfiguration?.model,\n\n /**\n * Temperature\n */\n temperature: customConfiguration?.temperature,\n\n /**\n * Application context\n *\n * Default: undefined\n *\n * The application context.\n *\n * Example: `'My application context'`\n *\n * Note: Can be used to provide additional context about the application to the AI model. You can add more rules (e.g. \"You should not transform urls\").\n */\n applicationContext: customConfiguration?.applicationContext,\n\n /**\n * Base URL for the AI API\n *\n * Default: undefined\n *\n * The base URL for the AI API.\n *\n * Example: `'http://localhost:5000'`\n *\n * Note: Can be used to point to a local, or custom AI API endpoint.\n */\n baseURL: customConfiguration?.baseURL,\n\n /**\n * Data serialization\n *\n * Options:\n * - \"json\": The industry standard. Highly reliable and structured, but consumes more tokens.\n * - \"toon\": An optimized format designed to reduce token consumption (cost-effective). However, it may slightly increase the risk of output inconsistency compared to standard JSON\n *\n * Default: \"json\"\n */\n dataSerialization: customConfiguration?.dataSerialization,\n});\n\nconst buildBuildFields = (\n customConfiguration?: Partial<BuildConfig>\n): BuildConfig => ({\n /**\n * Indicates the mode of the build\n *\n * Default: 'auto'\n *\n * If 'auto', the build will be enabled automatically when the application is built.\n * If 'manual', the build will be set only when the build command is executed.\n *\n * Can be used to disable dictionaries build, for instance when execution on Node.js environment should be avoided.\n */\n mode: customConfiguration?.mode ?? BUILD_MODE,\n\n /**\n * Indicates if the build should be optimized\n *\n * Default: process.env.NODE_ENV === 'production'\n *\n * If true, the build will be optimized.\n * If false, the build will not be optimized.\n *\n * Intlayer will replace all calls of dictionaries to optimize chunking. That way the final bundle will import only the dictionaries that are used.\n * All imports will stay as static import to avoid async processing when loading the dictionaries.\n *\n * Note:\n * - Intlayer will replace all call of `useIntlayer` with the defined mode by the `importMode` option.\n * - Intlayer will replace all call of `getIntlayer` with `getDictionary`.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - In most cases, \"dynamic\" will be used for React applications, \"async\" for Vue.js applications.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n */\n optimize: customConfiguration?.optimize,\n\n /**\n * Indicates the mode of import to use for the dictionaries.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionary`.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * Live mode will use the live sync API to fetch the dictionaries. If the API call fails, the dictionaries will be imported dynamically as \"dynamic\" mode.\n *\n * Default: \"static\"\n *\n * By default, when a dictionary is loaded, it imports content for all locales as it's imported statically.\n *\n * Note:\n * - Dynamic imports rely on Suspense and may slightly impact rendering performance.\n * - If disabled all locales will be loaded at once, even if they are not used.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n * - This option will be ignored if `optimize` is disabled.\n * - This option will not impact the `getIntlayer`, `getDictionary`, `useDictionary`, `useDictionaryAsync` and `useDictionaryDynamic` functions. You can still use them to refine you code on manual optimization.\n * - The \"live\" allows to sync the dictionaries to the live sync server.\n *\n * @deprecated Use `dictionary.importMode` instead.\n */\n importMode: customConfiguration?.importMode,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * Allows to avoid to traverse the code that is not relevant to the optimization.\n * Improve build performance.\n *\n * Default: ['**\\/*.{js,ts,mjs,cjs,jsx,tsx}', '!**\\/node_modules/**']\n *\n * Example: `['src/**\\/*.{ts,tsx}', '../ui-library/**\\/*.{ts,tsx}']`\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - Use glob pattern.\n */\n traversePattern: customConfiguration?.traversePattern ?? TRAVERSE_PATTERN,\n\n /**\n * Output format of the dictionaries\n *\n * Can be set on large projects to improve build performance.\n *\n * Default: ['cjs', 'esm']\n *\n * The output format of the dictionaries. It can be either 'cjs' or 'esm'.\n * - 'cjs': The dictionaries are outputted as CommonJS modules.\n * - 'esm': The dictionaries are outputted as ES modules.\n */\n outputFormat: customConfiguration?.outputFormat ?? OUTPUT_FORMAT,\n\n /**\n * Cache\n */\n cache: customConfiguration?.cache ?? CACHE,\n\n /**\n * Require function\n */\n require: customConfiguration?.require,\n\n /**\n * Indicates if the build should check TypeScript types\n *\n * Default: false\n *\n * If true, the build will check TypeScript types and log errors.\n * Note: This can slow down the build.\n */\n checkTypes: customConfiguration?.checkTypes ?? TYPE_CHECKING,\n});\n\nconst buildCompilerFields = (\n customConfiguration?: Partial<CompilerConfig>\n): CompilerConfig => ({\n /**\n * Indicates if the compiler should be enabled\n */\n enabled: customConfiguration?.enabled ?? COMPILER_ENABLED,\n\n /**\n * Prefix for the extracted dictionary keys\n */\n dictionaryKeyPrefix:\n customConfiguration?.dictionaryKeyPrefix ?? COMPILER_DICTIONARY_KEY_PREFIX,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * @deprecated use build.traversePattern instead\n */\n transformPattern: customConfiguration?.transformPattern,\n\n /**\n * Pattern to exclude from the optimization.\n *\n * @deprecated use build.traversePattern instead\n */\n excludePattern: customConfiguration?.excludePattern,\n\n /**\n * Defines the output files path. Replaces `outputDir`.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - Including the `{{locale}}` variable in the path will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * output: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // output: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * output: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // output: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n output: customConfiguration?.output,\n\n /**\n * Indicates if the metadata should be saved in the file.\n *\n * If true, the compiler will not save the metadata of the dictionaries.\n *\n * If true:\n *\n * ```json\n * {\n * \"key\": \"value\"\n * }\n * ```\n *\n * If false:\n *\n * ```json\n * {\n * \"key\": \"value\",\n * \"content\": {\n * \"key\": \"value\"\n * }\n * }\n * ```\n *\n * Default: false\n *\n * Note: Useful if used with loadJSON plugin\n */\n noMetadata: customConfiguration?.noMetadata ?? COMPILER_NO_METADATA,\n\n /**\n * Indicates if the components should be saved after being transformed.\n */\n saveComponents:\n customConfiguration?.saveComponents ?? COMPILER_SAVE_COMPONENTS,\n});\n\nconst buildDictionaryFields = (\n customConfiguration?: Partial<DictionaryConfig>\n): DictionaryConfig => {\n const contentAutoTransformation =\n customConfiguration?.contentAutoTransformation ??\n CONTENT_AUTO_TRANSFORMATION;\n\n return {\n /**\n * Indicate how the dictionary should be filled using AI.\n *\n * Default: `true`\n *\n * - If `true`, will consider the `compiler.output` field.\n * - If `false`, will skip the fill process.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - If includes `{{locale}}` variable in the path, will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * fill: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // fill: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * fill: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // fill: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create custom output based on the locale\n * fill: {\n * en: ({ key }) => `/locales/en/${key}.content.json`,\n * fr: '/locales/fr/{{key}}.content.json',\n * es: false,\n * de: true,\n * },\n * }\n * ```\n *\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n fill: customConfiguration?.fill ?? FILL,\n\n /**\n * Indicates if the content of the dictionary should be automatically transformed.\n *\n * Default: false\n */\n contentAutoTransformation:\n typeof contentAutoTransformation === 'object'\n ? {\n markdown: contentAutoTransformation.markdown ?? false,\n html: contentAutoTransformation.html ?? false,\n insertion: contentAutoTransformation.insertion ?? false,\n }\n : contentAutoTransformation,\n\n /**\n * The location of the dictionary.\n *\n * Default: 'local'\n */\n location: customConfiguration?.location ?? LOCATION,\n\n /**\n * Transform the dictionary in a per-locale dictionary.\n * Each field declared in a per-locale dictionary will be transformed in a translation node.\n * If missing, the dictionary will be treated as a multilingual dictionary.\n */\n locale: customConfiguration?.locale,\n\n /**\n * The title of the dictionary.\n */\n title: customConfiguration?.title,\n\n /**\n * The description of the dictionary.\n */\n description: customConfiguration?.description,\n\n /**\n * Tags to categorize the dictionaries.\n */\n tags: customConfiguration?.tags,\n\n /**\n * The priority of the dictionary.\n */\n priority: customConfiguration?.priority,\n\n /**\n * Indicates the mode of import to use for the dictionary.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n *\n * Default: 'static'\n */\n importMode: customConfiguration?.importMode ?? IMPORT_MODE,\n };\n};\n\n/**\n * Build the configuration fields by merging the default values with the custom configuration\n */\nexport const buildConfigurationFields = (\n customConfiguration?: CustomIntlayerConfig,\n baseDir?: string,\n logFunctions?: LogFunctions\n): IntlayerConfig => {\n const internationalizationConfig = buildInternationalizationFields(\n customConfiguration?.internationalization\n );\n\n const routingConfig = buildRoutingFields(customConfiguration?.routing);\n\n const systemConfig = buildSystemFields(baseDir, customConfiguration?.system);\n\n const contentConfig = buildContentFields(\n systemConfig,\n customConfiguration?.content\n );\n\n const editorConfig = buildEditorFields(customConfiguration?.editor);\n\n const logConfig = buildLogFields(customConfiguration?.log, logFunctions);\n\n const aiConfig = buildAiFields(customConfiguration?.ai);\n\n const buildConfig = buildBuildFields(customConfiguration?.build);\n\n const compilerConfig = buildCompilerFields(customConfiguration?.compiler);\n\n const dictionaryConfig = buildDictionaryFields(\n customConfiguration?.dictionary\n );\n\n storedConfiguration = {\n internationalization: internationalizationConfig,\n routing: routingConfig,\n content: contentConfig,\n system: systemConfig,\n editor: editorConfig,\n log: logConfig,\n ai: aiConfig,\n build: buildConfig,\n compiler: compilerConfig,\n dictionary: dictionaryConfig,\n plugins: customConfiguration?.plugins,\n schemas: customConfiguration?.schemas,\n metadata: {\n name: 'Intlayer',\n version: packageJson.version,\n doc: `https://intlayer.org/docs`,\n },\n } as IntlayerConfig;\n\n return storedConfiguration;\n};\n"],"mappings":"u4BA+EA,IAAI,EAEJ,MAAM,EACJ,IACgC,CAOhC,QAAS,GAAqB,SAAW,EAWzC,gBACE,GAAqB,iBACrB,GAAqB,SACrB,EAUF,WAAY,GAAqB,YAAA,YAOjC,cAAe,GAAqB,eAAiB,EACtD,EAEK,EACJ,IACmB,CAuBnB,KAAM,GAAqB,MAAA,oBAW3B,QAAS,GAAqB,SAAW,EAazC,SAAU,GAAqB,UAAA,GA6B/B,QAAS,GAAqB,QAC/B,EAEK,GACJ,EACA,IACiB,CACjB,IAAM,EAAiB,GAAW,QAAQ,KAAK,CAEzC,EAAuB,GAAsB,CACjD,IAAI,EAEJ,GAAI,CAGF,EAFwB,EAAkB,EAAe,CAE1B,QAAQ,EAAW,CAChD,MAAO,CAAC,EAAe,CACxB,CAAC,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son"],"sources":["../../../src/configFile/buildConfigurationFields.ts"],"sourcesContent":["import { statSync } from 'node:fs';\nimport { dirname, isAbsolute, join } from 'node:path';\nimport type {\n AiConfig,\n BuildConfig,\n CompilerConfig,\n ContentConfig,\n CustomIntlayerConfig,\n DictionaryConfig,\n EditorConfig,\n InternationalizationConfig,\n IntlayerConfig,\n LogConfig,\n LogFunctions,\n RoutingConfig,\n SystemConfig,\n} from '@intlayer/types/config';\nimport packageJson from '@intlayer/types/package.json' with { type: 'json' };\nimport {\n BUILD_MODE,\n CACHE,\n OUTPUT_FORMAT,\n TRAVERSE_PATTERN,\n TYPE_CHECKING,\n} from '../defaultValues/build';\nimport {\n COMPILER_DICTIONARY_KEY_PREFIX,\n COMPILER_ENABLED,\n COMPILER_NO_METADATA,\n COMPILER_SAVE_COMPONENTS,\n} from '../defaultValues/compiler';\nimport {\n CODE_DIR,\n CONTENT_DIR,\n EXCLUDED_PATHS,\n FILE_EXTENSIONS,\n WATCH,\n} from '../defaultValues/content';\nimport {\n CONTENT_AUTO_TRANSFORMATION,\n FILL,\n IMPORT_MODE,\n LOCATION,\n} from '../defaultValues/dictionary';\nimport {\n APPLICATION_URL,\n BACKEND_URL,\n CMS_URL,\n DICTIONARY_PRIORITY_STRATEGY,\n EDITOR_URL,\n IS_ENABLED,\n LIVE_SYNC,\n LIVE_SYNC_PORT,\n PORT,\n} from '../defaultValues/editor';\nimport {\n DEFAULT_LOCALE,\n LOCALES,\n REQUIRED_LOCALES,\n STRICT_MODE,\n} from '../defaultValues/internationalization';\nimport { MODE, PREFIX } from '../defaultValues/log';\nimport { BASE_PATH, ROUTING_MODE, STORAGE } from '../defaultValues/routing';\nimport {\n CACHE_DIR,\n CONFIG_DIR,\n DICTIONARIES_DIR,\n DYNAMIC_DICTIONARIES_DIR,\n FETCH_DICTIONARIES_DIR,\n MAIN_DIR,\n MODULE_AUGMENTATION_DIR,\n REMOTE_DICTIONARIES_DIR,\n TEMP_DIR,\n TYPES_DIR,\n UNMERGED_DICTIONARIES_DIR,\n} from '../defaultValues/system';\nimport { getProjectRequire } from '../utils';\nimport { normalizePath } from '../utils/normalizePath';\n\nlet storedConfiguration: IntlayerConfig;\n\nconst buildInternationalizationFields = (\n customConfiguration?: Partial<InternationalizationConfig>\n): InternationalizationConfig => ({\n /**\n * Locales available in the application\n *\n * Default: ['en']\n *\n */\n locales: customConfiguration?.locales ?? LOCALES,\n\n /**\n * Locales required by TypeScript to ensure strong implementations of internationalized content using typescript.\n *\n * Default: []\n *\n * If empty, all locales are required in `strict` mode.\n *\n * Ensure required locales are also defined in the `locales` field.\n */\n requiredLocales:\n customConfiguration?.requiredLocales ??\n customConfiguration?.locales ??\n REQUIRED_LOCALES,\n\n /**\n * Ensure strong implementations of internationalized content using typescript.\n * - If set to \"strict\", the translation `t` function will require each declared locales to be defined. If one locale is missing, or if a locale is not declared in your config, it will throw an error.\n * - If set to \"inclusive\", the translation `t` function will require each declared locales to be defined. If one locale is missing, it will throw a warning. But will accept if a locale is not declared in your config, but exist.\n * - If set to \"loose\", the translation `t` function will accept any existing locale.\n *\n * Default: \"inclusive\"\n */\n strictMode: customConfiguration?.strictMode ?? STRICT_MODE,\n\n /**\n * Default locale of the application for fallback\n *\n * Default: 'en'\n */\n defaultLocale: customConfiguration?.defaultLocale ?? DEFAULT_LOCALE,\n});\n\nconst buildRoutingFields = (\n customConfiguration?: Partial<RoutingConfig>\n): RoutingConfig => ({\n /**\n * URL routing mode for locale handling\n *\n * Controls how locales are represented in application URLs:\n * - 'prefix-no-default': Prefix all locales except the default locale (default)\n * - en → /dashboard\n * - fr → /fr/dashboard\n *\n * - 'prefix-all': Prefix all locales including the default locale\n * - en → /en/dashboard\n * - fr → /fr/dashboard\n *\n * - 'search-params': Use search parameters for locale handling\n * - en → /dashboard?locale=en\n * - fr → /fr/dashboard?locale=fr\n *\n * - 'no-prefix': No locale prefixing in URLs\n * - en → /dashboard\n * - fr → /dashboard\n *\n * Default: 'prefix-no-default'\n */\n mode: customConfiguration?.mode ?? ROUTING_MODE,\n\n /**\n * Configuration for storing the locale in the client (localStorage or sessionStorage)\n *\n * If false, the locale will not be stored by the middleware.\n * If true, the locale storage will consider all default values. (cookie and header)\n *\n * Default: ['cookie', 'header']\n *\n */\n storage: customConfiguration?.storage ?? STORAGE,\n\n /**\n * Base path of the application URL\n *\n * Default: ''\n *\n * Example:\n * - If the application is hosted at https://example.com/my-app\n * - The base path is '/my-app'\n * - The URL will be https://example.com/my-app/en\n * - If the base path is not set, the URL will be https://example.com/en\n */\n basePath: customConfiguration?.basePath ?? BASE_PATH,\n\n /**\n * Custom URL rewriting rules that override the default routing mode for specific paths.\n * Allows you to define locale-specific paths that differ from the standard routing behavior.\n * Supports dynamic route parameters using `[param]` syntax.\n *\n * Default: undefined\n *\n * Example:\n * ```typescript\n * rewrite: {\n * \"/about\": {\n * en: \"/about\",\n * fr: \"/a-propos\",\n * },\n * \"/product/[slug]\": {\n * en: \"/product/[slug]\",\n * fr: \"/produit/[slug]\",\n * },\n * }\n * ```\n *\n * Note:\n * - The rewrite rules take precedence over the default `mode` behavior.\n * - If a path matches a rewrite rule, the localized path from the rewrite configuration will be used.\n * - Dynamic route parameters are supported using bracket notation (e.g., `[slug]`, `[id]`).\n * - Works with both Next.js and Vite applications.\n */\n rewrite: customConfiguration?.rewrite,\n});\n\nconst buildSystemFields = (\n baseDir?: string,\n customConfiguration?: Partial<SystemConfig>\n): SystemConfig => {\n const projectBaseDir = baseDir ?? process.cwd();\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n const requireFunction = getProjectRequire(projectBaseDir);\n\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [projectBaseDir],\n });\n } catch {\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(projectBaseDir, pathInput);\n }\n\n try {\n const stats = statSync(absolutePath);\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n return absolutePath;\n };\n\n const dictionariesDir = optionalJoinBaseDir(\n customConfiguration?.dictionariesDir ?? DICTIONARIES_DIR\n );\n\n return {\n baseDir: projectBaseDir,\n moduleAugmentationDir: optionalJoinBaseDir(\n customConfiguration?.moduleAugmentationDir ?? MODULE_AUGMENTATION_DIR\n ),\n unmergedDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.unmergedDictionariesDir ?? UNMERGED_DICTIONARIES_DIR\n ),\n remoteDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.remoteDictionariesDir ?? REMOTE_DICTIONARIES_DIR\n ),\n dictionariesDir,\n dynamicDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.dynamicDictionariesDir ?? DYNAMIC_DICTIONARIES_DIR\n ),\n fetchDictionariesDir: optionalJoinBaseDir(\n customConfiguration?.fetchDictionariesDir ?? FETCH_DICTIONARIES_DIR\n ),\n typesDir: optionalJoinBaseDir(customConfiguration?.typesDir ?? TYPES_DIR),\n mainDir: optionalJoinBaseDir(customConfiguration?.mainDir ?? MAIN_DIR),\n configDir: optionalJoinBaseDir(\n customConfiguration?.configDir ?? CONFIG_DIR\n ),\n cacheDir: optionalJoinBaseDir(customConfiguration?.cacheDir ?? CACHE_DIR),\n tempDir: optionalJoinBaseDir(customConfiguration?.tempDir ?? TEMP_DIR),\n outputFilesPatternWithPath: `${normalizePath(dictionariesDir)}/**/*.json`,\n };\n};\n\nconst buildContentFields = (\n systemConfig: SystemConfig,\n customConfiguration?: Partial<ContentConfig>\n): ContentConfig => {\n const fileExtensions = customConfiguration?.fileExtensions ?? FILE_EXTENSIONS;\n\n const optionalJoinBaseDir = (pathInput: string) => {\n let absolutePath: string;\n\n try {\n // Try resolving as a Node module first\n const requireFunction = getProjectRequire(systemConfig.baseDir);\n absolutePath = requireFunction.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch {\n try {\n // Fall back to native require.resolve if the custom require fails\n absolutePath = require.resolve(pathInput, {\n paths: [systemConfig.baseDir],\n });\n } catch {\n // If all resolution fails, fall back to standard path joining\n absolutePath = isAbsolute(pathInput)\n ? pathInput\n : join(systemConfig.baseDir, pathInput);\n }\n }\n\n try {\n // Smart Detection: File vs Directory\n const stats = statSync(absolutePath);\n\n // If it resolved to a file (like package.json \"main\" or index.js),\n // we want the FOLDER containing that file.\n if (stats.isFile()) {\n return dirname(absolutePath);\n }\n } catch {\n // Safety Fallback:\n // If statSync fails but it looks like a file (has an extension), strip it.\n if (/\\.[a-z0-9]+$/i.test(absolutePath)) {\n return dirname(absolutePath);\n }\n }\n\n // Return the calculated path (usually a directory)\n return absolutePath;\n };\n\n const contentDir = (customConfiguration?.contentDir ?? CONTENT_DIR).map(\n optionalJoinBaseDir\n );\n\n const codeDirInput = customConfiguration?.codeDir;\n\n const codeDir = (codeDirInput ?? CODE_DIR).map(optionalJoinBaseDir);\n\n return {\n fileExtensions,\n contentDir,\n codeDir,\n excludedPath: customConfiguration?.excludedPath ?? EXCLUDED_PATHS,\n watch: customConfiguration?.watch ?? WATCH,\n formatCommand: customConfiguration?.formatCommand,\n watchedFilesPattern: fileExtensions.map((ext) => `/**/*${ext}`),\n watchedFilesPatternWithPath: fileExtensions.flatMap((ext) =>\n contentDir.map((dir) => `${normalizePath(dir)}/**/*${ext}`)\n ),\n };\n};\n\nconst buildEditorFields = (\n customConfiguration?: Partial<EditorConfig>\n): EditorConfig => ({\n /**\n * URL of the application. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n applicationURL: customConfiguration?.applicationURL || APPLICATION_URL,\n\n /**\n * URL of the editor server. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n editorURL: customConfiguration?.editorURL || EDITOR_URL,\n\n /**\n * URL of the CMS server. Used to restrict the origin of the editor for security reasons.\n */\n cmsURL: customConfiguration?.cmsURL || CMS_URL,\n\n /**\n * URL of the editor server\n *\n * Default: 'https://back.intlayer.org'\n */\n backendURL: customConfiguration?.backendURL || BACKEND_URL,\n\n /** Port of the editor server\n *\n * Default: 8000\n */\n port: customConfiguration?.port ?? PORT,\n\n /**\n * Indicates if the application interact with the visual editor\n *\n * Default: false;\n *\n * If true, the editor will be able to interact with the application.\n * If false, the editor will not be able to interact with the application.\n * In any case, the editor can only be enabled by the visual editor.\n * Disabling the editor for specific environments is a way to enforce the security.\n *\n * Usage:\n * ```js\n * {\n * // Other configurations\n * editor: {\n * enabled: process.env.NODE_ENV !== 'production',\n * }\n * };\n * ```\n */\n enabled: customConfiguration?.enabled ?? IS_ENABLED,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientId: customConfiguration?.clientId ?? undefined,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientSecret: customConfiguration?.clientSecret ?? undefined,\n\n /**\n * Strategy for prioritizing dictionaries. If a dictionary is both present online and locally, the content will be merge.\n * However, is a field is defined in both dictionary, this setting determines which fields takes the priority over the other.\n *\n * Default: 'local_first'\n *\n * The strategy for prioritizing dictionaries. It can be either 'local_first' or 'distant_first'.\n * - 'local_first': The first dictionary found in the locale is used.\n * - 'distant_first': The first dictionary found in the distant locales is used.\n */\n dictionaryPriorityStrategy:\n customConfiguration?.dictionaryPriorityStrategy ??\n DICTIONARY_PRIORITY_STRATEGY,\n\n /**\n * Indicates if the application should hot reload the locale configurations when a change is detected.\n * For example, when a new dictionary is added or updated, the application will update the content tu display in the page.\n *\n * The hot reload is only available for clients of the `enterprise` plan.\n *\n * Default: false\n */\n liveSync: customConfiguration?.liveSync ?? LIVE_SYNC,\n\n /**\n * Port of the live sync server\n *\n * Default: 4000\n */\n liveSyncPort: customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT,\n\n /**\n * URL of the live sync server in case of remote live sync server\n *\n * Default: `http://localhost:${LIVE_SYNC_PORT}`\n */\n liveSyncURL:\n customConfiguration?.liveSyncURL ??\n `http://localhost:${customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT}`,\n});\n\nconst buildLogFields = (\n customConfiguration?: Partial<LogConfig>,\n logFunctions?: LogFunctions\n): LogConfig => ({\n /**\n * Indicates if the logger is enabled\n *\n * Default: 'prefix-no-default'\n *\n * If 'default', the logger is enabled and can be used.\n * If 'verbose', the logger will be enabled and can be used, but will log more information.\n * If 'disabled', the logger is disabled and cannot be used.\n */\n mode: customConfiguration?.mode ?? MODE,\n\n /**\n * Prefix of the logger\n *\n * Default: '[intlayer]'\n *\n * The prefix of the logger.\n */\n prefix: customConfiguration?.prefix ?? PREFIX,\n\n /**\n * Functions to log\n */\n error: logFunctions?.error,\n log: logFunctions?.log,\n info: logFunctions?.info,\n warn: logFunctions?.warn,\n});\n\nconst buildAiFields = (customConfiguration?: Partial<AiConfig>): AiConfig => ({\n /**\n * AI configuration\n */\n provider: customConfiguration?.provider,\n\n /**\n * API key\n */\n apiKey: customConfiguration?.apiKey,\n\n /**\n * API model\n */\n model: customConfiguration?.model,\n\n /**\n * Temperature\n */\n temperature: customConfiguration?.temperature,\n\n /**\n * Application context\n *\n * Default: undefined\n *\n * The application context.\n *\n * Example: `'My application context'`\n *\n * Note: Can be used to provide additional context about the application to the AI model. You can add more rules (e.g. \"You should not transform urls\").\n */\n applicationContext: customConfiguration?.applicationContext,\n\n /**\n * Base URL for the AI API\n *\n * Default: undefined\n *\n * The base URL for the AI API.\n *\n * Example: `'http://localhost:5000'`\n *\n * Note: Can be used to point to a local, or custom AI API endpoint.\n */\n baseURL: customConfiguration?.baseURL,\n\n /**\n * Data serialization\n *\n * Options:\n * - \"json\": The industry standard. Highly reliable and structured, but consumes more tokens.\n * - \"toon\": An optimized format designed to reduce token consumption (cost-effective). However, it may slightly increase the risk of output inconsistency compared to standard JSON\n *\n * Default: \"json\"\n */\n dataSerialization: customConfiguration?.dataSerialization,\n});\n\nconst buildBuildFields = (\n customConfiguration?: Partial<BuildConfig>\n): BuildConfig => ({\n /**\n * Indicates the mode of the build\n *\n * Default: 'auto'\n *\n * If 'auto', the build will be enabled automatically when the application is built.\n * If 'manual', the build will be set only when the build command is executed.\n *\n * Can be used to disable dictionaries build, for instance when execution on Node.js environment should be avoided.\n */\n mode: customConfiguration?.mode ?? BUILD_MODE,\n\n /**\n * Indicates if the build should be optimized\n *\n * Default: process.env.NODE_ENV === 'production'\n *\n * If true, the build will be optimized.\n * If false, the build will not be optimized.\n *\n * Intlayer will replace all calls of dictionaries to optimize chunking. That way the final bundle will import only the dictionaries that are used.\n * All imports will stay as static import to avoid async processing when loading the dictionaries.\n *\n * Note:\n * - Intlayer will replace all call of `useIntlayer` with the defined mode by the `importMode` option.\n * - Intlayer will replace all call of `getIntlayer` with `getDictionary`.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - In most cases, \"dynamic\" will be used for React applications, \"async\" for Vue.js applications.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n */\n optimize: customConfiguration?.optimize,\n\n /**\n * Indicates the mode of import to use for the dictionaries.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionary`.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n * In that case, Intlayer will replace all calls to `useIntlayer` with `useDictionaryDynamic`.\n * Live mode will use the live sync API to fetch the dictionaries. If the API call fails, the dictionaries will be imported dynamically as \"dynamic\" mode.\n *\n * Default: \"static\"\n *\n * By default, when a dictionary is loaded, it imports content for all locales as it's imported statically.\n *\n * Note:\n * - Dynamic imports rely on Suspense and may slightly impact rendering performance.\n * - If disabled all locales will be loaded at once, even if they are not used.\n * - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.\n * - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.\n * - This option will be ignored if `optimize` is disabled.\n * - This option will not impact the `getIntlayer`, `getDictionary`, `useDictionary`, `useDictionaryAsync` and `useDictionaryDynamic` functions. You can still use them to refine you code on manual optimization.\n * - The \"live\" allows to sync the dictionaries to the live sync server.\n *\n * @deprecated Use `dictionary.importMode` instead.\n */\n importMode: customConfiguration?.importMode,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * Allows to avoid to traverse the code that is not relevant to the optimization.\n * Improve build performance.\n *\n * Default: ['**\\/*.{js,ts,mjs,cjs,jsx,tsx}', '!**\\/node_modules/**']\n *\n * Example: `['src/**\\/*.{ts,tsx}', '../ui-library/**\\/*.{ts,tsx}']`\n *\n * Note:\n * - This option will be ignored if `optimize` is disabled.\n * - Use glob pattern.\n */\n traversePattern: customConfiguration?.traversePattern ?? TRAVERSE_PATTERN,\n\n /**\n * Output format of the dictionaries\n *\n * Can be set on large projects to improve build performance.\n *\n * Default: ['cjs', 'esm']\n *\n * The output format of the dictionaries. It can be either 'cjs' or 'esm'.\n * - 'cjs': The dictionaries are outputted as CommonJS modules.\n * - 'esm': The dictionaries are outputted as ES modules.\n */\n outputFormat: customConfiguration?.outputFormat ?? OUTPUT_FORMAT,\n\n /**\n * Cache\n */\n cache: customConfiguration?.cache ?? CACHE,\n\n /**\n * Require function\n */\n require: customConfiguration?.require,\n\n /**\n * Indicates if the build should check TypeScript types\n *\n * Default: false\n *\n * If true, the build will check TypeScript types and log errors.\n * Note: This can slow down the build.\n */\n checkTypes: customConfiguration?.checkTypes ?? TYPE_CHECKING,\n});\n\nconst buildCompilerFields = (\n customConfiguration?: Partial<CompilerConfig>\n): CompilerConfig => ({\n /**\n * Indicates if the compiler should be enabled\n */\n enabled: customConfiguration?.enabled ?? COMPILER_ENABLED,\n\n /**\n * Prefix for the extracted dictionary keys\n */\n dictionaryKeyPrefix:\n customConfiguration?.dictionaryKeyPrefix ?? COMPILER_DICTIONARY_KEY_PREFIX,\n\n /**\n * Pattern to traverse the code to optimize.\n *\n * @deprecated use build.traversePattern instead\n */\n transformPattern: customConfiguration?.transformPattern,\n\n /**\n * Pattern to exclude from the optimization.\n *\n * @deprecated use build.traversePattern instead\n */\n excludePattern: customConfiguration?.excludePattern,\n\n /**\n * Defines the output files path. Replaces `outputDir`.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - Including the `{{locale}}` variable in the path will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * output: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // output: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * output: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // output: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n output: customConfiguration?.output,\n\n /**\n * Indicates if the metadata should be saved in the file.\n *\n * If true, the compiler will not save the metadata of the dictionaries.\n *\n * If true:\n *\n * ```json\n * {\n * \"key\": \"value\"\n * }\n * ```\n *\n * If false:\n *\n * ```json\n * {\n * \"key\": \"value\",\n * \"content\": {\n * \"key\": \"value\"\n * }\n * }\n * ```\n *\n * Default: false\n *\n * Note: Useful if used with loadJSON plugin\n */\n noMetadata: customConfiguration?.noMetadata ?? COMPILER_NO_METADATA,\n\n /**\n * Indicates if the components should be saved after being transformed.\n */\n saveComponents:\n customConfiguration?.saveComponents ?? COMPILER_SAVE_COMPONENTS,\n});\n\nconst buildDictionaryFields = (\n customConfiguration?: Partial<DictionaryConfig>\n): DictionaryConfig => {\n const contentAutoTransformation =\n customConfiguration?.contentAutoTransformation ??\n CONTENT_AUTO_TRANSFORMATION;\n\n return {\n /**\n * Indicate how the dictionary should be filled using AI.\n *\n * Default: `true`\n *\n * - If `true`, will consider the `compiler.output` field.\n * - If `false`, will skip the fill process.\n *\n * - `./` paths are resolved relative to the component directory.\n * - `/` paths are resolved relative to the project root (`baseDir`).\n *\n * - If includes `{{locale}}` variable in the path, will trigger the generation of separate dictionaries per locale.\n *\n * Example:\n * ```ts\n * {\n * // Create Multilingual .content.ts files close to the component\n * fill: ({ fileName, extension }) => `./${fileName}${extension}`,\n *\n * // fill: './{{fileName}}{{extension}}', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create centralize per-locale JSON at the root of the project\n * fill: ({ key, locale }) => `/locales/${locale}/${key}.content.json`,\n *\n * // fill: '/locales/{{locale}}/{{key}}.content.json', // Equivalent using template string\n * }\n * ```\n *\n * ```ts\n * {\n * // Create custom output based on the locale\n * fill: {\n * en: ({ key }) => `/locales/en/${key}.content.json`,\n * fr: '/locales/fr/{{key}}.content.json',\n * es: false,\n * de: true,\n * },\n * }\n * ```\n *\n *\n * Variable list:\n * - `fileName`: The name of the file.\n * - `key`: The key of the content.\n * - `locale`: The locale of the content.\n * - `extension`: The extension of the file.\n * - `componentFileName`: The name of the component file.\n * - `componentExtension`: The extension of the component file.\n * - `format`: The format of the dictionary.\n * - `componentFormat`: The format of the component dictionary.\n * - `componentDirPath`: The directory path of the component.\n */\n fill: customConfiguration?.fill ?? FILL,\n\n /**\n * Indicates if the content of the dictionary should be automatically transformed.\n *\n * Default: false\n */\n contentAutoTransformation:\n typeof contentAutoTransformation === 'object'\n ? {\n markdown: contentAutoTransformation.markdown ?? false,\n html: contentAutoTransformation.html ?? false,\n insertion: contentAutoTransformation.insertion ?? false,\n }\n : contentAutoTransformation,\n\n /**\n * The location of the dictionary.\n *\n * Default: 'local'\n */\n location: customConfiguration?.location ?? LOCATION,\n\n /**\n * Transform the dictionary in a per-locale dictionary.\n * Each field declared in a per-locale dictionary will be transformed in a translation node.\n * If missing, the dictionary will be treated as a multilingual dictionary.\n */\n locale: customConfiguration?.locale,\n\n /**\n * The title of the dictionary.\n */\n title: customConfiguration?.title,\n\n /**\n * The description of the dictionary.\n */\n description: customConfiguration?.description,\n\n /**\n * Tags to categorize the dictionaries.\n */\n tags: customConfiguration?.tags,\n\n /**\n * The priority of the dictionary.\n */\n priority: customConfiguration?.priority,\n\n /**\n * Indicates the mode of import to use for the dictionary.\n *\n * Available modes:\n * - \"static\": The dictionaries are imported statically.\n * - \"dynamic\": The dictionaries are imported dynamically in a synchronous component using the suspense API.\n * - \"live\": The dictionaries are imported dynamically using the live sync API.\n *\n * Default: 'static'\n */\n importMode: customConfiguration?.importMode ?? IMPORT_MODE,\n };\n};\n\n/**\n * Build the configuration fields by merging the default values with the custom configuration\n */\nexport const buildConfigurationFields = (\n customConfiguration?: CustomIntlayerConfig,\n baseDir?: string,\n logFunctions?: LogFunctions\n): IntlayerConfig => {\n const internationalizationConfig = buildInternationalizationFields(\n customConfiguration?.internationalization\n );\n\n const routingConfig = buildRoutingFields(customConfiguration?.routing);\n\n const systemConfig = buildSystemFields(baseDir, customConfiguration?.system);\n\n const contentConfig = buildContentFields(\n systemConfig,\n customConfiguration?.content\n );\n\n const editorConfig = buildEditorFields(customConfiguration?.editor);\n\n const logConfig = buildLogFields(customConfiguration?.log, logFunctions);\n\n const aiConfig = buildAiFields(customConfiguration?.ai);\n\n const buildConfig = buildBuildFields(customConfiguration?.build);\n\n const compilerConfig = buildCompilerFields(customConfiguration?.compiler);\n\n const dictionaryConfig = buildDictionaryFields(\n customConfiguration?.dictionary\n );\n\n storedConfiguration = {\n internationalization: internationalizationConfig,\n routing: routingConfig,\n content: contentConfig,\n system: systemConfig,\n editor: editorConfig,\n log: logConfig,\n ai: aiConfig,\n build: buildConfig,\n compiler: compilerConfig,\n dictionary: dictionaryConfig,\n plugins: customConfiguration?.plugins,\n schemas: customConfiguration?.schemas,\n metadata: {\n name: 'Intlayer',\n version: packageJson.version,\n doc: `https://intlayer.org/docs`,\n },\n } as IntlayerConfig;\n\n return storedConfiguration;\n};\n"],"mappings":"u4BA+EA,IAAI,EAEJ,MAAM,EACJ,IACgC,CAOhC,QAAS,GAAqB,SAAW,EAWzC,gBACE,GAAqB,iBACrB,GAAqB,SACrB,EAUF,WAAY,GAAqB,YAAA,YAOjC,cAAe,GAAqB,eAAiB,EACtD,EAEK,EACJ,IACmB,CAuBnB,KAAM,GAAqB,MAAA,oBAW3B,QAAS,GAAqB,SAAW,EAazC,SAAU,GAAqB,UAAA,GA6B/B,QAAS,GAAqB,QAC/B,EAEK,GACJ,EACA,IACiB,CACjB,IAAM,EAAiB,GAAW,QAAQ,KAAK,CAEzC,EAAuB,GAAsB,CACjD,IAAI,EAEJ,GAAI,CAGF,EAFwB,EAAkB,EAAe,CAE1B,QAAQ,EAAW,CAChD,MAAO,CAAC,EAAe,CACxB,CAAC,MACI,CACN,EAAe,EAAW,EAAU,CAChC,EACA,EAAK,EAAgB,EAAU,CAGrC,GAAI,CAEF,GADc,EAAS,EAAa,CAC1B,QAAQ,CAChB,OAAO,EAAQ,EAAa,MAExB,CACN,GAAI,gBAAgB,KAAK,EAAa,CACpC,OAAO,EAAQ,EAAa,CAIhC,OAAO,GAGH,EAAkB,EACtB,GAAqB,iBAAA,uBACtB,CAED,MAAO,CACL,QAAS,EACT,sBAAuB,EACrB,GAAqB,uBAAA,kBACtB,CACD,wBAAyB,EACvB,GA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,MAAA,GAO3B,0BACE,OAAO,GAA8B,SACjC,CACE,SAAU,EAA0B,UAAY,GAChD,KAAM,EAA0B,MAAQ,GACxC,UAAW,EAA0B,WAAa,GACnD,CACD,EAON,SAAU,GAAqB,UAAA,QAO/B,OAAQ,GAAqB,OAK7B,MAAO,GAAqB,MAK5B,YAAa,GAAqB,YAKlC,KAAM,GAAqB,KAK3B,SAAU,GAAqB,SAY/B,WAAY,GAAqB,YAAA,SAClC,EAMU,GACX,EACA,EACA,IACmB,CACnB,IAAM,EAA6B,EACjC,GAAqB,qBACtB,CAEK,EAAgB,EAAmB,GAAqB,QAAQ,CAEhE,EAAe,EAAkB,EAAS,GAAqB,OAAO,CAyC5E,MApBA,GAAsB,CACpB,qBAAsB,EACtB,QAAS,EACT,QAtBoB,EACpB,EACA,GAAqB,QACtB,CAoBC,OAAQ,EACR,OAnBmB,EAAkB,GAAqB,OAAO,CAoBjE,IAlBgB,EAAe,GAAqB,IAAK,EAAa,CAmBtE,GAjBe,EAAc,GAAqB,GAAG,CAkBrD,MAhBkB,EAAiB,GAAqB,MAAM,CAiB9D,SAfqB,EAAoB,GAAqB,SAAS,CAgBvE,WAduB,EACvB,GAAqB,WACtB,CAaC,QAAS,GAAqB,QAC9B,QAAS,GAAqB,QAC9B,SAAU,CACR,KAAM,WACN,QAASA,EAAY,QACrB,IAAK,4BACN,CACF,CAEM"}
@@ -1 +1 @@
1
- {"version":3,"file":"cacheDisk.mjs","names":["configPackageJson"],"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\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":"uZA2CA,MAAM,EAA0D,CAC9D,SAAU,GACX,CAEK,EAAY,KAAO,IAAgB,CACvC,MAAM,EAAM,EAAK,CAAE,UAAW,GAAM,CAAC,EAGjC,EAAkB,MACtB,EACA,EACA,IACG,CACH,GAAI,EACF,GAAI,CACF,MAAM,EAAU,EAAQ,MAClB,EAGV,IAAM,EAAe,GAAG,EAAS,EAAK,CAAC,OAAO,QAAQ,IAAI,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,GAC1F,EAAM,EACR,EAAK,EAAS,EAAa,CAC3B,GAAG,EAAK,OAAO,QAAQ,IAAI,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,GACrE,GAAI,CACF,MAAM,EAAU,EAAK,EAAK,CAC1B,MAAM,EAAO,EAAK,EAAK,OAChB,EAAO,CACd,GAAI,CACF,MAAM,EAAG,EAAK,CAAE,MAAO,GAAM,CAAC,MACxB,EAGR,MAAM,IAIJ,GAAwB,EAAa,IACzC,IAAU,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AG7D,GAFI,CAAC,GAED,OAAO,GAAU,UAAY,EAAQ,GAC3B,KAAK,KAAK,CAAG,EAAU,QACzB,EAAO,MAAO,GAG1B,IAAI,EAAM,MAAM,EAAS,EAAS,CAC5B,EAAO,EAAI,GACjB,EAAM,EAAI,SAAS,EAAE,CAIrB,IAAM,EAFe,EADL,IAAS,EAAO,EAAW,EAAI,CAAG,EACT,CAUzC,GANI,GACF,OAAO,GAAa,UACpB,OAAO,EAAS,SAAY,UAC5B,OAAO,EAAS,WAAc,UAC9B,OAAO,OAAO,EAAU,OAAO,CAEjB,CACd,IAAM,EAAQ,EAOd,MAJA,EAFI,EAAM,UAAYA,EAAkB,SAEpC,OAAO,GAAc,UAAY,EAAY,GACnC,KAAK,KAAK,CAAG,EAAM,UACrB,GASd,MAJA,EAAI,OAAO,GAAc,UAAY,EAAY,GACnC,KAAK,KAAK,CAAG,EAAU,QACzB,QAGN,CACN,MAAO,KAIX,KAEA,WACD"}
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\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":"uZA2CA,MAAM,EAA0D,CAC9D,SAAU,GACX,CAEK,EAAY,KAAO,IAAgB,CACvC,MAAM,EAAM,EAAK,CAAE,UAAW,GAAM,CAAC,EAGjC,EAAkB,MACtB,EACA,EACA,IACG,CACH,GAAI,EACF,GAAI,CACF,MAAM,EAAU,EAAQ,MAClB,EAGV,IAAM,EAAe,GAAG,EAAS,EAAK,CAAC,OAAO,QAAQ,IAAI,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,GAC1F,EAAM,EACR,EAAK,EAAS,EAAa,CAC3B,GAAG,EAAK,OAAO,QAAQ,IAAI,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,GACrE,GAAI,CACF,MAAM,EAAU,EAAK,EAAK,CAC1B,MAAM,EAAO,EAAK,EAAK,OAChB,EAAO,CACd,GAAI,CACF,MAAM,EAAG,EAAK,CAAE,MAAO,GAAM,CAAC,MACxB,EAGR,MAAM,IAIJ,GAAwB,EAAa,IACzC,IAAU,IAAS,IAAU,IAAS,EAAI,WAAa,KAGnD,GAAa,EAAkB,EAAY,IAC/C,EAAK,EAAU,EAAK,EAAK,EAAI,EAAG,CAAG,EAAG,CAIlC,EAAW,IAAI,IAER,GACX,EACA,EACA,IACG,CACH,GAAM,CAAE,WAAU,WAAY,EAAe,OACvC,EAAoB,EAAe,MAAM,OAAS,GAClD,EACJ,GAAS,aAAe,IAChB,GAAS,aAAe,QAAe,EAE3C,CAAE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,EAAS,SAAY,UAC5B,OAAO,EAAS,WAAc,UAC9B,OAAO,OAAO,EAAU,OAAO,CAEjB,CACd,IAAM,EAAQ,EAOd,MAJA,EAFI,EAAM,UAAY,EAAkB,SAEpC,OAAO,GAAc,UAAY,EAAY,GACnC,KAAK,KAAK,CAAG,EAAM,UACrB,GASd,MAJA,EAAI,OAAO,GAAc,UAAY,EAAY,GACnC,KAAK,KAAK,CAAG,EAAU,QACzB,QAGN,CACN,MAAO,KAIX,KAEA,WACD"}
@@ -21,8 +21,8 @@ declare const cookiesAttributesSchema: z.ZodObject<{
21
21
  httpOnly: z.ZodOptional<z.ZodBoolean>;
22
22
  sameSite: z.ZodOptional<z.ZodEnum<{
23
23
  strict: "strict";
24
- lax: "lax";
25
24
  none: "none";
25
+ lax: "lax";
26
26
  }>>;
27
27
  expires: z.ZodOptional<z.ZodUnion<readonly [z.ZodDate, z.ZodNumber]>>;
28
28
  }, z.core.$strip>;
@@ -48,8 +48,8 @@ declare const storageSchema: z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodEnum
48
48
  httpOnly: z.ZodOptional<z.ZodBoolean>;
49
49
  sameSite: z.ZodOptional<z.ZodEnum<{
50
50
  strict: "strict";
51
- lax: "lax";
52
51
  none: "none";
52
+ lax: "lax";
53
53
  }>>;
54
54
  expires: z.ZodOptional<z.ZodUnion<readonly [z.ZodDate, z.ZodNumber]>>;
55
55
  }, z.core.$strip>, z.ZodObject<{
@@ -73,8 +73,8 @@ declare const storageSchema: z.ZodUnion<readonly [z.ZodLiteral<false>, z.ZodEnum
73
73
  httpOnly: z.ZodOptional<z.ZodBoolean>;
74
74
  sameSite: z.ZodOptional<z.ZodEnum<{
75
75
  strict: "strict";
76
- lax: "lax";
77
76
  none: "none";
77
+ lax: "lax";
78
78
  }>>;
79
79
  expires: z.ZodOptional<z.ZodUnion<readonly [z.ZodDate, z.ZodNumber]>>;
80
80
  }, z.core.$strip>, z.ZodObject<{
@@ -156,8 +156,8 @@ declare const routingSchema: z.ZodObject<{
156
156
  httpOnly: z.ZodOptional<z.ZodBoolean>;
157
157
  sameSite: z.ZodOptional<z.ZodEnum<{
158
158
  strict: "strict";
159
- lax: "lax";
160
159
  none: "none";
160
+ lax: "lax";
161
161
  }>>;
162
162
  expires: z.ZodOptional<z.ZodUnion<readonly [z.ZodDate, z.ZodNumber]>>;
163
163
  }, z.core.$strip>, z.ZodObject<{
@@ -181,8 +181,8 @@ declare const routingSchema: z.ZodObject<{
181
181
  httpOnly: z.ZodOptional<z.ZodBoolean>;
182
182
  sameSite: z.ZodOptional<z.ZodEnum<{
183
183
  strict: "strict";
184
- lax: "lax";
185
184
  none: "none";
185
+ lax: "lax";
186
186
  }>>;
187
187
  expires: z.ZodOptional<z.ZodUnion<readonly [z.ZodDate, z.ZodNumber]>>;
188
188
  }, z.core.$strip>, z.ZodObject<{
@@ -239,8 +239,8 @@ declare const editorSchema: z.ZodObject<{
239
239
  }, z.core.$strip>;
240
240
  declare const logSchema: z.ZodObject<{
241
241
  mode: z.ZodOptional<z.ZodEnum<{
242
- default: "default";
243
242
  verbose: "verbose";
243
+ default: "default";
244
244
  disabled: "disabled";
245
245
  }>>;
246
246
  prefix: z.ZodOptional<z.ZodString>;
@@ -353,8 +353,8 @@ declare const intlayerConfigSchema: z.ZodObject<{
353
353
  httpOnly: z.ZodOptional<z.ZodBoolean>;
354
354
  sameSite: z.ZodOptional<z.ZodEnum<{
355
355
  strict: "strict";
356
- lax: "lax";
357
356
  none: "none";
357
+ lax: "lax";
358
358
  }>>;
359
359
  expires: z.ZodOptional<z.ZodUnion<readonly [z.ZodDate, z.ZodNumber]>>;
360
360
  }, z.core.$strip>, z.ZodObject<{
@@ -378,8 +378,8 @@ declare const intlayerConfigSchema: z.ZodObject<{
378
378
  httpOnly: z.ZodOptional<z.ZodBoolean>;
379
379
  sameSite: z.ZodOptional<z.ZodEnum<{
380
380
  strict: "strict";
381
- lax: "lax";
382
381
  none: "none";
382
+ lax: "lax";
383
383
  }>>;
384
384
  expires: z.ZodOptional<z.ZodUnion<readonly [z.ZodDate, z.ZodNumber]>>;
385
385
  }, z.core.$strip>, z.ZodObject<{
@@ -436,8 +436,8 @@ declare const intlayerConfigSchema: z.ZodObject<{
436
436
  }, z.core.$strip>>;
437
437
  log: z.ZodOptional<z.ZodObject<{
438
438
  mode: z.ZodOptional<z.ZodEnum<{
439
- default: "default";
440
439
  verbose: "verbose";
440
+ default: "default";
441
441
  disabled: "disabled";
442
442
  }>>;
443
443
  prefix: z.ZodOptional<z.ZodString>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/config",
3
- "version": "8.3.1",
3
+ "version": "8.3.3",
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": [
@@ -127,22 +127,22 @@
127
127
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
128
128
  },
129
129
  "dependencies": {
130
- "@intlayer/types": "8.3.1",
130
+ "@intlayer/types": "8.3.3",
131
131
  "defu": "6.1.4",
132
132
  "dotenv": "17.3.1",
133
- "esbuild": "0.27.2",
133
+ "esbuild": "0.27.4",
134
134
  "json5": "2.2.3",
135
135
  "zod": "4.3.6"
136
136
  },
137
137
  "devDependencies": {
138
- "@types/node": "25.4.0",
138
+ "@types/node": "25.5.0",
139
139
  "@utils/ts-config": "1.0.4",
140
140
  "@utils/ts-config-types": "1.0.4",
141
141
  "@utils/tsdown-config": "1.0.4",
142
142
  "rimraf": "6.1.3",
143
143
  "tsdown": "0.21.2",
144
144
  "typescript": "5.9.3",
145
- "vitest": "4.0.18"
145
+ "vitest": "4.1.0"
146
146
  },
147
147
  "peerDependencies": {
148
148
  "react": ">=16.0.0"