@intlayer/config 8.1.2 → 8.1.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.
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -43
- package/dist/cjs/built.cjs +1 -7
- package/dist/cjs/built.cjs.map +1 -1
- package/dist/cjs/client.cjs +1 -40
- package/dist/cjs/configFile/buildConfigurationFields.cjs +1 -188
- package/dist/cjs/configFile/buildConfigurationFields.cjs.map +1 -1
- package/dist/cjs/configFile/getConfiguration.cjs +1 -70
- package/dist/cjs/configFile/getConfiguration.cjs.map +1 -1
- package/dist/cjs/configFile/index.cjs +1 -10
- package/dist/cjs/configFile/loadConfigurationFile.cjs +1 -33
- package/dist/cjs/configFile/loadConfigurationFile.cjs.map +1 -1
- package/dist/cjs/configFile/searchConfigurationFile.cjs +1 -51
- package/dist/cjs/configFile/searchConfigurationFile.cjs.map +1 -1
- package/dist/cjs/defaultValues/build.cjs +1 -29
- package/dist/cjs/defaultValues/build.cjs.map +1 -1
- package/dist/cjs/defaultValues/compiler.cjs +1 -24
- package/dist/cjs/defaultValues/compiler.cjs.map +1 -1
- package/dist/cjs/defaultValues/content.cjs +1 -56
- package/dist/cjs/defaultValues/content.cjs.map +1 -1
- package/dist/cjs/defaultValues/dictionary.cjs +1 -26
- package/dist/cjs/defaultValues/dictionary.cjs.map +1 -1
- package/dist/cjs/defaultValues/editor.cjs +1 -41
- package/dist/cjs/defaultValues/editor.cjs.map +1 -1
- package/dist/cjs/defaultValues/index.cjs +1 -78
- package/dist/cjs/defaultValues/internationalization.cjs +1 -27
- package/dist/cjs/defaultValues/internationalization.cjs.map +1 -1
- package/dist/cjs/defaultValues/log.cjs +1 -21
- package/dist/cjs/defaultValues/log.cjs.map +1 -1
- package/dist/cjs/defaultValues/routing.cjs +1 -35
- package/dist/cjs/defaultValues/routing.cjs.map +1 -1
- package/dist/cjs/defaultValues/system.cjs +1 -47
- package/dist/cjs/defaultValues/system.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -81
- package/dist/cjs/loadEnvFile.cjs +1 -36
- package/dist/cjs/loadEnvFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/bundleFile.cjs +1 -71
- package/dist/cjs/loadExternalFile/bundleFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/bundleJSFile.cjs +2 -0
- package/dist/cjs/loadExternalFile/bundleJSFile.cjs.map +1 -0
- package/dist/cjs/loadExternalFile/index.cjs +1 -0
- package/dist/cjs/loadExternalFile/loadExternalFile.cjs +1 -79
- package/dist/cjs/loadExternalFile/loadExternalFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/parseFileContent.cjs +1 -77
- package/dist/cjs/loadExternalFile/parseFileContent.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +1 -63
- package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
- package/dist/cjs/logger.cjs +1 -150
- package/dist/cjs/logger.cjs.map +1 -1
- package/dist/cjs/node.cjs +1 -0
- package/dist/cjs/utils/ESMxCJSHelpers.cjs +1 -27
- package/dist/cjs/utils/ESMxCJSHelpers.cjs.map +1 -1
- package/dist/cjs/utils/alias.cjs +2 -0
- package/dist/cjs/utils/alias.cjs.map +1 -0
- package/dist/cjs/utils/cacheDisk.cjs +1 -162
- package/dist/cjs/utils/cacheDisk.cjs.map +1 -1
- package/dist/cjs/utils/cacheMemory.cjs +1 -269
- package/dist/cjs/utils/cacheMemory.cjs.map +1 -1
- package/dist/cjs/utils/clearModuleCache.cjs +1 -26
- package/dist/cjs/utils/clearModuleCache.cjs.map +1 -1
- package/dist/cjs/utils/compareVersions.cjs +1 -38
- package/dist/cjs/utils/compareVersions.cjs.map +1 -1
- package/dist/cjs/utils/extractErrorMessage.cjs +1 -95
- package/dist/cjs/utils/extractErrorMessage.cjs.map +1 -1
- package/dist/cjs/utils/getExtension.cjs +1 -14
- package/dist/cjs/utils/getExtension.cjs.map +1 -1
- package/dist/cjs/utils/getPackageJsonPath.cjs +1 -35
- package/dist/cjs/utils/getPackageJsonPath.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +1 -0
- package/dist/cjs/utils/logStack.cjs +1 -16
- package/dist/cjs/utils/logStack.cjs.map +1 -1
- package/dist/cjs/utils/normalizePath.cjs +1 -17
- package/dist/cjs/utils/normalizePath.cjs.map +1 -1
- package/dist/cjs/utils/retryManager.cjs +2 -0
- package/dist/cjs/utils/retryManager.cjs.map +1 -0
- package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs +1 -13
- package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs +1 -16
- package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/index.cjs +1 -10
- package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs +1 -14
- package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs +1 -19
- package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs.map +1 -1
- package/dist/esm/_virtual/_rolldown/runtime.mjs +1 -22
- package/dist/esm/built.mjs +1 -7
- package/dist/esm/built.mjs.map +1 -1
- package/dist/esm/client.mjs +1 -11
- package/dist/esm/configFile/buildConfigurationFields.mjs +1 -186
- package/dist/esm/configFile/buildConfigurationFields.mjs.map +1 -1
- package/dist/esm/configFile/getConfiguration.mjs +1 -67
- package/dist/esm/configFile/getConfiguration.mjs.map +1 -1
- package/dist/esm/configFile/index.mjs +1 -5
- package/dist/esm/configFile/loadConfigurationFile.mjs +1 -32
- package/dist/esm/configFile/loadConfigurationFile.mjs.map +1 -1
- package/dist/esm/configFile/searchConfigurationFile.mjs +1 -48
- package/dist/esm/configFile/searchConfigurationFile.mjs.map +1 -1
- package/dist/esm/defaultValues/build.mjs +1 -18
- package/dist/esm/defaultValues/build.mjs.map +1 -1
- package/dist/esm/defaultValues/compiler.mjs +1 -19
- package/dist/esm/defaultValues/compiler.mjs.map +1 -1
- package/dist/esm/defaultValues/content.mjs +1 -43
- package/dist/esm/defaultValues/content.mjs.map +1 -1
- package/dist/esm/defaultValues/dictionary.mjs +1 -16
- package/dist/esm/defaultValues/dictionary.mjs.map +1 -1
- package/dist/esm/defaultValues/editor.mjs +1 -26
- package/dist/esm/defaultValues/editor.mjs.map +1 -1
- package/dist/esm/defaultValues/index.mjs +1 -24
- package/dist/esm/defaultValues/internationalization.mjs +1 -17
- package/dist/esm/defaultValues/internationalization.mjs.map +1 -1
- package/dist/esm/defaultValues/log.mjs +1 -13
- package/dist/esm/defaultValues/log.mjs.map +1 -1
- package/dist/esm/defaultValues/routing.mjs +1 -22
- package/dist/esm/defaultValues/routing.mjs.map +1 -1
- package/dist/esm/defaultValues/system.mjs +1 -30
- package/dist/esm/defaultValues/system.mjs.map +1 -1
- package/dist/esm/index.mjs +1 -28
- package/dist/esm/loadEnvFile.mjs +1 -32
- package/dist/esm/loadEnvFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/bundleFile.mjs +1 -67
- package/dist/esm/loadExternalFile/bundleFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/bundleJSFile.mjs +2 -0
- package/dist/esm/loadExternalFile/bundleJSFile.mjs.map +1 -0
- package/dist/esm/loadExternalFile/index.mjs +1 -0
- package/dist/esm/loadExternalFile/loadExternalFile.mjs +1 -75
- package/dist/esm/loadExternalFile/loadExternalFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/parseFileContent.mjs +1 -73
- package/dist/esm/loadExternalFile/parseFileContent.mjs.map +1 -1
- package/dist/esm/loadExternalFile/transpileTSToCJS.mjs +1 -60
- package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
- package/dist/esm/logger.mjs +1 -133
- package/dist/esm/logger.mjs.map +1 -1
- package/dist/esm/node.mjs +1 -0
- package/dist/esm/utils/ESMxCJSHelpers.mjs +1 -24
- package/dist/esm/utils/ESMxCJSHelpers.mjs.map +1 -1
- package/dist/esm/utils/alias.mjs +2 -0
- package/dist/esm/utils/alias.mjs.map +1 -0
- package/dist/esm/utils/cacheDisk.mjs +1 -159
- package/dist/esm/utils/cacheDisk.mjs.map +1 -1
- package/dist/esm/utils/cacheMemory.mjs +1 -261
- package/dist/esm/utils/cacheMemory.mjs.map +1 -1
- package/dist/esm/utils/clearModuleCache.mjs +1 -25
- package/dist/esm/utils/clearModuleCache.mjs.map +1 -1
- package/dist/esm/utils/compareVersions.mjs +1 -36
- package/dist/esm/utils/compareVersions.mjs.map +1 -1
- package/dist/esm/utils/extractErrorMessage.mjs +1 -93
- package/dist/esm/utils/extractErrorMessage.mjs.map +1 -1
- package/dist/esm/utils/getExtension.mjs +1 -12
- package/dist/esm/utils/getExtension.mjs.map +1 -1
- package/dist/esm/utils/getPackageJsonPath.mjs +1 -32
- package/dist/esm/utils/getPackageJsonPath.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +1 -0
- package/dist/esm/utils/logStack.mjs +1 -15
- package/dist/esm/utils/logStack.mjs.map +1 -1
- package/dist/esm/utils/normalizePath.mjs +1 -15
- package/dist/esm/utils/normalizePath.mjs.map +1 -1
- package/dist/esm/utils/retryManager.mjs +2 -0
- package/dist/esm/utils/retryManager.mjs.map +1 -0
- package/dist/esm/utils/stringFormatter/camelCaseToKebabCase.mjs +1 -11
- package/dist/esm/utils/stringFormatter/camelCaseToKebabCase.mjs.map +1 -1
- package/dist/esm/utils/stringFormatter/camelCaseToSentence.mjs +1 -14
- package/dist/esm/utils/stringFormatter/camelCaseToSentence.mjs.map +1 -1
- package/dist/esm/utils/stringFormatter/index.mjs +1 -6
- package/dist/esm/utils/stringFormatter/kebabCaseToCamelCase.mjs +1 -12
- package/dist/esm/utils/stringFormatter/kebabCaseToCamelCase.mjs.map +1 -1
- package/dist/esm/utils/stringFormatter/toLowerCamelCase.mjs +1 -17
- package/dist/esm/utils/stringFormatter/toLowerCamelCase.mjs.map +1 -1
- package/dist/types/index.d.ts +15 -9
- package/dist/types/{bundleJSFile.d.ts → loadExternalFile/bundleJSFile.d.ts} +1 -1
- package/dist/types/loadExternalFile/bundleJSFile.d.ts.map +1 -0
- package/dist/types/loadExternalFile/index.d.ts +6 -0
- package/dist/types/loadExternalFile/loadExternalFile.d.ts +2 -3
- package/dist/types/loadExternalFile/loadExternalFile.d.ts.map +1 -1
- package/dist/types/loadExternalFile/transpileTSToCJS.d.ts +2 -3
- package/dist/types/loadExternalFile/transpileTSToCJS.d.ts.map +1 -1
- package/dist/types/node.d.ts +5 -0
- package/dist/types/{alias.d.ts → utils/alias.d.ts} +1 -1
- package/dist/types/utils/alias.d.ts.map +1 -0
- package/dist/types/utils/getPackageJsonPath.d.ts +1 -2
- package/dist/types/utils/getPackageJsonPath.d.ts.map +1 -1
- package/dist/types/utils/index.d.ts +17 -0
- package/dist/types/{retryManager.d.ts → utils/retryManager.d.ts} +1 -1
- package/dist/types/utils/retryManager.d.ts.map +1 -0
- package/package.json +42 -10
- package/dist/cjs/alias.cjs +0 -30
- package/dist/cjs/alias.cjs.map +0 -1
- package/dist/cjs/bundleJSFile.cjs +0 -34
- package/dist/cjs/bundleJSFile.cjs.map +0 -1
- package/dist/cjs/retryManager.cjs +0 -46
- package/dist/cjs/retryManager.cjs.map +0 -1
- package/dist/esm/alias.mjs +0 -28
- package/dist/esm/alias.mjs.map +0 -1
- package/dist/esm/bundleJSFile.mjs +0 -32
- package/dist/esm/bundleJSFile.mjs.map +0 -1
- package/dist/esm/retryManager.mjs +0 -45
- package/dist/esm/retryManager.mjs.map +0 -1
- package/dist/types/alias.d.ts.map +0 -1
- package/dist/types/bundleJSFile.d.ts.map +0 -1
- package/dist/types/retryManager.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transpileTSToCJS.mjs","names":[],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, extname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {
|
|
1
|
+
{"version":3,"file":"transpileTSToCJS.mjs","names":[],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, extname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { type BuildOptions, type BuildResult, build, buildSync } from 'esbuild';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const tsconfigPath = join(\n getPackageJsonPath(dirname(filePath)).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n return existsSync(tsconfigPath) ? tsconfigPath : undefined;\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":"0SAOA,MAAM,EAAmB,GAAyC,CAChE,IAAM,EAAe,EACnB,EAAmB,EAAQ,EAAS,CAAC,CAAC,QACtC,gBACD,CAGD,OAAO,EAAW,EAAa,CAAG,EAAe,IAAA,IAG7C,EAA4B,IAAoC,CACpE,OAAQ,CACN,MAAO,KACP,OAAQ,MACR,OAAQ,KACR,MAAO,KACP,OAAQ,MACR,OAAQ,KACR,QAAS,OACT,MAAO,OACP,OAAQ,OACT,CACD,OAAQ,MACR,OAAQ,SACR,SAAU,OACV,MAAO,GACP,SAAU,WACV,OAAQ,GACR,SAAU,EAAgB,EAAS,CACnC,OAAQ,CACN,kBAAmB,KAAK,UAAU,EAAc,EAAS,CAAC,KAAK,CAChE,CACF,EAEY,GACX,EACA,EACA,IAKkC,EAAU,CAC1C,MAAO,CACL,SAAU,EACV,OALW,EADG,EAAQ,EAAS,CACA,CAM/B,WAAY,EAAQ,EAAS,CAC7B,WAAY,EACb,CACD,GAAG,EAAyB,EAAS,CACrC,GAAG,EACJ,CAAC,CAEsC,cAAc,GAAG,KAK9C,EAAmB,MAC9B,EACA,EACA,KAKkC,MAAM,EAAM,CAC5C,MAAO,CACL,SAAU,EACV,OALW,EADG,EAAQ,EAAS,CACA,CAM/B,WAAY,EAAQ,EAAS,CAC7B,WAAY,EACb,CACD,GAAG,EAAyB,EAAS,CACrC,GAAG,EACJ,CAAC,EAEsC,cAAc,GAAG"}
|
package/dist/esm/logger.mjs
CHANGED
|
@@ -1,134 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
let loggerPrefix;
|
|
3
|
-
const setPrefix = (prefix) => {
|
|
4
|
-
loggerPrefix = prefix;
|
|
5
|
-
};
|
|
6
|
-
const getPrefix = (configPrefix) => {
|
|
7
|
-
if (typeof loggerPrefix !== "undefined") return loggerPrefix;
|
|
8
|
-
return configPrefix;
|
|
9
|
-
};
|
|
10
|
-
const logger = (content, details) => {
|
|
11
|
-
const isVerbose = details?.isVerbose ?? false;
|
|
12
|
-
const mode = details?.config?.mode ?? "default";
|
|
13
|
-
const level = details?.level ?? "info";
|
|
14
|
-
const prefix = getPrefix(details?.config?.prefix);
|
|
15
|
-
const log = details?.config?.log ?? console.log;
|
|
16
|
-
const info = details?.config?.info ?? console.info;
|
|
17
|
-
const warn = details?.config?.warn ?? console.warn;
|
|
18
|
-
const error = details?.config?.error ?? console.error;
|
|
19
|
-
const debug = details?.config?.debug ?? console.debug;
|
|
20
|
-
if (mode === "disabled") return;
|
|
21
|
-
if (isVerbose && mode !== "verbose") return;
|
|
22
|
-
const flatContent = prefix ? [prefix, ...[content].flat()] : [content].flat();
|
|
23
|
-
if (level === "debug") return debug(...flatContent);
|
|
24
|
-
if (level === "info") return info(...flatContent);
|
|
25
|
-
if (level === "warn") return warn(...flatContent);
|
|
26
|
-
if (level === "error") return error(...flatContent);
|
|
27
|
-
log(...flatContent);
|
|
28
|
-
};
|
|
29
|
-
let ANSIColors = /* @__PURE__ */ function(ANSIColors) {
|
|
30
|
-
ANSIColors["RESET"] = "\x1B[0m";
|
|
31
|
-
ANSIColors["GREY"] = "\x1B[90m";
|
|
32
|
-
ANSIColors["GREY_DARK"] = "\x1B[38;5;239m";
|
|
33
|
-
ANSIColors["GREY_LIGHT"] = "\x1B[38;5;252m";
|
|
34
|
-
ANSIColors["BLUE"] = "\x1B[34m";
|
|
35
|
-
ANSIColors["RED"] = "\x1B[31m";
|
|
36
|
-
ANSIColors["GREEN"] = "\x1B[32m";
|
|
37
|
-
ANSIColors["YELLOW"] = "\x1B[38;5;226m";
|
|
38
|
-
ANSIColors["MAGENTA"] = "\x1B[35m";
|
|
39
|
-
ANSIColors["BEIGE"] = "\x1B[38;5;3m";
|
|
40
|
-
ANSIColors["ORANGE"] = "\x1B[38;5;208m";
|
|
41
|
-
ANSIColors["CYAN"] = "\x1B[36m";
|
|
42
|
-
ANSIColors["WHITE"] = "\x1B[37m";
|
|
43
|
-
ANSIColors["BOLD"] = "\x1B[1m";
|
|
44
|
-
return ANSIColors;
|
|
45
|
-
}({});
|
|
46
|
-
const spinnerFrames = [
|
|
47
|
-
"⠋",
|
|
48
|
-
"⠙",
|
|
49
|
-
"⠹",
|
|
50
|
-
"⠸",
|
|
51
|
-
"⠼",
|
|
52
|
-
"⠴",
|
|
53
|
-
"⠦",
|
|
54
|
-
"⠧",
|
|
55
|
-
"⠇",
|
|
56
|
-
"⠏"
|
|
57
|
-
];
|
|
58
|
-
/**
|
|
59
|
-
* The appLogger function takes the logger and merges it with the configuration from the intlayer config file.
|
|
60
|
-
* It allows overriding the default configuration by passing a config object in the details parameter.
|
|
61
|
-
* The configuration is merged with the default configuration from the intlayer config file.
|
|
62
|
-
*/
|
|
63
|
-
const getAppLogger = (configuration, globalDetails) => (content, details) => logger(content, {
|
|
64
|
-
...details ?? {},
|
|
65
|
-
config: {
|
|
66
|
-
...configuration?.log,
|
|
67
|
-
...globalDetails?.config,
|
|
68
|
-
...details?.config ?? {}
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
const colorize = (s, color, reset) => color ? `${color}${s}${reset ? typeof reset === "boolean" ? ANSIColors.RESET : reset : ANSIColors.RESET}` : s;
|
|
72
|
-
const colorizeLocales = (locales, color = ANSIColors.GREEN, reset = ANSIColors.RESET) => [locales].flat().map((locale) => colorize(locale, color, reset)).join(`, `);
|
|
73
|
-
const colorizeKey = (keyPath, color = ANSIColors.BEIGE, reset = ANSIColors.RESET) => [keyPath].flat().map((key) => colorize(key, color, reset)).join(`, `);
|
|
74
|
-
const colorizePath = (path, color = ANSIColors.GREY, reset = ANSIColors.RESET) => [path].flat().map((p) => colorize(p, color, reset)).join(`, `);
|
|
75
|
-
/**
|
|
76
|
-
* Colorize numeric value using Intl.NumberFormat and optional ANSI colors.
|
|
77
|
-
*
|
|
78
|
-
* Examples:
|
|
79
|
-
* colorizeNumber(2, [{ pluralRule: 'one' , color: ANSIColors.GREEN}, { pluralRule: 'other' , color: ANSIColors.RED}]) // "'\x1b[31m2\x1b[0m"
|
|
80
|
-
*/
|
|
81
|
-
const colorizeNumber = (number, options = {
|
|
82
|
-
zero: ANSIColors.BLUE,
|
|
83
|
-
one: ANSIColors.BLUE,
|
|
84
|
-
two: ANSIColors.BLUE,
|
|
85
|
-
few: ANSIColors.BLUE,
|
|
86
|
-
many: ANSIColors.BLUE,
|
|
87
|
-
other: ANSIColors.BLUE
|
|
88
|
-
}) => {
|
|
89
|
-
if (number === 0) {
|
|
90
|
-
const color = options.zero ?? ANSIColors.GREEN;
|
|
91
|
-
return colorize(number.toString(), color);
|
|
92
|
-
}
|
|
93
|
-
const color = options[new Intl.PluralRules("en").select(Number(number))];
|
|
94
|
-
return colorize(number.toString(), color);
|
|
95
|
-
};
|
|
96
|
-
const removeColor = (text) => text.replace(/\x1b\[[0-9;]*m/g, "");
|
|
97
|
-
const getLength = (length) => {
|
|
98
|
-
let value = 0;
|
|
99
|
-
if (typeof length === "number") value = length;
|
|
100
|
-
if (typeof length === "string") value = length.length;
|
|
101
|
-
if (Array.isArray(length) && length.every((l) => typeof l === "string")) value = Math.max(...length.map((str) => str.length));
|
|
102
|
-
if (Array.isArray(length) && length.every((l) => typeof l === "number")) value = Math.max(...length);
|
|
103
|
-
return Math.max(value, 0);
|
|
104
|
-
};
|
|
105
|
-
const defaultColonOptions = {
|
|
106
|
-
colSize: 0,
|
|
107
|
-
minSize: 0,
|
|
108
|
-
maxSize: Infinity,
|
|
109
|
-
pad: "right",
|
|
110
|
-
padChar: "0"
|
|
111
|
-
};
|
|
112
|
-
/**
|
|
113
|
-
* Create a string of spaces of a given length.
|
|
114
|
-
*
|
|
115
|
-
* @param colSize - The length of the string to create.
|
|
116
|
-
* @returns A string of spaces.
|
|
117
|
-
*/
|
|
118
|
-
const colon = (text, options) => [text].flat().map((text) => {
|
|
119
|
-
const { colSize, minSize, maxSize, pad, padChar } = {
|
|
120
|
-
...defaultColonOptions,
|
|
121
|
-
...options ?? {}
|
|
122
|
-
};
|
|
123
|
-
const length = getLength(colSize);
|
|
124
|
-
const spacesLength = Math.max(minSize, Math.min(maxSize, length - removeColor(text).length));
|
|
125
|
-
if (pad === "left") return `${" ".repeat(spacesLength)}${text}`;
|
|
126
|
-
return `${text}${" ".repeat(spacesLength)}`;
|
|
127
|
-
}).join("");
|
|
128
|
-
const x = colorize("✗", ANSIColors.RED);
|
|
129
|
-
const v = colorize("✓", ANSIColors.GREEN);
|
|
130
|
-
const clock = colorize("⏲", ANSIColors.BLUE);
|
|
131
|
-
|
|
132
|
-
//#endregion
|
|
133
|
-
export { ANSIColors, clock, colon, colorize, colorizeKey, colorizeLocales, colorizeNumber, colorizePath, getAppLogger, getPrefix, logger, removeColor, setPrefix, spinnerFrames, v, x };
|
|
1
|
+
let e;const t=t=>{e=t},n=t=>e===void 0?t:e,r=(e,t)=>{let r=t?.isVerbose??!1,i=t?.config?.mode??`default`,a=t?.level??`info`,o=n(t?.config?.prefix),s=t?.config?.log??console.log,c=t?.config?.info??console.info,l=t?.config?.warn??console.warn,u=t?.config?.error??console.error,d=t?.config?.debug??console.debug;if(i===`disabled`||r&&i!==`verbose`)return;let f=o?[o,...[e].flat()]:[e].flat();if(a===`debug`)return d(...f);if(a===`info`)return c(...f);if(a===`warn`)return l(...f);if(a===`error`)return u(...f);s(...f)};let i=function(e){return e.RESET=`\x1B[0m`,e.GREY=`\x1B[90m`,e.GREY_DARK=`\x1B[38;5;239m`,e.GREY_LIGHT=`\x1B[38;5;252m`,e.BLUE=`\x1B[34m`,e.RED=`\x1B[31m`,e.GREEN=`\x1B[32m`,e.YELLOW=`\x1B[38;5;226m`,e.MAGENTA=`\x1B[35m`,e.BEIGE=`\x1B[38;5;3m`,e.ORANGE=`\x1B[38;5;208m`,e.CYAN=`\x1B[36m`,e.WHITE=`\x1B[37m`,e.BOLD=`\x1B[1m`,e}({});const a=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],o=(e,t)=>(n,i)=>r(n,{...i??{},config:{...e?.log,...t?.config,...i?.config??{}}}),s=(e,t,n)=>t?`${t}${e}${n?typeof n==`boolean`?i.RESET:n:i.RESET}`:e,c=(e,t=i.GREEN,n=i.RESET)=>[e].flat().map(e=>s(e,t,n)).join(`, `),l=(e,t=i.BEIGE,n=i.RESET)=>[e].flat().map(e=>s(e,t,n)).join(`, `),u=(e,t=i.GREY,n=i.RESET)=>[e].flat().map(e=>s(e,t,n)).join(`, `),d=(e,t={zero:i.BLUE,one:i.BLUE,two:i.BLUE,few:i.BLUE,many:i.BLUE,other:i.BLUE})=>{if(e===0){let n=t.zero??i.GREEN;return s(e.toString(),n)}let n=t[new Intl.PluralRules(`en`).select(Number(e))];return s(e.toString(),n)},f=e=>e.replace(/\x1b\[[0-9;]*m/g,``),p=e=>{let t=0;return typeof e==`number`&&(t=e),typeof e==`string`&&(t=e.length),Array.isArray(e)&&e.every(e=>typeof e==`string`)&&(t=Math.max(...e.map(e=>e.length))),Array.isArray(e)&&e.every(e=>typeof e==`number`)&&(t=Math.max(...e)),Math.max(t,0)},m={colSize:0,minSize:0,maxSize:1/0,pad:`right`,padChar:`0`},h=(e,t)=>[e].flat().map(e=>{let{colSize:n,minSize:r,maxSize:i,pad:a,padChar:o}={...m,...t??{}},s=p(n),c=Math.max(r,Math.min(i,s-f(e).length));return a===`left`?`${` `.repeat(c)}${e}`:`${e}${` `.repeat(c)}`}).join(``),g=s(`✗`,i.RED),_=s(`✓`,i.GREEN),v=s(`⏲`,i.BLUE);export{i as ANSIColors,v as clock,h as colon,s as colorize,l as colorizeKey,c as colorizeLocales,d as colorizeNumber,u as colorizePath,o as getAppLogger,n as getPrefix,r as logger,f as removeColor,t as setPrefix,a as spinnerFrames,_ as v,g as x};
|
|
134
2
|
//# sourceMappingURL=logger.mjs.map
|
package/dist/esm/logger.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.mjs","names":[],"sources":["../../src/logger.ts"],"sourcesContent":["import type { CustomIntlayerConfig, Locale } from '@intlayer/types';\n\nexport type Details = {\n isVerbose?: boolean;\n level?: 'info' | 'warn' | 'error' | 'debug';\n config?: CustomIntlayerConfig['log'];\n};\n\nexport type Logger = (content: any, details?: Details) => void;\n\nlet loggerPrefix: string | undefined;\n\nexport const setPrefix = (prefix: string | undefined) => {\n loggerPrefix = prefix;\n};\n\nexport const getPrefix = (configPrefix?: string): string | undefined => {\n if (typeof loggerPrefix !== 'undefined') {\n return loggerPrefix;\n }\n\n return configPrefix;\n};\n\nexport const logger: Logger = (content, details) => {\n const isVerbose = details?.isVerbose ?? false;\n const mode = details?.config?.mode ?? 'default';\n const level = details?.level ?? 'info';\n const prefix = getPrefix(details?.config?.prefix);\n const log = details?.config?.log ?? console.log;\n const info = details?.config?.info ?? console.info;\n const warn = details?.config?.warn ?? console.warn;\n const error = details?.config?.error ?? console.error;\n const debug = details?.config?.debug ?? console.debug;\n\n if (mode === 'disabled') return;\n\n if (isVerbose && mode !== 'verbose') return;\n\n const flatContent = prefix ? [prefix, ...[content].flat()] : [content].flat();\n\n if (level === 'debug') {\n return debug(...flatContent);\n }\n\n if (level === 'info') {\n return info(...flatContent);\n }\n\n if (level === 'warn') {\n return warn(...flatContent);\n }\n\n if (level === 'error') {\n return error(...flatContent);\n }\n\n log(...flatContent);\n};\n\nexport enum ANSIColors {\n RESET = '\\x1b[0m',\n GREY = '\\x1b[90m',\n GREY_DARK = '\\x1b[38;5;239m',\n GREY_LIGHT = '\\x1b[38;5;252m',\n BLUE = '\\x1b[34m',\n RED = '\\x1b[31m',\n GREEN = '\\x1b[32m',\n YELLOW = '\\x1b[38;5;226m',\n MAGENTA = '\\x1b[35m',\n BEIGE = '\\x1b[38;5;3m',\n ORANGE = '\\x1b[38;5;208m',\n CYAN = '\\x1b[36m',\n WHITE = '\\x1b[37m',\n BOLD = '\\x1b[1m',\n}\n\nexport const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n/**\n * The appLogger function takes the logger and merges it with the configuration from the intlayer config file.\n * It allows overriding the default configuration by passing a config object in the details parameter.\n * The configuration is merged with the default configuration from the intlayer config file.\n */\nexport const getAppLogger =\n (configuration?: CustomIntlayerConfig, globalDetails?: Details) =>\n (content: any, details?: Details) =>\n logger(content, {\n ...(details ?? {}),\n config: {\n ...configuration?.log,\n ...globalDetails?.config,\n ...(details?.config ?? {}),\n },\n });\n\nexport const colorize = (\n s: string,\n color?: ANSIColors,\n reset?: boolean | ANSIColors\n): string =>\n color\n ? `${color}${s}${reset ? (typeof reset === 'boolean' ? ANSIColors.RESET : reset) : ANSIColors.RESET}`\n : s;\n\nexport const colorizeLocales = (\n locales: Locale | Locale[],\n color = ANSIColors.GREEN,\n reset: boolean | ANSIColors = ANSIColors.RESET\n) =>\n [locales]\n .flat()\n .map((locale) => colorize(locale, color, reset))\n .join(`, `);\n\nexport const colorizeKey = (\n keyPath: string | string[],\n color = ANSIColors.BEIGE,\n reset: boolean | ANSIColors = ANSIColors.RESET\n) =>\n [keyPath]\n .flat()\n .map((key) => colorize(key, color, reset))\n .join(`, `);\n\nexport const colorizePath = (\n path: string | string[],\n color = ANSIColors.GREY,\n reset: boolean | ANSIColors = ANSIColors.RESET\n) =>\n [path]\n .flat()\n .map((p) => colorize(p, color, reset))\n .join(`, `);\n\n/**\n * Colorize numeric value using Intl.NumberFormat and optional ANSI colors.\n *\n * Examples:\n * colorizeNumber(2, [{ pluralRule: 'one' , color: ANSIColors.GREEN}, { pluralRule: 'other' , color: ANSIColors.RED}]) // \"'\\x1b[31m2\\x1b[0m\"\n */\nexport const colorizeNumber = (\n number: number | string,\n options: Partial<Record<Intl.LDMLPluralRule, ANSIColors>> = {\n zero: ANSIColors.BLUE,\n one: ANSIColors.BLUE,\n two: ANSIColors.BLUE,\n few: ANSIColors.BLUE,\n many: ANSIColors.BLUE,\n other: ANSIColors.BLUE,\n }\n): string => {\n if (number === 0) {\n const color = options.zero ?? ANSIColors.GREEN;\n return colorize(number.toString(), color);\n }\n\n const rule = new Intl.PluralRules('en').select(Number(number));\n const color = options[rule];\n return colorize(number.toString(), color);\n};\n\nexport const removeColor = (text: string) =>\n // biome-ignore lint/suspicious/noControlCharactersInRegex: we need to remove the color codes\n text.replace(/\\x1b\\[[0-9;]*m/g, '');\n\nconst getLength = (length: number | number[] | string | string[]): number => {\n let value: number = 0;\n if (typeof length === 'number') {\n value = length;\n }\n if (typeof length === 'string') {\n value = length.length;\n }\n if (Array.isArray(length) && length.every((l) => typeof l === 'string')) {\n value = Math.max(...length.map((str) => str.length));\n }\n if (Array.isArray(length) && length.every((l) => typeof l === 'number')) {\n value = Math.max(...length);\n }\n return Math.max(value, 0);\n};\n\nconst defaultColonOptions = {\n colSize: 0,\n minSize: 0,\n maxSize: Infinity,\n pad: 'right',\n padChar: '0',\n};\n\n/**\n * Create a string of spaces of a given length.\n *\n * @param colSize - The length of the string to create.\n * @returns A string of spaces.\n */\nexport const colon = (\n text: string | string[],\n options?: {\n colSize?: number | number[] | string | string[];\n minSize?: number;\n maxSize?: number;\n pad?: 'left' | 'right';\n padChar?: string;\n }\n): string =>\n [text]\n .flat()\n .map((text) => {\n const { colSize, minSize, maxSize, pad, padChar } = {\n ...defaultColonOptions,\n ...(options ?? {}),\n };\n\n const length = getLength(colSize);\n const spacesLength = Math.max(\n minSize!,\n Math.min(maxSize!, length - removeColor(text).length)\n );\n\n if (pad === 'left') {\n return `${' '.repeat(spacesLength)}${text}`;\n }\n\n return `${text}${' '.repeat(spacesLength)}`;\n })\n .join('');\n\nexport const x = colorize('✗', ANSIColors.RED);\nexport const v = colorize('✓', ANSIColors.GREEN);\nexport const clock = colorize('⏲', ANSIColors.BLUE);\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"logger.mjs","names":[],"sources":["../../src/logger.ts"],"sourcesContent":["import type { CustomIntlayerConfig, Locale } from '@intlayer/types';\n\nexport type Details = {\n isVerbose?: boolean;\n level?: 'info' | 'warn' | 'error' | 'debug';\n config?: CustomIntlayerConfig['log'];\n};\n\nexport type Logger = (content: any, details?: Details) => void;\n\nlet loggerPrefix: string | undefined;\n\nexport const setPrefix = (prefix: string | undefined) => {\n loggerPrefix = prefix;\n};\n\nexport const getPrefix = (configPrefix?: string): string | undefined => {\n if (typeof loggerPrefix !== 'undefined') {\n return loggerPrefix;\n }\n\n return configPrefix;\n};\n\nexport const logger: Logger = (content, details) => {\n const isVerbose = details?.isVerbose ?? false;\n const mode = details?.config?.mode ?? 'default';\n const level = details?.level ?? 'info';\n const prefix = getPrefix(details?.config?.prefix);\n const log = details?.config?.log ?? console.log;\n const info = details?.config?.info ?? console.info;\n const warn = details?.config?.warn ?? console.warn;\n const error = details?.config?.error ?? console.error;\n const debug = details?.config?.debug ?? console.debug;\n\n if (mode === 'disabled') return;\n\n if (isVerbose && mode !== 'verbose') return;\n\n const flatContent = prefix ? [prefix, ...[content].flat()] : [content].flat();\n\n if (level === 'debug') {\n return debug(...flatContent);\n }\n\n if (level === 'info') {\n return info(...flatContent);\n }\n\n if (level === 'warn') {\n return warn(...flatContent);\n }\n\n if (level === 'error') {\n return error(...flatContent);\n }\n\n log(...flatContent);\n};\n\nexport enum ANSIColors {\n RESET = '\\x1b[0m',\n GREY = '\\x1b[90m',\n GREY_DARK = '\\x1b[38;5;239m',\n GREY_LIGHT = '\\x1b[38;5;252m',\n BLUE = '\\x1b[34m',\n RED = '\\x1b[31m',\n GREEN = '\\x1b[32m',\n YELLOW = '\\x1b[38;5;226m',\n MAGENTA = '\\x1b[35m',\n BEIGE = '\\x1b[38;5;3m',\n ORANGE = '\\x1b[38;5;208m',\n CYAN = '\\x1b[36m',\n WHITE = '\\x1b[37m',\n BOLD = '\\x1b[1m',\n}\n\nexport const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n/**\n * The appLogger function takes the logger and merges it with the configuration from the intlayer config file.\n * It allows overriding the default configuration by passing a config object in the details parameter.\n * The configuration is merged with the default configuration from the intlayer config file.\n */\nexport const getAppLogger =\n (configuration?: CustomIntlayerConfig, globalDetails?: Details) =>\n (content: any, details?: Details) =>\n logger(content, {\n ...(details ?? {}),\n config: {\n ...configuration?.log,\n ...globalDetails?.config,\n ...(details?.config ?? {}),\n },\n });\n\nexport const colorize = (\n s: string,\n color?: ANSIColors,\n reset?: boolean | ANSIColors\n): string =>\n color\n ? `${color}${s}${reset ? (typeof reset === 'boolean' ? ANSIColors.RESET : reset) : ANSIColors.RESET}`\n : s;\n\nexport const colorizeLocales = (\n locales: Locale | Locale[],\n color = ANSIColors.GREEN,\n reset: boolean | ANSIColors = ANSIColors.RESET\n) =>\n [locales]\n .flat()\n .map((locale) => colorize(locale, color, reset))\n .join(`, `);\n\nexport const colorizeKey = (\n keyPath: string | string[],\n color = ANSIColors.BEIGE,\n reset: boolean | ANSIColors = ANSIColors.RESET\n) =>\n [keyPath]\n .flat()\n .map((key) => colorize(key, color, reset))\n .join(`, `);\n\nexport const colorizePath = (\n path: string | string[],\n color = ANSIColors.GREY,\n reset: boolean | ANSIColors = ANSIColors.RESET\n) =>\n [path]\n .flat()\n .map((p) => colorize(p, color, reset))\n .join(`, `);\n\n/**\n * Colorize numeric value using Intl.NumberFormat and optional ANSI colors.\n *\n * Examples:\n * colorizeNumber(2, [{ pluralRule: 'one' , color: ANSIColors.GREEN}, { pluralRule: 'other' , color: ANSIColors.RED}]) // \"'\\x1b[31m2\\x1b[0m\"\n */\nexport const colorizeNumber = (\n number: number | string,\n options: Partial<Record<Intl.LDMLPluralRule, ANSIColors>> = {\n zero: ANSIColors.BLUE,\n one: ANSIColors.BLUE,\n two: ANSIColors.BLUE,\n few: ANSIColors.BLUE,\n many: ANSIColors.BLUE,\n other: ANSIColors.BLUE,\n }\n): string => {\n if (number === 0) {\n const color = options.zero ?? ANSIColors.GREEN;\n return colorize(number.toString(), color);\n }\n\n const rule = new Intl.PluralRules('en').select(Number(number));\n const color = options[rule];\n return colorize(number.toString(), color);\n};\n\nexport const removeColor = (text: string) =>\n // biome-ignore lint/suspicious/noControlCharactersInRegex: we need to remove the color codes\n text.replace(/\\x1b\\[[0-9;]*m/g, '');\n\nconst getLength = (length: number | number[] | string | string[]): number => {\n let value: number = 0;\n if (typeof length === 'number') {\n value = length;\n }\n if (typeof length === 'string') {\n value = length.length;\n }\n if (Array.isArray(length) && length.every((l) => typeof l === 'string')) {\n value = Math.max(...length.map((str) => str.length));\n }\n if (Array.isArray(length) && length.every((l) => typeof l === 'number')) {\n value = Math.max(...length);\n }\n return Math.max(value, 0);\n};\n\nconst defaultColonOptions = {\n colSize: 0,\n minSize: 0,\n maxSize: Infinity,\n pad: 'right',\n padChar: '0',\n};\n\n/**\n * Create a string of spaces of a given length.\n *\n * @param colSize - The length of the string to create.\n * @returns A string of spaces.\n */\nexport const colon = (\n text: string | string[],\n options?: {\n colSize?: number | number[] | string | string[];\n minSize?: number;\n maxSize?: number;\n pad?: 'left' | 'right';\n padChar?: string;\n }\n): string =>\n [text]\n .flat()\n .map((text) => {\n const { colSize, minSize, maxSize, pad, padChar } = {\n ...defaultColonOptions,\n ...(options ?? {}),\n };\n\n const length = getLength(colSize);\n const spacesLength = Math.max(\n minSize!,\n Math.min(maxSize!, length - removeColor(text).length)\n );\n\n if (pad === 'left') {\n return `${' '.repeat(spacesLength)}${text}`;\n }\n\n return `${text}${' '.repeat(spacesLength)}`;\n })\n .join('');\n\nexport const x = colorize('✗', ANSIColors.RED);\nexport const v = colorize('✓', ANSIColors.GREEN);\nexport const clock = colorize('⏲', ANSIColors.BLUE);\n"],"mappings":"AAUA,IAAI,EAEJ,MAAa,EAAa,GAA+B,CACvD,EAAe,GAGJ,EAAa,GACb,I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I,OAAO,CAAC,EAElD,MAAM,QAAQ,EAAO,EAAI,EAAO,MAAO,GAAM,OAAO,GAAM,SAAS,GACrE,EAAQ,KAAK,IAAI,GAAG,EAAO,EAEtB,KAAK,IAAI,EAAO,EAAE,EAGrB,EAAsB,CAC1B,QAAS,EACT,QAAS,EACT,QAAS,IACT,IAAK,QACL,QAAS,IACV,CAQY,GACX,EACA,IAQA,CAAC,EAAK,CACH,MAAM,CACN,IAAK,GAAS,CACb,GAAM,CAAE,UAAS,UAAS,UAAS,MAAK,WAAY,CAClD,GAAG,EACH,GAAI,GAAW,EAAE,CAClB,CAEK,EAAS,EAAU,EAAQ,CAC3B,EAAe,KAAK,IACxB,EACA,KAAK,IAAI,EAAU,EAAS,EAAY,EAAK,CAAC,OAAO,CACtD,CAMD,OAJI,IAAQ,OACH,GAAG,IAAI,OAAO,EAAa,GAAG,IAGhC,GAAG,IAAO,IAAI,OAAO,EAAa,IACzC,CACD,KAAK,GAAG,CAEA,EAAI,EAAS,IAAK,EAAW,IAAI,CACjC,EAAI,EAAS,IAAK,EAAW,MAAM,CACnC,EAAQ,EAAS,IAAK,EAAW,KAAK"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{buildConfigurationFields as e}from"./configFile/buildConfigurationFields.mjs";import{configurationFilesCandidates as t,searchConfigurationFile as n}from"./configFile/searchConfigurationFile.mjs";import{getConfiguration as r,getConfigurationAndFilePath as i}from"./configFile/getConfiguration.mjs";import{defaultValues_exports as a}from"./defaultValues/index.mjs";export{a as DefaultValues,e as buildConfigurationFields,t as configurationFilesCandidates,r as getConfiguration,i as getConfigurationAndFilePath,n as searchConfigurationFile};
|
|
@@ -1,25 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { getPackageJsonPath } from "./getPackageJsonPath.mjs";
|
|
3
|
-
import { createRequire } from "node:module";
|
|
4
|
-
|
|
5
|
-
//#region src/utils/ESMxCJSHelpers.ts
|
|
6
|
-
const isESModule = typeof import.meta.url === "string";
|
|
7
|
-
/**
|
|
8
|
-
* Require relative to the user project
|
|
9
|
-
*
|
|
10
|
-
* Note: Can resolve package that are installed in the user project, ex `'intlayer'`
|
|
11
|
-
*/
|
|
12
|
-
const getProjectRequire = (startDir) => {
|
|
13
|
-
const { packageJsonPath } = getPackageJsonPath(startDir);
|
|
14
|
-
return createRequire(packageJsonPath);
|
|
15
|
-
};
|
|
16
|
-
/**
|
|
17
|
-
* Require relative to the @intlayer/config package
|
|
18
|
-
*
|
|
19
|
-
* Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`
|
|
20
|
-
*/
|
|
21
|
-
const configESMxCJSRequire = isESModule ? createRequire(import.meta.url) : __require;
|
|
22
|
-
|
|
23
|
-
//#endregion
|
|
24
|
-
export { configESMxCJSRequire, getProjectRequire, isESModule };
|
|
1
|
+
import{__require as e}from"../_virtual/_rolldown/runtime.mjs";import{getPackageJsonPath as t}from"./getPackageJsonPath.mjs";import{createRequire as n}from"node:module";const r=typeof import.meta.url==`string`,i=e=>{let{packageJsonPath:r}=t(e);return n(r)},a=r?n(import.meta.url):e;export{a as configESMxCJSRequire,i as getProjectRequire,r as isESModule};
|
|
25
2
|
//# sourceMappingURL=ESMxCJSHelpers.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ESMxCJSHelpers.mjs","names":[],"sources":["../../../src/utils/ESMxCJSHelpers.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { getPackageJsonPath } from './getPackageJsonPath';\n\nexport const isESModule = typeof import.meta.url === 'string';\n\n/**\n * Require relative to the user project\n *\n * Note: Can resolve package that are installed in the user project, ex `'intlayer'`\n */\nexport const getProjectRequire = (startDir?: string): NodeJS.Require => {\n // Can fail on VSCode extensions\n const { packageJsonPath } = getPackageJsonPath(startDir);\n\n return createRequire(packageJsonPath);\n};\n\n/**\n * Require relative to the @intlayer/config package\n *\n * Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`\n */\nexport const configESMxCJSRequire: NodeJS.Require = isESModule\n ? createRequire(import.meta.url)\n : require;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ESMxCJSHelpers.mjs","names":[],"sources":["../../../src/utils/ESMxCJSHelpers.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { getPackageJsonPath } from './getPackageJsonPath';\n\nexport const isESModule = typeof import.meta.url === 'string';\n\n/**\n * Require relative to the user project\n *\n * Note: Can resolve package that are installed in the user project, ex `'intlayer'`\n */\nexport const getProjectRequire = (startDir?: string): NodeJS.Require => {\n // Can fail on VSCode extensions\n const { packageJsonPath } = getPackageJsonPath(startDir);\n\n return createRequire(packageJsonPath);\n};\n\n/**\n * Require relative to the @intlayer/config package\n *\n * Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`\n */\nexport const configESMxCJSRequire: NodeJS.Require = isESModule\n ? createRequire(import.meta.url)\n : require;\n"],"mappings":"wKAGA,MAAa,EAAa,OAAO,OAAO,KAAK,KAAQ,SAOxC,EAAqB,GAAsC,CAEtE,GAAM,CAAE,mBAAoB,EAAmB,EAAS,CAExD,OAAO,EAAc,EAAgB,EAQ1B,EAAuC,EAChD,EAAc,OAAO,KAAK,IAAI,CAAA"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{normalizePath as e}from"./normalizePath.mjs";import{getExtension as t}from"./getExtension.mjs";import{join as n,relative as r}from"node:path";const i=({configuration:i,format:a,formatter:o=e=>e})=>{let s=t(i,a??i.build.outputFormat[0]??`esm`),{baseDir:c}=i.content,{mainDir:l,configDir:u}=i.system,d=o(e(r(c,n(l,`dictionaries.${s}`)))),f=o(e(r(c,n(l,`unmerged_dictionaries.${s}`)))),p=o(e(r(c,n(l,`remote_dictionaries.${s}`)))),m=o(e(r(c,n(l,`dynamic_dictionaries.${s}`)))),h=o(e(r(c,n(l,`fetch_dictionaries.${s}`)))),g=o(e(r(c,n(u,`configuration.json`))));return{"@intlayer/dictionaries-entry":d,"@intlayer/unmerged-dictionaries-entry":f,"@intlayer/remote-dictionaries-entry":p,"@intlayer/dynamic-dictionaries-entry":m,"@intlayer/fetch-dictionaries-entry":h,"@intlayer/config/built":g}};export{i as getAlias};
|
|
2
|
+
//# sourceMappingURL=alias.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"alias.mjs","names":[],"sources":["../../../src/utils/alias.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { getExtension } from './getExtension';\nimport { normalizePath } from './normalizePath';\n\nexport type GetAliasOptions = {\n configuration: IntlayerConfig;\n format?: 'esm' | 'cjs';\n formatter?: (value: string) => string;\n};\n\nexport const getAlias = ({\n configuration,\n format,\n formatter = (value: string) => value,\n}: GetAliasOptions) => {\n const extension = getExtension(\n configuration,\n format ?? configuration.build.outputFormat[0] ?? 'esm'\n );\n\n const { baseDir } = configuration.content;\n const { mainDir, configDir } = configuration.system;\n\n /**\n * Dictionaries\n */\n const dictionariesPath = join(mainDir, `dictionaries.${extension}`);\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n const fixedDictionariesPath = formatter(\n normalizePath(relativeDictionariesPath)\n );\n\n /**\n * Unmerged dictionaries\n */\n const unmergedDictionariesPath = join(\n mainDir,\n `unmerged_dictionaries.${extension}`\n );\n const relativeUnmergedDictionariesPath = relative(\n baseDir,\n unmergedDictionariesPath\n );\n const fixedUnmergedDictionariesPath = formatter(\n normalizePath(relativeUnmergedDictionariesPath)\n );\n\n /**\n * Remote dictionaries\n */\n const remoteDictionariesPath = join(\n mainDir,\n `remote_dictionaries.${extension}`\n );\n const relativeRemoteDictionariesPath = relative(\n baseDir,\n remoteDictionariesPath\n );\n const fixedRemoteDictionariesPath = formatter(\n normalizePath(relativeRemoteDictionariesPath)\n );\n\n /**\n * Dynamic dictionaries\n */\n const dynamicDictionariesPath = join(\n mainDir,\n `dynamic_dictionaries.${extension}`\n );\n const relativeDynamicDictionariesPath = relative(\n baseDir,\n dynamicDictionariesPath\n );\n const fixedDynamicDictionariesPath = formatter(\n normalizePath(relativeDynamicDictionariesPath)\n );\n\n /**\n * Fetch dictionaries\n */\n const fetchDictionariesPath = join(\n mainDir,\n `fetch_dictionaries.${extension}`\n );\n const relativeFetchDictionariesPath = relative(\n baseDir,\n fetchDictionariesPath\n );\n const fixedFetchDictionariesPath = formatter(\n normalizePath(relativeFetchDictionariesPath)\n );\n\n /**\n * Configuration\n */\n const configurationPath = join(configDir, `configuration.json`);\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n const fixedConfigurationPath = formatter(\n normalizePath(relativeConfigurationPath)\n );\n\n return {\n '@intlayer/dictionaries-entry': fixedDictionariesPath,\n '@intlayer/unmerged-dictionaries-entry': fixedUnmergedDictionariesPath,\n '@intlayer/remote-dictionaries-entry': fixedRemoteDictionariesPath,\n '@intlayer/dynamic-dictionaries-entry': fixedDynamicDictionariesPath,\n '@intlayer/fetch-dictionaries-entry': fixedFetchDictionariesPath,\n '@intlayer/config/built': fixedConfigurationPath,\n } as const;\n};\n"],"mappings":"qJAWA,MAAa,GAAY,CACvB,gBACA,SACA,YAAa,GAAkB,KACV,CACrB,IAAM,EAAY,EAChB,EACA,GAAU,EAAc,MAAM,aAAa,IAAM,MAClD,CAEK,CAAE,WAAY,EAAc,QAC5B,CAAE,UAAS,aAAc,EAAc,OAOvC,EAAwB,EAC5B,EAF+B,EAAS,EADjB,EAAK,EAAS,gBAAgB,IAAY,CACC,CAE3B,CACxC,CAaK,EAAgC,EACpC,EALuC,EACvC,EAL+B,EAC/B,EACA,yBAAyB,IAC1B,CAIA,CAEgD,CAChD,CAaK,EAA8B,EAClC,EALqC,EACrC,EAL6B,EAC7B,EACA,uBAAuB,IACxB,CAIA,CAE8C,CAC9C,CAaK,EAA+B,EACnC,EALsC,EACtC,EAL8B,EAC9B,EACA,wBAAwB,IACzB,CAIA,CAE+C,CAC/C,CAaK,EAA6B,EACjC,EALoC,EACpC,EAL4B,EAC5B,EACA,sBAAsB,IACvB,CAIA,CAE6C,CAC7C,CAOK,EAAyB,EAC7B,EAFgC,EAAS,EADjB,EAAK,EAAW,qBAAqB,CACO,CAE5B,CACzC,CAED,MAAO,CACL,+BAAgC,EAChC,wCAAyC,EACzC,sCAAuC,EACvC,uCAAwC,EACxC,qCAAsC,EACtC,yBAA0B,EAC3B"}
|
|
@@ -1,160 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
3
|
-
import packageJson from "@intlayer/types/package.json" with { type: "json" };
|
|
4
|
-
import { mkdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
5
|
-
import { deserialize, serialize } from "node:v8";
|
|
6
|
-
import { gunzipSync, gzipSync } from "node:zlib";
|
|
7
|
-
|
|
8
|
-
//#region src/utils/cacheDisk.ts
|
|
9
|
-
const DEFAULTS = { compress: true };
|
|
10
|
-
const ensureDir = async (dir) => {
|
|
11
|
-
await mkdir(dir, { recursive: true });
|
|
12
|
-
};
|
|
13
|
-
const atomicWriteFile = async (file, data) => {
|
|
14
|
-
const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
15
|
-
await writeFile(tmp, data);
|
|
16
|
-
await rename(tmp, file);
|
|
17
|
-
};
|
|
18
|
-
const shouldUseCompression = (buf, force) => force === true || force !== false && buf.byteLength > 1024;
|
|
19
|
-
/** Derive on-disk path from config dir + namespace + key id. */
|
|
20
|
-
const cachePath = (cacheDir, id, ns) => join(cacheDir, ns ? join(ns, id) : id);
|
|
21
|
-
/** ------------------------- Local cache facade ------------------------- **/
|
|
22
|
-
const cacheMap = /* @__PURE__ */ new Map();
|
|
23
|
-
const cacheDisk = (intlayerConfig, keys, options) => {
|
|
24
|
-
const { cacheDir } = intlayerConfig.system;
|
|
25
|
-
const buildCacheEnabled = intlayerConfig.build.cache ?? true;
|
|
26
|
-
const persistent = options?.persistent === true || typeof options?.persistent === "undefined" && buildCacheEnabled;
|
|
27
|
-
const { compress, ttlMs, maxTimeMs, namespace } = {
|
|
28
|
-
...DEFAULTS,
|
|
29
|
-
...options
|
|
30
|
-
};
|
|
31
|
-
const id = computeKeyId(keys);
|
|
32
|
-
const filePath = cachePath(cacheDir, id, namespace);
|
|
33
|
-
const readFromDisk = async () => {
|
|
34
|
-
try {
|
|
35
|
-
const statValue = await stat(filePath).catch(() => void 0);
|
|
36
|
-
if (!statValue) return void 0;
|
|
37
|
-
if (typeof ttlMs === "number" && ttlMs > 0) {
|
|
38
|
-
if (Date.now() - statValue.mtimeMs > ttlMs) return void 0;
|
|
39
|
-
}
|
|
40
|
-
let raw = await readFile(filePath);
|
|
41
|
-
const flag = raw[0];
|
|
42
|
-
raw = raw.subarray(1);
|
|
43
|
-
const deserialized = deserialize(flag === 1 ? gunzipSync(raw) : raw);
|
|
44
|
-
let value;
|
|
45
|
-
const maybeObj = deserialized;
|
|
46
|
-
if (!!maybeObj && typeof maybeObj === "object" && typeof maybeObj.version === "string" && typeof maybeObj.timestamp === "number" && Object.hasOwn(maybeObj, "data")) {
|
|
47
|
-
const entry = maybeObj;
|
|
48
|
-
if (entry.version !== packageJson.version) {
|
|
49
|
-
try {
|
|
50
|
-
await unlink(filePath);
|
|
51
|
-
} catch {}
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
if (typeof maxTimeMs === "number" && maxTimeMs > 0) {
|
|
55
|
-
if (Date.now() - entry.timestamp > maxTimeMs) {
|
|
56
|
-
try {
|
|
57
|
-
await unlink(filePath);
|
|
58
|
-
} catch {}
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
value = entry.data;
|
|
63
|
-
} else {
|
|
64
|
-
if (typeof maxTimeMs === "number" && maxTimeMs > 0) {
|
|
65
|
-
if (Date.now() - statValue.mtimeMs > maxTimeMs) {
|
|
66
|
-
try {
|
|
67
|
-
await unlink(filePath);
|
|
68
|
-
} catch {}
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
value = deserialized;
|
|
73
|
-
}
|
|
74
|
-
cacheMap.set(id, value);
|
|
75
|
-
return value;
|
|
76
|
-
} catch {
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
const writeToDisk = async (value) => {
|
|
81
|
-
try {
|
|
82
|
-
await ensureDir(dirname(filePath));
|
|
83
|
-
const envelope = {
|
|
84
|
-
version: packageJson.version,
|
|
85
|
-
timestamp: Date.now(),
|
|
86
|
-
data: value
|
|
87
|
-
};
|
|
88
|
-
const payload = Buffer.from(serialize(envelope));
|
|
89
|
-
const gz = shouldUseCompression(payload, compress) ? gzipSync(payload) : payload;
|
|
90
|
-
await atomicWriteFile(filePath, Buffer.concat([Buffer.from([gz === payload ? 0 : 1]), gz]));
|
|
91
|
-
} catch {}
|
|
92
|
-
};
|
|
93
|
-
return {
|
|
94
|
-
get: async () => {
|
|
95
|
-
const mem = cacheMap.get(id);
|
|
96
|
-
if (mem !== void 0) return mem;
|
|
97
|
-
if (persistent && buildCacheEnabled) return await readFromDisk();
|
|
98
|
-
},
|
|
99
|
-
set: async (value) => {
|
|
100
|
-
cacheMap.set(id, value);
|
|
101
|
-
if (persistent && buildCacheEnabled) await writeToDisk(value);
|
|
102
|
-
},
|
|
103
|
-
clear: async () => {
|
|
104
|
-
cacheMap.delete(id);
|
|
105
|
-
try {
|
|
106
|
-
await unlink(filePath);
|
|
107
|
-
} catch {}
|
|
108
|
-
},
|
|
109
|
-
clearAll: async () => {
|
|
110
|
-
clearAllCache();
|
|
111
|
-
if (persistent && buildCacheEnabled) {
|
|
112
|
-
const base = namespace ? join(cacheDir, namespace) : cacheDir;
|
|
113
|
-
try {
|
|
114
|
-
await rm(base, {
|
|
115
|
-
recursive: true,
|
|
116
|
-
force: true
|
|
117
|
-
});
|
|
118
|
-
} catch {}
|
|
119
|
-
try {
|
|
120
|
-
await mkdir(base, { recursive: true });
|
|
121
|
-
} catch {}
|
|
122
|
-
}
|
|
123
|
-
},
|
|
124
|
-
isValid: async () => {
|
|
125
|
-
if (cacheMap.get(id) !== void 0) return true;
|
|
126
|
-
if (!persistent || !buildCacheEnabled) return false;
|
|
127
|
-
try {
|
|
128
|
-
const statValue = await stat(filePath).catch(() => void 0);
|
|
129
|
-
if (!statValue) return false;
|
|
130
|
-
if (typeof ttlMs === "number" && ttlMs > 0) {
|
|
131
|
-
if (Date.now() - statValue.mtimeMs > ttlMs) return false;
|
|
132
|
-
}
|
|
133
|
-
let raw = await readFile(filePath);
|
|
134
|
-
const flag = raw[0];
|
|
135
|
-
raw = raw.subarray(1);
|
|
136
|
-
const maybeObj = deserialize(flag === 1 ? gunzipSync(raw) : raw);
|
|
137
|
-
if (!!maybeObj && typeof maybeObj === "object" && typeof maybeObj.version === "string" && typeof maybeObj.timestamp === "number" && Object.hasOwn(maybeObj, "data")) {
|
|
138
|
-
const entry = maybeObj;
|
|
139
|
-
if (entry.version !== packageJson.version) return false;
|
|
140
|
-
if (typeof maxTimeMs === "number" && maxTimeMs > 0) {
|
|
141
|
-
if (Date.now() - entry.timestamp > maxTimeMs) return false;
|
|
142
|
-
}
|
|
143
|
-
return true;
|
|
144
|
-
}
|
|
145
|
-
if (typeof maxTimeMs === "number" && maxTimeMs > 0) {
|
|
146
|
-
if (Date.now() - statValue.mtimeMs > maxTimeMs) return false;
|
|
147
|
-
}
|
|
148
|
-
return true;
|
|
149
|
-
} catch {
|
|
150
|
-
return false;
|
|
151
|
-
}
|
|
152
|
-
},
|
|
153
|
-
id,
|
|
154
|
-
filePath
|
|
155
|
-
};
|
|
156
|
-
};
|
|
157
|
-
|
|
158
|
-
//#endregion
|
|
159
|
-
export { cacheDisk };
|
|
1
|
+
import{clearAllCache as e,computeKeyId as t}from"./cacheMemory.mjs";import{dirname as n,join as r}from"node:path";import i from"@intlayer/types/package.json"with{type:"json"};import{mkdir as a,readFile as o,rename as s,rm as c,stat as l,unlink as u,writeFile as d}from"node:fs/promises";import{deserialize as f,serialize as p}from"node:v8";import{gunzipSync as m,gzipSync as h}from"node:zlib";const g={compress:!0},_=async e=>{await a(e,{recursive:!0})},v=async(e,t)=>{let n=`${e}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;await d(n,t),await s(n,e)},y=(e,t)=>t===!0||t!==!1&&e.byteLength>1024,b=(e,t,n)=>r(e,n?r(n,t):t),x=new Map,S=(s,d,S)=>{let{cacheDir:C}=s.system,w=s.build.cache??!0,T=S?.persistent===!0||S?.persistent===void 0&&w,{compress:E,ttlMs:D,maxTimeMs:O,namespace:k}={...g,...S},A=t(d),j=b(C,A,k),M=async()=>{try{let e=await l(j).catch(()=>void 0);if(!e||typeof D==`number`&&D>0&&Date.now()-e.mtimeMs>D)return;let t=await o(j),n=t[0];t=t.subarray(1);let r=f(n===1?m(t):t),a,s=r;if(s&&typeof s==`object`&&typeof s.version==`string`&&typeof s.timestamp==`number`&&Object.hasOwn(s,`data`)){let e=s;if(e.version!==i.version){try{await u(j)}catch{}return}if(typeof O==`number`&&O>0&&Date.now()-e.timestamp>O){try{await u(j)}catch{}return}a=e.data}else{if(typeof O==`number`&&O>0&&Date.now()-e.mtimeMs>O){try{await u(j)}catch{}return}a=r}return x.set(A,a),a}catch{return}},N=async e=>{try{await _(n(j));let t={version:i.version,timestamp:Date.now(),data:e},r=Buffer.from(p(t)),a=y(r,E)?h(r):r;await v(j,Buffer.concat([Buffer.from([a===r?0:1]),a]))}catch{}};return{get:async()=>{let e=x.get(A);if(e!==void 0)return e;if(T&&w)return await M()},set:async e=>{x.set(A,e),T&&w&&await N(e)},clear:async()=>{x.delete(A);try{await u(j)}catch{}},clearAll:async()=>{if(e(),T&&w){let e=k?r(C,k):C;try{await c(e,{recursive:!0,force:!0})}catch{}try{await a(e,{recursive:!0})}catch{}}},isValid:async()=>{if(x.get(A)!==void 0)return!0;if(!T||!w)return!1;try{let e=await l(j).catch(()=>void 0);if(!e||typeof D==`number`&&D>0&&Date.now()-e.mtimeMs>D)return!1;let t=await o(j),n=t[0];t=t.subarray(1);let r=f(n===1?m(t):t);if(r&&typeof r==`object`&&typeof r.version==`string`&&typeof r.timestamp==`number`&&Object.hasOwn(r,`data`)){let e=r;return!(e.version!==i.version||typeof O==`number`&&O>0&&Date.now()-e.timestamp>O)}return!(typeof O==`number`&&O>0&&Date.now()-e.mtimeMs>O)}catch{return!1}},id:A,filePath:j}};export{S as cacheDisk};
|
|
160
2
|
//# sourceMappingURL=cacheDisk.mjs.map
|
|
@@ -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 { dirname, join } from 'node:path';\nimport { deserialize, serialize } from 'node:v8';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport type { IntlayerConfig } from '@intlayer/types';\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 (file: string, data: Buffer) => {\n const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n await writeFile(tmp, data);\n await rename(tmp, file);\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 } = 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);\n } catch {\n // swallow disk errors for cache writes\n }\n };\n\n return {\n /** In-memory first, then disk (if enabled), otherwise undefined. */\n get: async <T>(): Promise<T | undefined> => {\n const mem = cacheMap.get(id);\n\n if (mem !== undefined) return mem as T;\n\n if (persistent && buildCacheEnabled) {\n return (await readFromDisk()) as T | undefined;\n }\n return undefined;\n },\n /** Sets in-memory (always) and persists to disk if enabled. */\n set: async (value: unknown): Promise<void> => {\n cacheMap.set(id, value);\n\n if (persistent && buildCacheEnabled) {\n await writeToDisk(value);\n }\n },\n /** Clears only this entry from memory and disk. */\n clear: async (): Promise<void> => {\n cacheMap.delete(id);\n\n try {\n await unlink(filePath);\n } catch {}\n },\n /** Clears ALL cached entries (memory Map and entire cacheDir namespace if persistent). */\n clearAll: async (): Promise<void> => {\n clearAllCache();\n if (persistent && buildCacheEnabled) {\n // remove only the current namespace (if provided), else the root dir\n const base = namespace ? join(cacheDir, namespace) : cacheDir;\n\n try {\n await rm(base, { recursive: true, force: true });\n } catch {}\n\n try {\n await mkdir(base, { recursive: true });\n } catch {}\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n isValid: async (): Promise<boolean> => {\n const cachedValue = cacheMap.get(id);\n if (cachedValue !== undefined) return true;\n\n // If persistence is disabled or build cache disabled, only memory can be valid\n if (!persistent || !buildCacheEnabled) return false;\n\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n if (!statValue) return false;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return false;\n }\n\n let raw = await readFile(filePath);\n const flag = raw[0];\n raw = raw.subarray(1);\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof maybeObj.version === 'string' &&\n typeof maybeObj.timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n if (entry.version !== configPackageJson.version) return false;\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) return false;\n }\n return true;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) return false;\n }\n return true;\n } catch {\n return false;\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n id,\n /** Expose the absolute file path for debugging. */\n filePath,\n };\n};\n"],"mappings":";;;;;;;;AA2CA,MAAM,WAA0D,EAC9D,UAAU,MACX;AAED,MAAM,YAAY,OAAO,QAAgB;AACvC,OAAM,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC;;AAGvC,MAAM,kBAAkB,OAAO,MAAc,SAAiB;CAC5D,MAAM,MAAM,GAAG,KAAK,OAAO,QAAQ,IAAI,GAAG,KAAK,QAAQ,CAAC,SAAS,G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AM;MAAE,WAAW;MAAM,OAAO;MAAM,CAAC;YAC1C;AAER,QAAI;AACF,WAAM,MAAM,MAAM,EAAE,WAAW,MAAM,CAAC;YAChC;;;EAIZ,SAAS,YAA8B;AAErC,OADoB,SAAS,IAAI,GAAG,KAChB,OAAW,QAAO;AAGtC,OAAI,CAAC,cAAc,CAAC,kBAAmB,QAAO;AAE9C,OAAI;IACF,MAAM,YAAY,MAAM,KAAK,SAAS,CAAC,YAAY,OAAU;AAC7D,QAAI,CAAC,UAAW,QAAO;AAEvB,QAAI,OAAO,UAAU,YAAY,QAAQ,GAEvC;SADY,KAAK,KAAK,GAAG,UAAU,UACzB,MAAO,QAAO;;IAG1B,IAAI,MAAM,MAAM,SAAS,SAAS;IAClC,MAAM,OAAO,IAAI;AACjB,UAAM,IAAI,SAAS,EAAE;IAIrB,MAAM,WAFe,YADL,SAAS,IAAO,WAAW,IAAI,GAAG,IACT;AAUzC,QANE,CAAC,CAAC,YACF,OAAO,aAAa,YACpB,OAAO,SAAS,YAAY,YAC5B,OAAO,SAAS,cAAc,YAC9B,OAAO,OAAO,UAAU,OAAO,EAEjB;KACd,MAAM,QAAQ;AACd,SAAI,MAAM,YAAYA,YAAkB,QAAS,QAAO;AAExD,SAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;UADY,KAAK,KAAK,GAAG,MAAM,YACrB,UAAW,QAAO;;AAE9B,YAAO;;AAGT,QAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;SADY,KAAK,KAAK,GAAG,UAAU,UACzB,UAAW,QAAO;;AAE9B,WAAO;WACD;AACN,WAAO;;;EAIX;EAEA;EACD"}
|
|
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 { dirname, join } from 'node:path';\nimport { deserialize, serialize } from 'node:v8';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport type { IntlayerConfig } from '@intlayer/types';\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 (file: string, data: Buffer) => {\n const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n await writeFile(tmp, data);\n await rename(tmp, file);\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 } = 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);\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":"yYA2CA,MAAM,EAA0D,CAC9D,SAAU,GACX,CAEK,EAAY,KAAO,IAAgB,CACvC,MAAM,EAAM,EAAK,CAAE,UAAW,GAAM,CAAC,EAGjC,EAAkB,MAAO,EAAc,IAAiB,CAC5D,IAAM,EAAM,GAAG,EAAK,OAAO,QAAQ,IAAI,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,GAC7E,MAAM,EAAU,EAAK,EAAK,CAC1B,MAAM,EAAO,EAAK,EAAK,EAGnB,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,YAAa,EAAe,OAC9B,EAAoB,EAAe,MAAM,OAAS,GAClD,EACJ,GAAS,aAAe,IAChB,GAAS,aAAe,QAAe,EAE3C,CAAE,WAAU,QAAO,YAAW,aAAc,CAChD,GAAG,EACH,GAAG,EACJ,CAGK,EAAK,EAAa,EAAK,CACvB,EAAW,EAAU,EAAU,EAAI,EA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