@intlayer/config
Version:
Retrieve Intlayer configurations and manage environment variables for both server-side and client-side environments.
629 lines • 21.4 kB
JavaScript
import { join } from "path";
import {
ACTIVATE_DYNAMIC_IMPORT,
OPTIMIZE,
TRAVERSE_PATTERN
} from "../defaultValues/build.mjs";
import {
CONFIG_DIR,
CONTENT_DIR,
DICTIONARIES_DIR,
DICTIONARY_OUTPUT,
DYNAMIC_DICTIONARIES_DIR,
EXCLUDED_PATHS,
FILE_EXTENSIONS,
I18NEXT_DICTIONARIES_DIR,
MAIN_DIR,
MODULE_AUGMENTATION_DIR,
REACT_INTL_MESSAGES_DIR,
TYPES_DIR,
UNMERGED_DICTIONARIES_DIR,
WATCH
} from "../defaultValues/content.mjs";
import {
APPLICATION_URL,
BACKEND_URL,
CMS_URL,
DICTIONARY_PRIORITY_STRATEGY,
EDITOR_URL,
HOT_RELOAD,
IS_ENABLED,
PORT
} from "../defaultValues/editor.mjs";
import {
DEFAULT_LOCALE,
LOCALES,
REQUIRED_LOCALES,
STRICT_MODE
} from "../defaultValues/internationalization.mjs";
import { MODE, PREFIX } from "../defaultValues/log.mjs";
import {
BASE_PATH,
COOKIE_NAME,
HEADER_NAME,
NO_PREFIX,
PREFIX_DEFAULT,
SERVER_SET_COOKIE
} from "../defaultValues/middleware.mjs";
import { normalizePath } from "../utils/normalizePath.mjs";
let storedConfiguration;
const buildInternationalizationFields = (customConfiguration) => ({
/**
* Locales available in the application
*
* Default: ['en']
*
*/
locales: customConfiguration?.locales ?? LOCALES,
/**
* Locales required by TypeScript to ensure strong implementations of internationalized content using typescript.
*
* Default: []
*
* If empty, all locales are required in `strict` mode.
*
* Ensure required locales are also defined in the `locales` field.
*/
requiredLocales: customConfiguration?.requiredLocales ?? REQUIRED_LOCALES,
/**
* Ensure strong implementations of internationalized content using typescript.
* - 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.
* - 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.
* - If set to "loose", the translation `t` function will accept any existing locale.
*
* Default: "inclusive"
*/
strictMode: customConfiguration?.strictMode ?? STRICT_MODE,
/**
* Default locale of the application for fallback
*
* Default: 'en'
*/
defaultLocale: customConfiguration?.defaultLocale ?? DEFAULT_LOCALE
});
const buildMiddlewareFields = (customConfiguration) => ({
/**
* Header name to get the locale
*
* Default: 'x-intlayer-locale'
*/
headerName: customConfiguration?.headerName ?? HEADER_NAME,
/**
* Cookie name to get the locale
*
* Default: 'intlayer-locale'
*/
cookieName: customConfiguration?.cookieName ?? COOKIE_NAME,
/**
* Prefix default prefix the default locale to the path as other locales.
*
* Example with prefixDefault = true and defaultLocale = 'en':
* path = /en/dashboard or /fr/dashboard
*
* Example with prefixDefault = false and defaultLocale = 'en':
* path = /dashboard or /fr/dashboard
*
*
* Default: false
*/
prefixDefault: customConfiguration?.prefixDefault ?? PREFIX_DEFAULT,
/**
* Base path of the application URL
*
* Default: ''
*
* Example:
* - If the application is hosted at https://example.com/my-app
* - The base path is '/my-app'
* - The URL will be https://example.com/my-app/en
* - If the base path is not set, the URL will be https://example.com/en
*/
basePath: customConfiguration?.basePath ?? BASE_PATH,
/**
* Rule to set the cookie on the server
* - 'always': Set the cookie on every request
* - 'never': Never set the cookie
*/
serverSetCookie: customConfiguration?.serverSetCookie ?? SERVER_SET_COOKIE,
/**
* No prefix in the URL
* - true: No prefix in the URL
* - false: Prefix in the URL
*
* Example:
* - If the application is hosted at https://example.com/my-app
* - The base path is '/my-app'
* - The URL will be https://example.com/my-app/en
* - If the base path is not set, the URL will be https://example.com/en
* - If no prefix is set, the URL will be https://example.com/en
* - If the no prefix is set to true, the URL will be https://example.com
*
* Default: false
*/
noPrefix: customConfiguration?.noPrefix ?? NO_PREFIX
});
const buildContentFields = (customConfiguration, baseDir) => {
const notDerivedContentConfig = {
/**
* File extensions of content to look for to build the dictionaries
*
* - Default: ['.content.ts', '.content.js', '.content.cjs', '.content.mjs', '.content.json', '.content.tsx', '.content.jsx']
*
* - Example: ['.data.ts', '.data.js', '.data.json']
*
* Note:
* - Can exclude unused file extensions to improve performance
* - Avoid using common file extensions like '.ts', '.js', '.json' to avoid conflicts
*/
fileExtensions: customConfiguration?.fileExtensions ?? FILE_EXTENSIONS,
/**
* Absolute path of the directory of the project
* - Default: process.cwd()
* - Example: '
*
* Will be used to resolve all intlayer directories
*
* Note:
* - The base directory should be the root of the project
* - Can be changed to a custom directory to externalize either the content used in the project, or the intlayer application from the project
*/
baseDir: customConfiguration?.baseDir ?? baseDir ?? process.cwd(),
/**
* Should exclude some directories from the content search
*
* Default: ['node_modules']
*
* Not used yet
* @TODO Implement the exclusion or remove it
*/
excludedPath: customConfiguration?.excludedPath ?? EXCLUDED_PATHS,
/**
* Indicates if Intlayer should watch for changes in the content declaration files in the app to rebuild the related dictionaries.
*
* Default: process.env.NODE_ENV === 'development'
*/
watch: customConfiguration?.watch ?? WATCH
};
const baseDirDerivedConfiguration = {
/**
* Directory where the content is stored
*
* Relative to the base directory of the project
*
* Default: ./src
*
* Example: 'src'
*
* Note:
* - Can be changed to a custom directory to externalize the content used in the project
* - If the content is not at the base directory level, update the contentDirName field instead
*/
contentDir: (customConfiguration?.contentDir ?? CONTENT_DIR).map(
(contentDir) => join(notDerivedContentConfig.baseDir, contentDir)
),
/**
* Directory where the result will be stored
*
* Relative to the base directory of the project
*
* Default: .intlayer/dictionary
*
* Example: '.intlayer'
*
* Note:
* - Can be changed to a custom directory to externalize the intlayer application from the project
* - If the result is not at the base directory level, update the dictionariesDirName field instead
*/
dictionariesDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.dictionariesDir ?? DICTIONARIES_DIR
),
/**
* Directory where the module augmentation will be stored
*
* Module augmentation allow better IDE suggestions and type checking
*
* Relative to the base directory of the project
*
* Default: .intlayer/types
*
* Example: 'types'
*
* Note:
* - If this path changed, be sure to include it from the tsconfig.json file
* - If the module augmentation is not at the base directory level, update the moduleAugmentationDirName field instead
*
*/
moduleAugmentationDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.moduleAugmentationDir ?? MODULE_AUGMENTATION_DIR
),
/**
* Output format of the dictionary
*
* Default: ['intlayer']
*
* Note:
* - 'i18next' is not yet ensure a 1:1 mapping with the i18next library.
* - Removing 'intlayer' will break the compatibility with react-intlayer or next-intlayer
*/
dictionaryOutput: customConfiguration?.dictionaryOutput ?? DICTIONARY_OUTPUT
};
const dictionariesDirDerivedConfiguration = {
/**
* Directory where the unmerged dictionaries will be stored
*
* Relative to the result directory
*
* Default: '.intlayer/unmerged_dictionary'
*
*/
unmergedDictionariesDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.unmergedDictionariesDir ?? UNMERGED_DICTIONARIES_DIR
),
/**
* Directory where the final dictionaries will be stored
*
* Relative to the result directory
*
* Default: .intlayer/dictionary
*
* Example: '.intlayer/dictionary'
*
* Note:
* - If the types are not at the result directory level, update the dictionariesDirName field instead
* - The dictionaries are stored in JSON format
* - The dictionaries are used to translate the content
* - The dictionaries are built from the content files
*/
dictionariesDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.dictionariesDir ?? DICTIONARIES_DIR
),
/**
* Directory where the dynamic dictionaries will be stored
*
* Relative to the result directory
*
* Default: .intlayer/dynamic_dictionary
*/
dynamicDictionariesDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.dynamicDictionariesDir ?? DYNAMIC_DICTIONARIES_DIR
),
/**
* Directory where the 18n dictionaries will be stored
*
* Relative to the result directory
*
* Default: i18next_resources
*
* Example: '.intlayer/dictionary/i18n'
*
* Note:
* - If the types are not at the result directory level, update the i18nextResourcesDirName field instead
*/
i18nextResourcesDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.i18nextResourcesDir ?? I18NEXT_DICTIONARIES_DIR
),
/**
* Directory where the dictionaries will be stored
*
* Relative to the result directory
*
* Default: intl_messages
*
* Example: '.intlayer/react-intl_dictionary'
*
* Note:
* - If the types are not at the result directory level, update the dictionariesDirName field instead
*/
reactIntlMessagesDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.reactIntlMessagesDir ?? REACT_INTL_MESSAGES_DIR
),
/**
* Directory where the dictionaries types will be stored
*
* Relative to the result directory
*
* Default: .intlayer/types
*
* Example: 'types'
*
* Note:
* - If the types are not at the result directory level, update the typesDirName field instead
*/
typesDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.typesDir ?? TYPES_DIR
),
/**
* Directory where the main files will be stored
*
* Relative to the result directory
*
* Default: .intlayer/main
*
* Example: '.intlayer/main'
*
* Note:
*
* - If the main files are not at the result directory level, update the mainDirName field instead
*/
mainDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.mainDir ?? MAIN_DIR
),
/**
* Directory where the configuration files are stored
*
* Relative to the result directory
*
* Default: .intlayer/config
*
* Example: '.intlayer/config'
*
* Note:
*
* - If the configuration files are not at the result directory level, update the configDirName field instead
*/
configDir: join(
notDerivedContentConfig.baseDir,
customConfiguration?.configDir ?? CONFIG_DIR
)
};
const patternsConfiguration = {
/**
* Pattern of files to watch
*
* Default: ['/**\/*.content.ts', '/**\/*.content.js', '/**\/*.content.json', '/**\/*.content.cjs', '/**\/*.content.mjs', '/**\/*.content.tsx', '/**\/*.content.jsx']
*/
watchedFilesPattern: notDerivedContentConfig.fileExtensions.map(
(ext) => `/**/*${ext}`
),
/**
* Pattern of files to watch including the relative path
*
* Default: ['src/**\/*.content.ts', 'src/**\/*.content.js', 'src/**\/*.content.json', 'src/**\/*.content.cjs', 'src/**\/*.content.mjs', 'src/**\/*.content.tsx', 'src/**\/*.content.jsx']
*/
watchedFilesPatternWithPath: notDerivedContentConfig.fileExtensions.flatMap(
(ext) => baseDirDerivedConfiguration.contentDir.map(
(contentDir) => `${normalizePath(contentDir)}/**/*${ext}`
)
),
/**
* Pattern of dictionary to interpret
*
* Default: '.intlayer/dictionary/**\/*.json'
*/
outputFilesPatternWithPath: `${normalizePath(
dictionariesDirDerivedConfiguration.dictionariesDir
)}/**/*.json`
};
return {
...notDerivedContentConfig,
...baseDirDerivedConfiguration,
...dictionariesDirDerivedConfiguration,
...patternsConfiguration
};
};
const buildEditorFields = (customConfiguration) => ({
/**
* URL of the application. Used to restrict the origin of the editor for security reasons.
*
* > '*' means that the editor is accessible from any origin
*
* Default: '*'
*/
applicationURL: customConfiguration?.applicationURL ?? APPLICATION_URL,
/**
* URL of the editor server. Used to restrict the origin of the editor for security reasons.
*
* > '*' means that the editor is accessible from any origin
*
* Default: '*'
*/
editorURL: customConfiguration?.editorURL ?? EDITOR_URL,
/**
* URL of the CMS server. Used to restrict the origin of the editor for security reasons.
*/
cmsURL: customConfiguration?.cmsURL ?? CMS_URL,
/**
* URL of the editor server
*
* Default: 'https://back.intlayer.org'
*/
backendURL: customConfiguration?.backendURL ?? BACKEND_URL,
/** Port of the editor server
*
* Default: 8000
*/
port: customConfiguration?.port ?? PORT,
/**
* Indicates if the application interact with the visual editor
*
* Default: true;
*
* If true, the editor will be able to interact with the application.
* If false, the editor will not be able to interact with the application.
* In any case, the editor can only be enabled by the visual editor.
* Disabling the editor for specific environments is a way to enforce the security.
*
* Usage:
* ```js
* {
* // Other configurations
* editor: {
* enabled: process.env.NODE_ENV !== 'production',
* }
* };
* ```
*/
enabled: customConfiguration?.enabled ?? IS_ENABLED,
/**
* clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.
* An access token is use to authenticate the user related to the project.
* To get an access token, go to https://intlayer.org/dashboard/project and create an account.
*
* Default: undefined
*
* > 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.
*/
clientId: customConfiguration?.clientId ?? void 0,
/**
* clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.
* An access token is use to authenticate the user related to the project.
* To get an access token, go to https://intlayer.org/dashboard/project and create an account.
*
* Default: undefined
*
* > 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.
*/
clientSecret: customConfiguration?.clientSecret ?? void 0,
/**
* Strategy for prioritizing dictionaries. If a dictionary is both present online and locally, the content will be merge.
* However, is a field is defined in both dictionary, this setting determines which fields takes the priority over the other.
*
* Default: 'local_first'
*
* The strategy for prioritizing dictionaries. It can be either 'local_first' or 'distant_first'.
* - 'local_first': The first dictionary found in the locale is used.
* - 'distant_first': The first dictionary found in the distant locales is used.
*/
dictionaryPriorityStrategy: customConfiguration?.dictionaryPriorityStrategy ?? DICTIONARY_PRIORITY_STRATEGY,
/**
* Indicates if the application should hot reload the locale configurations when a change is detected.
* For example, when a new dictionary is added or updated, the application will update the content tu display in the page.
*
* The hot reload is only available for clients of the `enterprise` plan.
*
* Default: false
*/
hotReload: customConfiguration?.hotReload ?? HOT_RELOAD
});
const buildLogFields = (customConfiguration) => ({
/**
* Indicates if the logger is enabled
*
* Default: 'default'
*
* If 'default', the logger is enabled and can be used.
* If 'verbose', the logger will be enabled and can be used, but will log more information.
* If 'disabled', the logger is disabled and cannot be used.
*/
mode: customConfiguration?.mode ?? MODE,
/**
* Prefix of the logger
*
* Default: '[intlayer]'
*
* The prefix of the logger.
*/
prefix: customConfiguration?.prefix ?? PREFIX
});
const buildAiFields = (customConfiguration) => ({
/**
* AI configuration
*/
provider: customConfiguration?.provider,
/**
* API key
*/
apiKey: customConfiguration?.apiKey,
/**
* API model
*/
model: customConfiguration?.model,
/**
* Temperature
*/
temperature: customConfiguration?.temperature,
/**
* Application context
*/
applicationContext: customConfiguration?.applicationContext
});
const buildBuildFields = (customConfiguration) => ({
/**
* Indicates if the build should be optimized
*
* Default: process.env.NODE_ENV === 'production'
*
* If true, the build will be optimized.
* If false, the build will not be optimized.
*
* Intlayer will replace all calls of dictionaries to optimize chunking. That way the final bundle will import only the dictionaries that are used.
* All imports will stay as static import to avoid async processing when loading the dictionaries.
*
* Note:
* - Intlayer will replace all call of `useIntlayer` with `useDictionary`, `getIntlayer` with `getDictionary`.
* - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.
* - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.
*/
optimize: customConfiguration?.optimize ?? OPTIMIZE,
/**
* Indicates if the dynamic import should be activated
*
* Default: false
*
* By default, when a dictionary is loaded, it imports content for all locales as it's imported statically.
* If this option is set to true, only the current locale's dictionary content
* will be fetched via dynamic import. In that case, Intlayer will replace all
* calls to `useIntlayer` with `useDynamicDictionary`.
*
* Note:
* - Dynamic imports rely on React Suspense and may slightly impact rendering performance. But if desabled all locales will be loaded at once, even if they are not used.
* - This option relies on the `@intlayer/babel` and `@intlayer/swc` plugins.
* - Ensure all keys are declared statically in the `useIntlayer` calls. e.g. `useIntlayer('navbar')`.
* - This option will be ignored if `optimize` is disabled.
*/
activateDynamicImport: customConfiguration?.activateDynamicImport ?? ACTIVATE_DYNAMIC_IMPORT,
/**
* Pattern to traverse the code to optimize.
*
* Allows to avoid to traverse the code that is not relevant to the optimization.
* Improve build performance.
*
* Default: ['**\/*.{js,ts,mjs,cjs,jsx,tsx,mjx,cjx}', '!**\/node_modules/**']
*
* Example: `['src/**\/*.{ts,tsx}', '../ui-library/**\/*.{ts,tsx}']`
*
* Note:
* - This option will be ignored if `optimize` is disabled.
* - Use glob pattern.
*/
traversePattern: customConfiguration?.traversePattern ?? TRAVERSE_PATTERN
});
const buildConfigurationFields = (customConfiguration, baseDir) => {
const internationalizationConfig = buildInternationalizationFields(
customConfiguration?.internationalization
);
const middlewareConfig = buildMiddlewareFields(
customConfiguration?.middleware
);
const contentConfig = buildContentFields(
customConfiguration?.content,
baseDir
);
const editorConfig = buildEditorFields(customConfiguration?.editor);
const logConfig = buildLogFields(customConfiguration?.log);
const aiConfig = buildAiFields(customConfiguration?.ai);
const buildConfig = buildBuildFields(customConfiguration?.build);
storedConfiguration = {
internationalization: internationalizationConfig,
middleware: middlewareConfig,
content: contentConfig,
editor: editorConfig,
log: logConfig,
ai: aiConfig,
build: buildConfig
};
return storedConfiguration;
};
export {
buildConfigurationFields
};
//# sourceMappingURL=buildConfigurationFields.mjs.map