@intlayer/config 9.2.0 → 9.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -24
- package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -2
- package/dist/cjs/bundle/index.cjs.map +1 -1
- package/dist/cjs/callers/base.cjs +0 -1
- package/dist/cjs/callers/base.cjs.map +1 -1
- package/dist/cjs/callers/compat/i18next.cjs +0 -1
- package/dist/cjs/callers/compat/i18next.cjs.map +1 -1
- package/dist/cjs/callers/compat/lingui.cjs +0 -1
- package/dist/cjs/callers/compat/lingui.cjs.map +1 -1
- package/dist/cjs/callers/compat/nextIntl.cjs +0 -1
- package/dist/cjs/callers/compat/nextIntl.cjs.map +1 -1
- package/dist/cjs/callers/compat/reactI18next.cjs +0 -1
- package/dist/cjs/callers/compat/reactI18next.cjs.map +1 -1
- package/dist/cjs/callers/compat/reactIntl.cjs +0 -1
- package/dist/cjs/callers/compat/reactIntl.cjs.map +1 -1
- package/dist/cjs/callers/compat/useIntl.cjs +0 -1
- package/dist/cjs/callers/compat/useIntl.cjs.map +1 -1
- package/dist/cjs/callers/compat/vueI18n.cjs +0 -1
- package/dist/cjs/callers/compat/vueI18n.cjs.map +1 -1
- package/dist/cjs/callers/transform.cjs +0 -1
- package/dist/cjs/callers/transform.cjs.map +1 -1
- package/dist/cjs/colors.cjs +0 -1
- package/dist/cjs/colors.cjs.map +1 -1
- package/dist/cjs/configFile/buildBrowserConfiguration.cjs +10 -11
- package/dist/cjs/configFile/buildBrowserConfiguration.cjs.map +1 -1
- package/dist/cjs/configFile/buildConfigurationFields.cjs +2 -7
- package/dist/cjs/configFile/buildConfigurationFields.cjs.map +1 -1
- package/dist/cjs/configFile/getConfiguration.cjs +5 -12
- package/dist/cjs/configFile/getConfiguration.cjs.map +1 -1
- package/dist/cjs/configFile/searchConfigurationFile.cjs.map +1 -1
- package/dist/cjs/defaultValues/analytics.cjs +0 -1
- package/dist/cjs/defaultValues/analytics.cjs.map +1 -1
- package/dist/cjs/defaultValues/build.cjs +0 -1
- package/dist/cjs/defaultValues/build.cjs.map +1 -1
- package/dist/cjs/defaultValues/compiler.cjs +0 -1
- package/dist/cjs/defaultValues/compiler.cjs.map +1 -1
- package/dist/cjs/defaultValues/content.cjs +0 -1
- package/dist/cjs/defaultValues/content.cjs.map +1 -1
- package/dist/cjs/defaultValues/dictionary.cjs +0 -1
- package/dist/cjs/defaultValues/dictionary.cjs.map +1 -1
- package/dist/cjs/defaultValues/editor.cjs +0 -1
- package/dist/cjs/defaultValues/editor.cjs.map +1 -1
- package/dist/cjs/defaultValues/internationalization.cjs +0 -1
- package/dist/cjs/defaultValues/internationalization.cjs.map +1 -1
- package/dist/cjs/defaultValues/routing.cjs +0 -1
- package/dist/cjs/defaultValues/routing.cjs.map +1 -1
- package/dist/cjs/defaultValues/system.cjs +0 -1
- package/dist/cjs/defaultValues/system.cjs.map +1 -1
- package/dist/cjs/envVars/envVars.cjs +23 -1
- package/dist/cjs/envVars/envVars.cjs.map +1 -1
- package/dist/cjs/envVars/index.cjs +1 -0
- package/dist/cjs/loadEnvFile.cjs +8 -6
- package/dist/cjs/loadEnvFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/bundleFile.cjs +4 -2
- package/dist/cjs/loadExternalFile/bundleFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/bundleJSFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/loadExternalFile.cjs +4 -2
- package/dist/cjs/loadExternalFile/loadExternalFile.cjs.map +1 -1
- package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs +4 -2
- package/dist/cjs/loadExternalFile/transpileTSToCJS.cjs.map +1 -1
- package/dist/cjs/utils/ESMxCJSHelpers.cjs.map +1 -1
- package/dist/cjs/utils/alias.cjs +41 -6
- package/dist/cjs/utils/alias.cjs.map +1 -1
- package/dist/cjs/utils/builtConfigKeys.cjs +0 -1
- package/dist/cjs/utils/builtConfigKeys.cjs.map +1 -1
- package/dist/cjs/utils/cacheDisk.cjs +4 -2
- package/dist/cjs/utils/cacheDisk.cjs.map +1 -1
- package/dist/cjs/utils/cacheMemory.cjs.map +1 -1
- package/dist/cjs/utils/compareVersions.cjs +0 -1
- package/dist/cjs/utils/compareVersions.cjs.map +1 -1
- package/dist/cjs/utils/extractErrorMessage.cjs +0 -1
- package/dist/cjs/utils/extractErrorMessage.cjs.map +1 -1
- package/dist/cjs/utils/getDictionarySelectorUsage.cjs +0 -1
- package/dist/cjs/utils/getDictionarySelectorUsage.cjs.map +1 -1
- package/dist/cjs/utils/getExtension.cjs +0 -1
- package/dist/cjs/utils/getExtension.cjs.map +1 -1
- package/dist/cjs/utils/getPackageJsonPath.cjs.map +1 -1
- package/dist/cjs/utils/getStorageAttributes.cjs +1 -1
- package/dist/cjs/utils/getStorageAttributes.cjs.map +1 -1
- package/dist/cjs/utils/normalizePath.cjs +0 -1
- package/dist/cjs/utils/normalizePath.cjs.map +1 -1
- package/dist/cjs/utils/parseFilePathPattern.cjs +0 -1
- package/dist/cjs/utils/parseFilePathPattern.cjs.map +1 -1
- package/dist/cjs/utils/pathSecurity.cjs.map +1 -1
- package/dist/cjs/utils/retryManager.cjs +12 -1
- package/dist/cjs/utils/retryManager.cjs.map +1 -1
- package/dist/cjs/utils/setIntlayerIdentifier.cjs +0 -1
- package/dist/cjs/utils/setIntlayerIdentifier.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs +0 -1
- package/dist/cjs/utils/stringFormatter/camelCaseToKebabCase.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs +0 -1
- package/dist/cjs/utils/stringFormatter/camelCaseToSentence.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs +0 -1
- package/dist/cjs/utils/stringFormatter/kebabCaseToCamelCase.cjs.map +1 -1
- package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs +0 -1
- package/dist/cjs/utils/stringFormatter/toLowerCamelCase.cjs.map +1 -1
- package/dist/esm/configFile/buildBrowserConfiguration.mjs +10 -11
- package/dist/esm/configFile/buildBrowserConfiguration.mjs.map +1 -1
- package/dist/esm/configFile/buildConfigurationFields.mjs +2 -7
- package/dist/esm/configFile/buildConfigurationFields.mjs.map +1 -1
- package/dist/esm/configFile/getConfiguration.mjs +5 -12
- package/dist/esm/configFile/getConfiguration.mjs.map +1 -1
- package/dist/esm/envVars/envVars.mjs +23 -1
- package/dist/esm/envVars/envVars.mjs.map +1 -1
- package/dist/esm/envVars/index.mjs +2 -2
- package/dist/esm/loadEnvFile.mjs +8 -6
- package/dist/esm/loadEnvFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/bundleFile.mjs +4 -2
- package/dist/esm/loadExternalFile/bundleFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/loadExternalFile.mjs +4 -2
- package/dist/esm/loadExternalFile/loadExternalFile.mjs.map +1 -1
- package/dist/esm/loadExternalFile/transpileTSToCJS.mjs +4 -2
- package/dist/esm/loadExternalFile/transpileTSToCJS.mjs.map +1 -1
- package/dist/esm/utils/ESMxCJSHelpers.mjs.map +1 -1
- package/dist/esm/utils/alias.mjs +41 -6
- package/dist/esm/utils/alias.mjs.map +1 -1
- package/dist/esm/utils/cacheDisk.mjs +4 -2
- package/dist/esm/utils/cacheDisk.mjs.map +1 -1
- package/dist/esm/utils/getStorageAttributes.mjs +1 -1
- package/dist/esm/utils/getStorageAttributes.mjs.map +1 -1
- package/dist/esm/utils/retryManager.mjs +12 -1
- package/dist/esm/utils/retryManager.mjs.map +1 -1
- package/dist/types/configFile/buildBrowserConfiguration.d.ts +8 -9
- package/dist/types/configFile/buildBrowserConfiguration.d.ts.map +1 -1
- package/dist/types/configFile/buildConfigurationFields.d.ts +1 -6
- package/dist/types/configFile/buildConfigurationFields.d.ts.map +1 -1
- package/dist/types/configFile/getConfiguration.d.ts.map +1 -1
- package/dist/types/envVars/envVars.d.ts +23 -1
- package/dist/types/envVars/envVars.d.ts.map +1 -1
- package/dist/types/envVars/index.d.ts +2 -2
- package/dist/types/loadExternalFile/bundleJSFile.d.ts +1 -0
- package/dist/types/loadExternalFile/bundleJSFile.d.ts.map +1 -1
- package/dist/types/utils/retryManager.d.ts +7 -1
- package/dist/types/utils/retryManager.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleFile.cjs","names":[],"sources":["../../../src/loadExternalFile/bundleFile.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Loader,\n type Plugin,\n} from 'esbuild';\n\nexport type ESBuildPlugin = Plugin;\n\nexport const getLoader = (extension: string): Loader => {\n switch (extension) {\n case '.js':\n return 'js';\n case '.jsx':\n return 'jsx';\n case '.mjs':\n return 'js';\n case '.ts':\n return 'ts';\n case '.tsx':\n return 'tsx';\n case '.cjs':\n return 'js';\n case '.json':\n return 'json';\n case '.md':\n return 'text';\n case '.mdx':\n return 'text';\n default:\n return 'js';\n }\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node16',\n platform: 'neutral',\n write: false,\n packages: 'bundle',\n external: ['esbuild'],\n bundle: true,\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const bundleFileSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const bundleFile = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":";;;;;;AAaA,MAAa,aAAa,cAA8B;CACtD,QAAQ,WAAR;EACE,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;CACA,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,UAAU,CAAC,SAAS;CACpB,QAAQ;CACR,QAAQ,EACN,mBAAmB,KAAK,
|
|
1
|
+
{"version":3,"file":"bundleFile.cjs","names":["pathToFileURL","extname","buildSync","dirname","build"],"sources":["../../../src/loadExternalFile/bundleFile.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Loader,\n type Plugin,\n} from 'esbuild';\n\nexport type ESBuildPlugin = Plugin;\n\nexport const getLoader = (extension: string): Loader => {\n switch (extension) {\n case '.js':\n return 'js';\n case '.jsx':\n return 'jsx';\n case '.mjs':\n return 'js';\n case '.ts':\n return 'ts';\n case '.tsx':\n return 'tsx';\n case '.cjs':\n return 'js';\n case '.json':\n return 'json';\n case '.md':\n return 'text';\n case '.mdx':\n return 'text';\n default:\n return 'js';\n }\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node16',\n platform: 'neutral',\n write: false,\n packages: 'bundle',\n external: ['esbuild'],\n bundle: true,\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n },\n});\n\nexport const bundleFileSync = (\n code: string,\n filePath: string,\n options?: BuildOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = buildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n\nexport const bundleFile = async (\n code: string,\n filePath: string,\n options?: BuildOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const moduleResult: BuildResult = await build({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...options,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0].text;\n\n return moduleResultString;\n};\n"],"mappings":";;;;;;AAaA,MAAa,aAAa,cAA8B;CACtD,QAAQ,WAAR;EACE,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;CACA,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,UAAU,CAAC,SAAS;CACpB,QAAQ;CACR,QAAQ,EACN,mBAAmB,KAAK,cAAUA,wBAAc,QAAQ,CAAC,CAAC,IAAI,EAChE;AACF;AAEA,MAAa,kBACX,MACA,UACA,YACuB;CACvB,MAAM,gBAAYC,mBAAQ,QAAQ;CAClC,MAAM,SAAS,UAAU,SAAS;CAelC,WAbkCC,mBAAU;EAC1C,OAAO;GACL,UAAU;GACV;GACA,gBAAYC,mBAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAEsC,CAAC,CAAC,cAAc,EAAE,CAAC;AAG3D;AAEA,MAAa,aAAa,OACxB,MACA,UACA,YACgC;CAChC,MAAM,gBAAYF,mBAAQ,QAAQ;CAClC,MAAM,SAAS,UAAU,SAAS;CAelC,QAF2B,UAXaG,eAAM;EAC5C,OAAO;GACL,UAAU;GACV;GACA,gBAAYD,mBAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC,EAEsC,CAAC,cAAc,EAAE,CAAC;AAG3D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleJSFile.cjs","names":[],"sources":["../../../src/loadExternalFile/bundleJSFile.ts"],"sourcesContent":["import { type BuildOptions, build } from 'esbuild';\n\nconst commonBuildOptions = {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n target: 'es2019',\n sourcemap: false,\n logLevel: 'silent',\n write: true,\n // Bundle relative/local files, but keep bare module imports external\n packages: 'external',\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} as const;\n\nexport const bundleJSFile = async (buildOptions: BuildOptions) =>\n await build({\n ...commonBuildOptions,\n ...buildOptions,\n });\n"],"mappings":";;;;AAEA,MAAM,qBAAqB;CACzB,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,WAAW;CACX,UAAU;CACV,OAAO;CAEP,UAAU;CACV,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;AACF;AAEA,MAAa,eAAe,OAAO,iBACjC,
|
|
1
|
+
{"version":3,"file":"bundleJSFile.cjs","names":["build"],"sources":["../../../src/loadExternalFile/bundleJSFile.ts"],"sourcesContent":["import { type BuildOptions, build } from 'esbuild';\n\nconst commonBuildOptions = {\n bundle: true,\n format: 'cjs',\n platform: 'node',\n target: 'es2019',\n sourcemap: false,\n logLevel: 'silent',\n write: true,\n // Bundle relative/local files, but keep bare module imports external\n packages: 'external',\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} as const;\n\nexport const bundleJSFile = async (buildOptions: BuildOptions) =>\n await build({\n ...commonBuildOptions,\n ...buildOptions,\n });\n"],"mappings":";;;;AAEA,MAAM,qBAAqB;CACzB,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,WAAW;CACX,UAAU;CACV,OAAO;CAEP,UAAU;CACV,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;AACF;AAEA,MAAa,eAAe,OAAO,iBACjC,UAAMA,eAAM;CACV,GAAG;CACH,GAAG;AACL,CAAC"}
|
|
@@ -20,7 +20,8 @@ const loadExternalFileSync = (filePath, options) => {
|
|
|
20
20
|
const fileExtension = (0, node_path.extname)(filePath) || ".json";
|
|
21
21
|
try {
|
|
22
22
|
if (fileExtension === ".json" || fileExtension === ".json5" || fileExtension === ".jsonc") return parseJSON5((0, node_fs.readFileSync)(filePath, "utf-8"));
|
|
23
|
-
const
|
|
23
|
+
const code = (0, node_fs.readFileSync)(filePath, "utf-8");
|
|
24
|
+
const moduleResultString = require_loadExternalFile_transpileTSToCJS.transpileTSToCJSSync(code, filePath, options?.buildOptions);
|
|
24
25
|
if (!moduleResultString) {
|
|
25
26
|
require_logger.logger("File could not be loaded.", { level: "error" });
|
|
26
27
|
return;
|
|
@@ -70,7 +71,8 @@ const loadExternalFile = async (filePath, options) => {
|
|
|
70
71
|
const fileContent = await (0, node_fs_promises.readFile)(filePath, "utf-8");
|
|
71
72
|
return parseJSON5(fileContent);
|
|
72
73
|
}
|
|
73
|
-
const
|
|
74
|
+
const code = await (0, node_fs_promises.readFile)(filePath, "utf-8");
|
|
75
|
+
const moduleResultString = await require_loadExternalFile_transpileTSToCJS.transpileTSToCJS(code, filePath, options?.buildOptions);
|
|
74
76
|
if (!moduleResultString) {
|
|
75
77
|
require_logger.logger("File could not be loaded.", { level: "error" });
|
|
76
78
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadExternalFile.cjs","names":["JSON5","transpileTSToCJSSync","parseFileContent","transpileTSToCJS","colorizePath"],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // fully restores the globals before returning.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const previousValues: Record<string, unknown> = {};\n const previouslyPresent: Record<string, boolean> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n previouslyPresent[key] = key in globalVars;\n previousValues[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n // `in` check (not `!== undefined`) so a global that legitimately held\n // `undefined` is restored rather than deleted.\n if (previouslyPresent[key]) {\n globalVars[key] = previousValues[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,aAAaA,cAAM,SAAUA,cAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,
|
|
1
|
+
{"version":3,"file":"loadExternalFile.cjs","names":["JSON5","extname","readFileSync","transpileTSToCJSSync","parseFileContent","readFile","transpileTSToCJS","colorizePath"],"sources":["../../../src/loadExternalFile/loadExternalFile.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport JSON5 from 'json5';\nimport { colorizePath, logger } from '../logger';\nimport {\n parseFileContent,\n type SandBoxContextOptions,\n} from './parseFileContent';\nimport {\n type TranspileOptions,\n transpileTSToCJS,\n transpileTSToCJSSync,\n} from './transpileTSToCJS';\n\n// CJS MJS cross usage\nconst parseJSON5 = JSON5.parse || (JSON5 as any).default?.parse;\n\nexport type LoadExternalFileOptions = {\n configuration?: IntlayerConfig;\n buildOptions?: TranspileOptions;\n logError?: boolean;\n /**\n * Key-value pairs to temporarily set on the main Node.js `globalThis` for the\n * synchronous duration of `parseFileContent` / `runInNewContext`. External modules\n * loaded via `require()` inside the VM (e.g. `@intlayer/core`'s `file()` helper)\n * run in the main context and read from the real `globalThis`, not the VM sandbox.\n * Values are restored (or deleted) after `runInNewContext` returns.\n */\n preloadGlobals?: Record<string, unknown>;\n} & SandBoxContextOptions;\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFileSync = (\n filePath: string,\n options?: LoadExternalFileOptions\n): any | undefined => {\n const fileExtension = extname(filePath) || '.json';\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Assume JSON\n return parseJSON5(readFileSync(filePath, 'utf-8'));\n }\n\n // Rest is JS, MJS or TS\n const code = readFileSync(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = transpileTSToCJSSync(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // fully restores the globals before returning.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${filePath}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n};\n\nconst withPreloadedGlobals = <T>(\n globals: Record<string, unknown> | undefined,\n fn: () => T\n): T => {\n if (!globals) return fn();\n\n const globalVars = globalThis as Record<string, unknown>;\n const previousValues: Record<string, unknown> = {};\n const previouslyPresent: Record<string, boolean> = {};\n\n for (const [key, value] of Object.entries(globals)) {\n previouslyPresent[key] = key in globalVars;\n previousValues[key] = globalVars[key];\n globalVars[key] = value;\n }\n\n try {\n return fn();\n } finally {\n for (const key of Object.keys(globals)) {\n // `in` check (not `!== undefined`) so a global that legitimately held\n // `undefined` is restored rather than deleted.\n if (previouslyPresent[key]) {\n globalVars[key] = previousValues[key];\n } else {\n delete globalVars[key];\n }\n }\n }\n};\n\n/**\n * Load the content declaration from the given path\n *\n * Accepts JSON, JS, MJS and TS files as configuration\n */\nexport const loadExternalFile = async (\n filePath: string,\n options?: LoadExternalFileOptions\n): Promise<any | undefined> => {\n const fileExtension = extname(filePath);\n\n try {\n if (\n fileExtension === '.json' ||\n fileExtension === '.json5' ||\n fileExtension === '.jsonc'\n ) {\n // Remove cache to force getting fresh content\n const fileContent = await readFile(filePath, 'utf-8');\n return parseJSON5(fileContent);\n }\n\n // Rest is JS, MJS or TS\n const code = await readFile(filePath, 'utf-8');\n\n const moduleResultString: string | undefined = await transpileTSToCJS(\n code,\n filePath,\n options?.buildOptions\n );\n\n if (!moduleResultString) {\n logger('File could not be loaded.', { level: 'error' });\n return undefined;\n }\n\n // parseFileContent/runInNewContext is synchronous, so withPreloadedGlobals\n // has no interleaving risk even when multiple files are processed concurrently.\n const fileContent = withPreloadedGlobals(options?.preloadGlobals, () =>\n parseFileContent(moduleResultString, {\n projectRequire: options?.projectRequire,\n envVarOptions: options?.envVarOptions,\n additionalEnvVars: options?.additionalEnvVars,\n mocks: options?.mocks,\n aliases: options?.aliases,\n })\n );\n\n if (typeof fileContent === 'undefined') {\n logger(`File could not be loaded. Path : ${colorizePath(filePath)}`);\n return undefined;\n }\n\n return fileContent;\n } catch (error) {\n if (options?.logError ?? true) {\n logger(\n [\n `Error: ${(error as Error).message} - `,\n JSON.stringify((error as Error).stack, null, 2),\n ],\n {\n level: 'error',\n }\n );\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAM,aAAaA,cAAM,SAAUA,cAAc,SAAS;;;;;;AAqB1D,MAAa,wBACX,UACA,YACoB;CACpB,MAAM,oBAAgBC,mBAAQ,QAAQ,KAAK;CAE3C,IAAI;EACF,IACE,kBAAkB,WAClB,kBAAkB,YAClB,kBAAkB,UAGlB,OAAO,eAAWC,sBAAa,UAAU,OAAO,CAAC;EAInD,MAAM,WAAOA,sBAAa,UAAU,OAAO;EAE3C,MAAM,qBAAyCC,+DAC7C,M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MACA,UACA,SAAS,YACX;EAEA,IAAI,CAAC,oBAAoB;GACvB,sBAAO,6BAA6B,EAAE,OAAO,QAAQ,CAAC;GACtD;EACF;EAIA,MAAM,cAAc,qBAAqB,SAAS,sBAChDF,2DAAiB,oBAAoB;GACnC,gBAAgB,SAAS;GACzB,eAAe,SAAS;GACxB,mBAAmB,SAAS;GAC5B,OAAO,SAAS;GAChB,SAAS,SAAS;EACpB,CAAC,CACH;EAEA,IAAI,OAAO,gBAAgB,aAAa;GACtC,sBAAO,oCAAoCG,4BAAa,QAAQ,GAAG;GACnE;EACF;EAEA,OAAO;CACT,SAAS,OAAO;EACd,IAAI,SAAS,YAAY,MACvB,sBACE,CACE,UAAW,MAAgB,QAAQ,MACnC,KAAK,UAAW,MAAgB,OAAO,MAAM,CAAC,CAChD,GACA,EACE,OAAO,QACT,CACF;CAEJ;AACF"}
|
|
@@ -118,7 +118,8 @@ const clearTranspileCache = () => {
|
|
|
118
118
|
tsConfigPathCache.clear();
|
|
119
119
|
};
|
|
120
120
|
const transpileTSToCJSSync = (code, filePath, options) => {
|
|
121
|
-
const
|
|
121
|
+
const extension = (0, node_path.extname)(filePath);
|
|
122
|
+
const loader = require_loadExternalFile_bundleFile.getLoader(extension);
|
|
122
123
|
const { esbuildInstance, ...buildOptions } = options ?? {};
|
|
123
124
|
const codeHash = require_utils_cacheMemory.computeKeyId([code]);
|
|
124
125
|
const optionsKey = require_utils_cacheMemory.computeKeyId([buildOptions]);
|
|
@@ -159,7 +160,8 @@ const transpileTSToCJSSync = (code, filePath, options) => {
|
|
|
159
160
|
return moduleResultString;
|
|
160
161
|
};
|
|
161
162
|
const transpileTSToCJS = async (code, filePath, options) => {
|
|
162
|
-
const
|
|
163
|
+
const extension = (0, node_path.extname)(filePath);
|
|
164
|
+
const loader = require_loadExternalFile_bundleFile.getLoader(extension);
|
|
163
165
|
const { esbuildInstance, ...buildOptions } = options ?? {};
|
|
164
166
|
const codeHash = require_utils_cacheMemory.computeKeyId([code]);
|
|
165
167
|
const optionsKey = require_utils_cacheMemory.computeKeyId([buildOptions]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transpileTSToCJS.cjs","names":["getPackageJsonPath","getLoader","computeKeyId","buildSync","build"],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, extname, isAbsolute, join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Metafile,\n} from 'esbuild';\nimport { computeKeyId } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nexport type TranspileOptions = BuildOptions & {\n /**\n * Optional custom esbuild instance to use for transpilation.\n * Useful in environments (e.g. VS Code extensions) where the bundled\n * esbuild binary may not match the host platform.\n * When provided, its `buildSync`/`build` methods are used instead of\n * the ones imported from the `esbuild` package.\n */\n esbuildInstance?: typeof import('esbuild');\n};\n\n/**\n * Cache of resolved tsconfig paths keyed by the file's directory.\n * Avoids re-walking to package.json + existsSync on every transpilation.\n */\nconst tsConfigPathCache = new Map<string, string | undefined>();\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const fileDirectory = dirname(filePath);\n\n if (tsConfigPathCache.has(fileDirectory)) {\n return tsConfigPathCache.get(fileDirectory);\n }\n\n let resolvedPath: string | undefined;\n try {\n const tsconfigPath = join(\n getPackageJsonPath(fileDirectory).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n resolvedPath = existsSync(tsconfigPath) ? tsconfigPath : undefined;\n } catch {\n // No package.json found up the tree — transpile without a tsconfig\n resolvedPath = undefined;\n }\n\n tsConfigPathCache.set(fileDirectory, resolvedPath);\n\n return resolvedPath;\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n // The metafile lists every bundled input, which the transpile cache uses to\n // invalidate when an imported file changes (the entry itself is keyed by hash).\n metafile: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n 'import.meta.env': 'process.env',\n },\n});\n\n/** Fingerprint of a bundled input file, used to detect changes without re-reading it. */\ntype TranspileCacheInput = {\n path: string;\n mtimeMs: number;\n size: number;\n};\n\ntype TranspileCacheEntry = {\n /** Hash of the entry file's source code. */\n codeHash: string;\n /** Hash of the build options, so different option sets don't collide. */\n optionsKey: string;\n /** The transpiled CJS output. */\n output: string;\n /** Fingerprints of every non-entry input bundled into the output. */\n inputs: TranspileCacheInput[];\n};\n\n/**\n * In-memory cache of transpiled outputs keyed by entry file path (one entry\n * per file, so re-transpilations replace rather than accumulate).\n * The entry file is validated by content hash; bundled relative imports are\n * validated by mtime + size so an edited dependency invalidates the cache.\n */\nconst transpileCache = new Map<string, TranspileCacheEntry>();\n\nconst isInputUnchanged = (input: TranspileCacheInput): boolean => {\n try {\n const stats = statSync(input.path);\n return stats.mtimeMs === input.mtimeMs && stats.size === input.size;\n } catch {\n // File removed or unreadable — treat as changed\n return false;\n }\n};\n\nconst getCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string\n): string | undefined => {\n const cacheEntry = transpileCache.get(filePath);\n\n if (!cacheEntry) return undefined;\n if (cacheEntry.codeHash !== codeHash) return undefined;\n if (cacheEntry.optionsKey !== optionsKey) return undefined;\n if (!cacheEntry.inputs.every(isInputUnchanged)) return undefined;\n\n return cacheEntry.output;\n};\n\n/**\n * Extracts the fingerprints of every bundled input from the esbuild metafile.\n * Returns `undefined` when an input cannot be fingerprinted (the result should\n * then not be cached, as invalidation would be unreliable).\n */\nconst getInputFingerprints = (\n metafile: Metafile | undefined,\n entryFilePath: string\n): TranspileCacheInput[] | undefined => {\n if (!metafile) return undefined;\n\n const resolvedEntryFilePath = resolve(entryFilePath);\n const inputs: TranspileCacheInput[] = [];\n\n for (const inputPath of Object.keys(metafile.inputs)) {\n // The entry itself is provided via stdin and validated by content hash.\n // esbuild labels it \"<stdin>\", or with the sourcefile path when set.\n if (inputPath === '<stdin>') continue;\n // Virtual modules from plugins (e.g. \"plugin:...\") cannot be fingerprinted\n if (inputPath.includes(':') && !isAbsolute(inputPath)) return undefined;\n\n const absoluteInputPath = isAbsolute(inputPath)\n ? inputPath\n : resolve(process.cwd(), inputPath);\n\n if (absoluteInputPath === resolvedEntryFilePath) continue;\n\n try {\n const stats = statSync(absoluteInputPath);\n inputs.push({\n path: absoluteInputPath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n });\n } catch {\n return undefined;\n }\n }\n\n return inputs;\n};\n\nconst setCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string,\n moduleResult: BuildResult,\n output: string\n): void => {\n const inputs = getInputFingerprints(moduleResult.metafile, filePath);\n\n // Without a usable metafile the cache cannot be invalidated reliably — skip\n if (!inputs) return;\n\n transpileCache.set(filePath, { codeHash, optionsKey, output, inputs });\n};\n\n/** Clears the in-memory transpilation cache (mainly for tests). */\nexport const clearTranspileCache = (): void => {\n transpileCache.clear();\n tsConfigPathCache.clear();\n};\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;\n\n // esbuild's worker thread service calls `new Worker(__filename, …)` on first use.\n // In Vite's SSR module runner the SSR-optimised chunk is ESM and __filename is\n // never declared (confirmed: accessing it throws ReferenceError, not undefined).\n // Because there is no local declaration the bare `__filename` lookup falls\n // through to globalThis, so we set it there to esbuild's own CJS entry-point –\n // the exact path esbuild would use if it were loaded in a normal CJS context.\n //\n // IMPORTANT: We save/restore the globals so this temporary shim does not leak\n // to other Vite plugins (e.g. `@vitejs/plugin-react-swc`) that check\n // `typeof __dirname !== \"undefined\"` to locate their own assets.\n const g = globalThis as Record<string, unknown>;\n const hadFilename = typeof g.__filename === 'string';\n const prevFilename = g.__filename;\n const prevDirname = g.__dirname;\n\n if (!hadFilename) {\n try {\n const _require = createRequire(import.meta.url);\n const esbuildEntry = _require.resolve('esbuild');\n g.__filename = esbuildEntry;\n g.__dirname = dirname(esbuildEntry);\n } catch {\n // Best-effort: if esbuild can't be resolved the caller's catch handles it\n }\n }\n\n let moduleResult: BuildResult;\n try {\n moduleResult = esbuildBuildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n } finally {\n // Always restore the previous values so the globals don't linger.\n if (!hadFilename) {\n if (prevFilename === undefined) {\n // biome-ignore lint/performance/noDelete: the global must be truly absent — assigning undefined would leave the key present and break `typeof __filename` checks in other tools\n delete g.__filename;\n } else {\n g.__filename = prevFilename;\n }\n if (prevDirname === undefined) {\n // biome-ignore lint/performance/noDelete: same as __filename above\n delete g.__dirname;\n } else {\n g.__dirname = prevDirname;\n }\n }\n }\n\n const moduleResultString = moduleResult!.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult!,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n // A one-shot build() releases its Go-side resources on completion and costs a\n // single service round-trip (context()+rebuild()+dispose() costs three).\n const esbuildBuild = esbuildInstance?.build ?? build;\n\n const moduleResult = await esbuildBuild({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath),\n sourcefile: filePath,\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,oCAAoB,IAAI,IAAgC;AAE9D,MAAM,mBAAmB,aAAyC;CAChE,MAAM,uCAAwB,QAAQ;CAEtC,IAAI,kBAAkB,IAAI,aAAa,GACrC,OAAO,kBAAkB,IAAI,aAAa;CAG5C,IAAI;CACJ,IAAI;EACF,MAAM,mCACJA,oDAAmB,aAAa,CAAC,CAAC,SAClC,eACF;EAGA,uCAA0B,YAAY,IAAI,eAAe;CAC3D,QAAQ;EAEN,eAAe;CACjB;CAEA,kBAAkB,IAAI,eAAe,YAAY;CAEjD,OAAO;AACT;AAEA,MAAM,4BAA4B,cAAoC;CACpE,QAAQ;EACN,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,QAAQ;CACV;CACA,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,OAAO;CACP,UAAU;CACV,QAAQ;CAGR,UAAU;CACV,UAAU,gBAAgB,QAAQ;CAClC,QAAQ;EACN,mBAAmB,KAA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WC,uCAAa,CAAC,IAAI,CAAC;CACpC,MAAM,aAAaA,uCAAa,CAAC,YAAY,CAAC;CAE9C,MAAM,eAAe,uBAAuB,UAAU,UAAU,UAAU;CAC1E,IAAI,OAAO,iBAAiB,UAAU,OAAO;CAM7C,MAAM,eAAe,OAFA,iBAAiB,SAASE,cAER,CAAC;EACtC,OAAO;GACL,UAAU;GACV;GACA,mCAAoB,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC;CAED,MAAM,qBAAqB,aAAa,cAAc,EAAE,EAAE;CAE1D,IAAI,OAAO,uBAAuB,UAChC,uBACE,UACA,UACA,YACA,cACA,kBACF;CAGF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"transpileTSToCJS.cjs","names":["dirname","join","getPackageJsonPath","existsSync","pathToFileURL","statSync","resolve","isAbsolute","extname","getLoader","computeKeyId","buildSync","createRequire","build"],"sources":["../../../src/loadExternalFile/transpileTSToCJS.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, extname, isAbsolute, join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n type BuildOptions,\n type BuildResult,\n build,\n buildSync,\n type Metafile,\n} from 'esbuild';\nimport { computeKeyId } from '../utils/cacheMemory';\nimport { getPackageJsonPath } from '../utils/getPackageJsonPath';\nimport { getLoader } from './bundleFile';\n\nexport type TranspileOptions = BuildOptions & {\n /**\n * Optional custom esbuild instance to use for transpilation.\n * Useful in environments (e.g. VS Code extensions) where the bundled\n * esbuild binary may not match the host platform.\n * When provided, its `buildSync`/`build` methods are used instead of\n * the ones imported from the `esbuild` package.\n */\n esbuildInstance?: typeof import('esbuild');\n};\n\n/**\n * Cache of resolved tsconfig paths keyed by the file's directory.\n * Avoids re-walking to package.json + existsSync on every transpilation.\n */\nconst tsConfigPathCache = new Map<string, string | undefined>();\n\nconst getTsConfigPath = (filePath: string): string | undefined => {\n const fileDirectory = dirname(filePath);\n\n if (tsConfigPathCache.has(fileDirectory)) {\n return tsConfigPathCache.get(fileDirectory);\n }\n\n let resolvedPath: string | undefined;\n try {\n const tsconfigPath = join(\n getPackageJsonPath(fileDirectory).baseDir,\n 'tsconfig.json'\n );\n\n // Only return the tsconfig path if it exists\n resolvedPath = existsSync(tsconfigPath) ? tsconfigPath : undefined;\n } catch {\n // No package.json found up the tree — transpile without a tsconfig\n resolvedPath = undefined;\n }\n\n tsConfigPathCache.set(fileDirectory, resolvedPath);\n\n return resolvedPath;\n};\n\nconst getTransformationOptions = (filePath: string): BuildOptions => ({\n loader: {\n '.js': 'js',\n '.jsx': 'jsx',\n '.mjs': 'js',\n '.ts': 'ts',\n '.tsx': 'tsx',\n '.cjs': 'js',\n '.json': 'json',\n '.md': 'text',\n '.mdx': 'text',\n },\n format: 'cjs',\n target: 'node20',\n platform: 'node',\n write: false,\n packages: 'external',\n bundle: true,\n // The metafile lists every bundled input, which the transpile cache uses to\n // invalidate when an imported file changes (the entry itself is keyed by hash).\n metafile: true,\n tsconfig: getTsConfigPath(filePath),\n define: {\n 'import.meta.url': JSON.stringify(pathToFileURL(filePath).href),\n 'import.meta.env': 'process.env',\n },\n});\n\n/** Fingerprint of a bundled input file, used to detect changes without re-reading it. */\ntype TranspileCacheInput = {\n path: string;\n mtimeMs: number;\n size: number;\n};\n\ntype TranspileCacheEntry = {\n /** Hash of the entry file's source code. */\n codeHash: string;\n /** Hash of the build options, so different option sets don't collide. */\n optionsKey: string;\n /** The transpiled CJS output. */\n output: string;\n /** Fingerprints of every non-entry input bundled into the output. */\n inputs: TranspileCacheInput[];\n};\n\n/**\n * In-memory cache of transpiled outputs keyed by entry file path (one entry\n * per file, so re-transpilations replace rather than accumulate).\n * The entry file is validated by content hash; bundled relative imports are\n * validated by mtime + size so an edited dependency invalidates the cache.\n */\nconst transpileCache = new Map<string, TranspileCacheEntry>();\n\nconst isInputUnchanged = (input: TranspileCacheInput): boolean => {\n try {\n const stats = statSync(input.path);\n return stats.mtimeMs === input.mtimeMs && stats.size === input.size;\n } catch {\n // File removed or unreadable — treat as changed\n return false;\n }\n};\n\nconst getCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string\n): string | undefined => {\n const cacheEntry = transpileCache.get(filePath);\n\n if (!cacheEntry) return undefined;\n if (cacheEntry.codeHash !== codeHash) return undefined;\n if (cacheEntry.optionsKey !== optionsKey) return undefined;\n if (!cacheEntry.inputs.every(isInputUnchanged)) return undefined;\n\n return cacheEntry.output;\n};\n\n/**\n * Extracts the fingerprints of every bundled input from the esbuild metafile.\n * Returns `undefined` when an input cannot be fingerprinted (the result should\n * then not be cached, as invalidation would be unreliable).\n */\nconst getInputFingerprints = (\n metafile: Metafile | undefined,\n entryFilePath: string\n): TranspileCacheInput[] | undefined => {\n if (!metafile) return undefined;\n\n const resolvedEntryFilePath = resolve(entryFilePath);\n const inputs: TranspileCacheInput[] = [];\n\n for (const inputPath of Object.keys(metafile.inputs)) {\n // The entry itself is provided via stdin and validated by content hash.\n // esbuild labels it \"<stdin>\", or with the sourcefile path when set.\n if (inputPath === '<stdin>') continue;\n // Virtual modules from plugins (e.g. \"plugin:...\") cannot be fingerprinted\n if (inputPath.includes(':') && !isAbsolute(inputPath)) return undefined;\n\n const absoluteInputPath = isAbsolute(inputPath)\n ? inputPath\n : resolve(process.cwd(), inputPath);\n\n if (absoluteInputPath === resolvedEntryFilePath) continue;\n\n try {\n const stats = statSync(absoluteInputPath);\n inputs.push({\n path: absoluteInputPath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n });\n } catch {\n return undefined;\n }\n }\n\n return inputs;\n};\n\nconst setCachedTranspilation = (\n filePath: string,\n codeHash: string,\n optionsKey: string,\n moduleResult: BuildResult,\n output: string\n): void => {\n const inputs = getInputFingerprints(moduleResult.metafile, filePath);\n\n // Without a usable metafile the cache cannot be invalidated reliably — skip\n if (!inputs) return;\n\n transpileCache.set(filePath, { codeHash, optionsKey, output, inputs });\n};\n\n/** Clears the in-memory transpilation cache (mainly for tests). */\nexport const clearTranspileCache = (): void => {\n transpileCache.clear();\n tsConfigPathCache.clear();\n};\n\nexport const transpileTSToCJSSync = (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): string | undefined => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n const esbuildBuildSync = esbuildInstance?.buildSync ?? buildSync;\n\n // esbuild's worker thread service calls `new Worker(__filename, …)` on first use.\n // In Vite's SSR module runner the SSR-optimised chunk is ESM and __filename is\n // never declared (confirmed: accessing it throws ReferenceError, not undefined).\n // Because there is no local declaration the bare `__filename` lookup falls\n // through to globalThis, so we set it there to esbuild's own CJS entry-point –\n // the exact path esbuild would use if it were loaded in a normal CJS context.\n //\n // IMPORTANT: We save/restore the globals so this temporary shim does not leak\n // to other Vite plugins (e.g. `@vitejs/plugin-react-swc`) that check\n // `typeof __dirname !== \"undefined\"` to locate their own assets.\n const g = globalThis as Record<string, unknown>;\n const hadFilename = typeof g.__filename === 'string';\n const prevFilename = g.__filename;\n const prevDirname = g.__dirname;\n\n if (!hadFilename) {\n try {\n const _require = createRequire(import.meta.url);\n const esbuildEntry = _require.resolve('esbuild');\n g.__filename = esbuildEntry;\n g.__dirname = dirname(esbuildEntry);\n } catch {\n // Best-effort: if esbuild can't be resolved the caller's catch handles it\n }\n }\n\n let moduleResult: BuildResult;\n try {\n moduleResult = esbuildBuildSync({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath), // Add resolveDir to resolve imports relative to the file's location\n sourcefile: filePath, // Add sourcefile for better error messages\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n } finally {\n // Always restore the previous values so the globals don't linger.\n if (!hadFilename) {\n if (prevFilename === undefined) {\n // biome-ignore lint/performance/noDelete: the global must be truly absent — assigning undefined would leave the key present and break `typeof __filename` checks in other tools\n delete g.__filename;\n } else {\n g.__filename = prevFilename;\n }\n if (prevDirname === undefined) {\n // biome-ignore lint/performance/noDelete: same as __filename above\n delete g.__dirname;\n } else {\n g.__dirname = prevDirname;\n }\n }\n }\n\n const moduleResultString = moduleResult!.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult!,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n\nexport const transpileTSToCJS = async (\n code: string,\n filePath: string,\n options?: TranspileOptions\n): Promise<string | undefined> => {\n const extension = extname(filePath);\n const loader = getLoader(extension);\n\n const { esbuildInstance, ...buildOptions } = options ?? {};\n\n const codeHash = computeKeyId([code]);\n const optionsKey = computeKeyId([buildOptions]);\n\n const cachedOutput = getCachedTranspilation(filePath, codeHash, optionsKey);\n if (typeof cachedOutput === 'string') return cachedOutput;\n\n // A one-shot build() releases its Go-side resources on completion and costs a\n // single service round-trip (context()+rebuild()+dispose() costs three).\n const esbuildBuild = esbuildInstance?.build ?? build;\n\n const moduleResult = await esbuildBuild({\n stdin: {\n contents: code,\n loader,\n resolveDir: dirname(filePath),\n sourcefile: filePath,\n },\n ...getTransformationOptions(filePath),\n ...buildOptions,\n });\n\n const moduleResultString = moduleResult.outputFiles?.[0]?.text;\n\n if (typeof moduleResultString === 'string') {\n setCachedTranspilation(\n filePath,\n codeHash,\n optionsKey,\n moduleResult,\n moduleResultString\n );\n }\n\n return moduleResultString;\n};\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,oCAAoB,IAAI,IAAgC;AAE9D,MAAM,mBAAmB,aAAyC;CAChE,MAAM,oBAAgBA,mBAAQ,QAAQ;CAEtC,IAAI,kBAAkB,IAAI,aAAa,GACrC,OAAO,kBAAkB,IAAI,aAAa;CAG5C,IAAI;CACJ,IAAI;EACF,MAAM,mBAAeC,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;GAC9B,OAAO;IACL,UAAU;IACV;IACA,gBAAYA,mBAAQ,QAAQ;IAC5B,YAAY;GACd;GACA,GAAG,yBAAyB,QAAQ;GACpC,GAAG;EACL,CAAC;CACH,UAAU;EAER,IAAI,CAAC,aAAa;GAChB,IAAI,iBAAiB,QAEnB,OAAO,EAAE;QAET,EAAE,aAAa;GAEjB,IAAI,gBAAgB,QAElB,OAAO,EAAE;QAET,EAAE,YAAY;EAElB;CACF;CAEA,MAAM,qBAAqB,aAAc,cAAc,EAAE,EAAE;CAE3D,IAAI,OAAO,uBAAuB,UAChC,uBACE,UACA,UACA,YACA,cACA,kBACF;CAGF,OAAO;AACT;AAEA,MAAa,mBAAmB,OAC9B,MACA,UACA,YACgC;CAChC,MAAM,gBAAYQ,mBAAQ,QAAQ;CAClC,MAAM,SAASC,8CAAU,SAAS;CAElC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,WAAW,CAAC;CAEzD,MAAM,WAAWC,uCAAa,CAAC,IAAI,CAAC;CACpC,MAAM,aAAaA,uCAAa,CAAC,YAAY,CAAC;CAE9C,MAAM,eAAe,uBAAuB,UAAU,UAAU,UAAU;CAC1E,IAAI,OAAO,iBAAiB,UAAU,OAAO;CAM7C,MAAM,eAAe,OAFA,iBAAiB,SAASG,cAER,CAAC;EACtC,OAAO;GACL,UAAU;GACV;GACA,gBAAYb,mBAAQ,QAAQ;GAC5B,YAAY;EACd;EACA,GAAG,yBAAyB,QAAQ;EACpC,GAAG;CACL,CAAC;CAED,MAAM,qBAAqB,aAAa,cAAc,EAAE,EAAE;CAE1D,IAAI,OAAO,uBAAuB,UAChC,uBACE,UACA,UACA,YACA,cACA,kBACF;CAGF,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ESMxCJSHelpers.cjs","names":["getPackageJsonPath"],"sources":["../../../src/utils/ESMxCJSHelpers.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { getPackageJsonPath } from './getPackageJsonPath';\n\nexport const isESModule = typeof import.meta.url === 'string';\n\n/**\n * Require relative to the user project\n *\n * Note: Can resolve package that are installed in the user project, ex `'intlayer'`\n */\nexport const getProjectRequire = (startDir?: string): NodeJS.Require => {\n // Can fail on VSCode extensions\n const { packageJsonPath } = getPackageJsonPath(startDir);\n\n return createRequire(packageJsonPath);\n};\n\n/**\n * Require relative to the @intlayer/config package\n *\n * Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`\n */\nexport const configESMxCJSRequire: NodeJS.Require = isESModule\n ? createRequire(import.meta.url)\n : require;\n"],"mappings":";;;;;AAGA,MAAa,aAAa,yDAA2B;;;;;;AAOrD,MAAa,qBAAqB,aAAsC;CAEtE,MAAM,EAAE,oBAAoBA,oDAAmB,QAAQ;CAEvD,
|
|
1
|
+
{"version":3,"file":"ESMxCJSHelpers.cjs","names":["getPackageJsonPath","createRequire"],"sources":["../../../src/utils/ESMxCJSHelpers.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { getPackageJsonPath } from './getPackageJsonPath';\n\nexport const isESModule = typeof import.meta.url === 'string';\n\n/**\n * Require relative to the user project\n *\n * Note: Can resolve package that are installed in the user project, ex `'intlayer'`\n */\nexport const getProjectRequire = (startDir?: string): NodeJS.Require => {\n // Can fail on VSCode extensions\n const { packageJsonPath } = getPackageJsonPath(startDir);\n\n return createRequire(packageJsonPath);\n};\n\n/**\n * Require relative to the @intlayer/config package\n *\n * Note: Can resolve package that are installed in the config package, ex `'@intlayer/types'`\n */\nexport const configESMxCJSRequire: NodeJS.Require = isESModule\n ? createRequire(import.meta.url)\n : require;\n"],"mappings":";;;;;AAGA,MAAa,aAAa,yDAA2B;;;;;;AAOrD,MAAa,qBAAqB,aAAsC;CAEtE,MAAM,EAAE,oBAAoBA,oDAAmB,QAAQ;CAEvD,WAAOC,2BAAc,eAAe;AACtC;;;;;;AAOA,MAAa,uBAAuC,iBAChDA,wEAA6B,IAC7B"}
|
package/dist/cjs/utils/alias.cjs
CHANGED
|
@@ -8,13 +8,48 @@ const getAlias = ({ configuration, format, formatter = (value) => value }) => {
|
|
|
8
8
|
const extension = require_utils_getExtension.getExtension(configuration, format ?? configuration.build.outputFormat[0] ?? "esm");
|
|
9
9
|
const { baseDir } = configuration.system;
|
|
10
10
|
const { mainDir, configDir } = configuration.system;
|
|
11
|
+
/**
|
|
12
|
+
* Dictionaries
|
|
13
|
+
*/
|
|
14
|
+
const dictionariesPath = (0, node_path.join)(mainDir, `dictionaries.${extension}`);
|
|
15
|
+
const relativeDictionariesPath = (0, node_path.relative)(baseDir, dictionariesPath);
|
|
16
|
+
const fixedDictionariesPath = formatter(require_utils_normalizePath.normalizePath(relativeDictionariesPath));
|
|
17
|
+
/**
|
|
18
|
+
* Unmerged dictionaries
|
|
19
|
+
*/
|
|
20
|
+
const unmergedDictionariesPath = (0, node_path.join)(mainDir, `unmerged_dictionaries.${extension}`);
|
|
21
|
+
const relativeUnmergedDictionariesPath = (0, node_path.relative)(baseDir, unmergedDictionariesPath);
|
|
22
|
+
const fixedUnmergedDictionariesPath = formatter(require_utils_normalizePath.normalizePath(relativeUnmergedDictionariesPath));
|
|
23
|
+
/**
|
|
24
|
+
* Remote dictionaries
|
|
25
|
+
*/
|
|
26
|
+
const remoteDictionariesPath = (0, node_path.join)(mainDir, `remote_dictionaries.${extension}`);
|
|
27
|
+
const relativeRemoteDictionariesPath = (0, node_path.relative)(baseDir, remoteDictionariesPath);
|
|
28
|
+
const fixedRemoteDictionariesPath = formatter(require_utils_normalizePath.normalizePath(relativeRemoteDictionariesPath));
|
|
29
|
+
/**
|
|
30
|
+
* Dynamic dictionaries
|
|
31
|
+
*/
|
|
32
|
+
const dynamicDictionariesPath = (0, node_path.join)(mainDir, `dynamic_dictionaries.${extension}`);
|
|
33
|
+
const relativeDynamicDictionariesPath = (0, node_path.relative)(baseDir, dynamicDictionariesPath);
|
|
34
|
+
const fixedDynamicDictionariesPath = formatter(require_utils_normalizePath.normalizePath(relativeDynamicDictionariesPath));
|
|
35
|
+
/**
|
|
36
|
+
* Fetch dictionaries
|
|
37
|
+
*/
|
|
38
|
+
const fetchDictionariesPath = (0, node_path.join)(mainDir, `fetch_dictionaries.${extension}`);
|
|
39
|
+
const relativeFetchDictionariesPath = (0, node_path.relative)(baseDir, fetchDictionariesPath);
|
|
40
|
+
const fixedFetchDictionariesPath = formatter(require_utils_normalizePath.normalizePath(relativeFetchDictionariesPath));
|
|
41
|
+
/**
|
|
42
|
+
* Configuration
|
|
43
|
+
*/
|
|
44
|
+
const configurationPath = (0, node_path.join)(configDir, `configuration.${extension}`);
|
|
45
|
+
const relativeConfigurationPath = (0, node_path.relative)(baseDir, configurationPath);
|
|
11
46
|
return {
|
|
12
|
-
"@intlayer/dictionaries-entry":
|
|
13
|
-
"@intlayer/unmerged-dictionaries-entry":
|
|
14
|
-
"@intlayer/remote-dictionaries-entry":
|
|
15
|
-
"@intlayer/dynamic-dictionaries-entry":
|
|
16
|
-
"@intlayer/fetch-dictionaries-entry":
|
|
17
|
-
"@intlayer/config/built": formatter(require_utils_normalizePath.normalizePath(
|
|
47
|
+
"@intlayer/dictionaries-entry": fixedDictionariesPath,
|
|
48
|
+
"@intlayer/unmerged-dictionaries-entry": fixedUnmergedDictionariesPath,
|
|
49
|
+
"@intlayer/remote-dictionaries-entry": fixedRemoteDictionariesPath,
|
|
50
|
+
"@intlayer/dynamic-dictionaries-entry": fixedDynamicDictionariesPath,
|
|
51
|
+
"@intlayer/fetch-dictionaries-entry": fixedFetchDictionariesPath,
|
|
52
|
+
"@intlayer/config/built": formatter(require_utils_normalizePath.normalizePath(relativeConfigurationPath))
|
|
18
53
|
};
|
|
19
54
|
};
|
|
20
55
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alias.cjs","names":["getExtension","normalizePath"],"sources":["../../../src/utils/alias.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getExtension } from './getExtension';\nimport { normalizePath } from './normalizePath';\n\nexport type GetAliasOptions = {\n configuration: IntlayerConfig;\n format?: 'esm' | 'cjs';\n formatter?: (value: string) => string;\n};\n\nexport const getAlias = ({\n configuration,\n format,\n formatter = (value: string) => value,\n}: GetAliasOptions) => {\n const extension = getExtension(\n configuration,\n format ?? configuration.build.outputFormat[0] ?? 'esm'\n );\n\n const { baseDir } = configuration.system;\n const { mainDir, configDir } = configuration.system;\n\n /**\n * Dictionaries\n */\n const dictionariesPath = join(mainDir, `dictionaries.${extension}`);\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n const fixedDictionariesPath = formatter(\n normalizePath(relativeDictionariesPath)\n );\n\n /**\n * Unmerged dictionaries\n */\n const unmergedDictionariesPath = join(\n mainDir,\n `unmerged_dictionaries.${extension}`\n );\n const relativeUnmergedDictionariesPath = relative(\n baseDir,\n unmergedDictionariesPath\n );\n const fixedUnmergedDictionariesPath = formatter(\n normalizePath(relativeUnmergedDictionariesPath)\n );\n\n /**\n * Remote dictionaries\n */\n const remoteDictionariesPath = join(\n mainDir,\n `remote_dictionaries.${extension}`\n );\n const relativeRemoteDictionariesPath = relative(\n baseDir,\n remoteDictionariesPath\n );\n const fixedRemoteDictionariesPath = formatter(\n normalizePath(relativeRemoteDictionariesPath)\n );\n\n /**\n * Dynamic dictionaries\n */\n const dynamicDictionariesPath = join(\n mainDir,\n `dynamic_dictionaries.${extension}`\n );\n const relativeDynamicDictionariesPath = relative(\n baseDir,\n dynamicDictionariesPath\n );\n const fixedDynamicDictionariesPath = formatter(\n normalizePath(relativeDynamicDictionariesPath)\n );\n\n /**\n * Fetch dictionaries\n */\n const fetchDictionariesPath = join(\n mainDir,\n `fetch_dictionaries.${extension}`\n );\n const relativeFetchDictionariesPath = relative(\n baseDir,\n fetchDictionariesPath\n );\n const fixedFetchDictionariesPath = formatter(\n normalizePath(relativeFetchDictionariesPath)\n );\n\n /**\n * Configuration\n */\n const configurationPath = join(configDir, `configuration.${extension}`);\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n const fixedConfigurationPath = formatter(\n normalizePath(relativeConfigurationPath)\n );\n\n return {\n '@intlayer/dictionaries-entry': fixedDictionariesPath,\n '@intlayer/unmerged-dictionaries-entry': fixedUnmergedDictionariesPath,\n '@intlayer/remote-dictionaries-entry': fixedRemoteDictionariesPath,\n '@intlayer/dynamic-dictionaries-entry': fixedDynamicDictionariesPath,\n '@intlayer/fetch-dictionaries-entry': fixedFetchDictionariesPath,\n '@intlayer/config/built': fixedConfigurationPath,\n } as const;\n};\n"],"mappings":";;;;;;AAWA,MAAa,YAAY,EACvB,eACA,QACA,aAAa,UAAkB,YACV;CACrB,MAAM,YAAYA,wCAChB,eACA,UAAU,cAAc,MAAM,aAAa,MAAM,KACnD;CAEA,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,SAAS,cAAc,cAAc
|
|
1
|
+
{"version":3,"file":"alias.cjs","names":["getExtension","join","relative","normalizePath"],"sources":["../../../src/utils/alias.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { getExtension } from './getExtension';\nimport { normalizePath } from './normalizePath';\n\nexport type GetAliasOptions = {\n configuration: IntlayerConfig;\n format?: 'esm' | 'cjs';\n formatter?: (value: string) => string;\n};\n\nexport const getAlias = ({\n configuration,\n format,\n formatter = (value: string) => value,\n}: GetAliasOptions) => {\n const extension = getExtension(\n configuration,\n format ?? configuration.build.outputFormat[0] ?? 'esm'\n );\n\n const { baseDir } = configuration.system;\n const { mainDir, configDir } = configuration.system;\n\n /**\n * Dictionaries\n */\n const dictionariesPath = join(mainDir, `dictionaries.${extension}`);\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n const fixedDictionariesPath = formatter(\n normalizePath(relativeDictionariesPath)\n );\n\n /**\n * Unmerged dictionaries\n */\n const unmergedDictionariesPath = join(\n mainDir,\n `unmerged_dictionaries.${extension}`\n );\n const relativeUnmergedDictionariesPath = relative(\n baseDir,\n unmergedDictionariesPath\n );\n const fixedUnmergedDictionariesPath = formatter(\n normalizePath(relativeUnmergedDictionariesPath)\n );\n\n /**\n * Remote dictionaries\n */\n const remoteDictionariesPath = join(\n mainDir,\n `remote_dictionaries.${extension}`\n );\n const relativeRemoteDictionariesPath = relative(\n baseDir,\n remoteDictionariesPath\n );\n const fixedRemoteDictionariesPath = formatter(\n normalizePath(relativeRemoteDictionariesPath)\n );\n\n /**\n * Dynamic dictionaries\n */\n const dynamicDictionariesPath = join(\n mainDir,\n `dynamic_dictionaries.${extension}`\n );\n const relativeDynamicDictionariesPath = relative(\n baseDir,\n dynamicDictionariesPath\n );\n const fixedDynamicDictionariesPath = formatter(\n normalizePath(relativeDynamicDictionariesPath)\n );\n\n /**\n * Fetch dictionaries\n */\n const fetchDictionariesPath = join(\n mainDir,\n `fetch_dictionaries.${extension}`\n );\n const relativeFetchDictionariesPath = relative(\n baseDir,\n fetchDictionariesPath\n );\n const fixedFetchDictionariesPath = formatter(\n normalizePath(relativeFetchDictionariesPath)\n );\n\n /**\n * Configuration\n */\n const configurationPath = join(configDir, `configuration.${extension}`);\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n const fixedConfigurationPath = formatter(\n normalizePath(relativeConfigurationPath)\n );\n\n return {\n '@intlayer/dictionaries-entry': fixedDictionariesPath,\n '@intlayer/unmerged-dictionaries-entry': fixedUnmergedDictionariesPath,\n '@intlayer/remote-dictionaries-entry': fixedRemoteDictionariesPath,\n '@intlayer/dynamic-dictionaries-entry': fixedDynamicDictionariesPath,\n '@intlayer/fetch-dictionaries-entry': fixedFetchDictionariesPath,\n '@intlayer/config/built': fixedConfigurationPath,\n } as const;\n};\n"],"mappings":";;;;;;AAWA,MAAa,YAAY,EACvB,eACA,QACA,aAAa,UAAkB,YACV;CACrB,MAAM,YAAYA,wCAChB,eACA,UAAU,cAAc,MAAM,aAAa,MAAM,KACnD;CAEA,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,EAAE,SAAS,cAAc,cAAc;;;;CAK7C,MAAM,uBAAmBC,gBAAK,SAAS,gBAAgB,WAAW;CAClE,MAAM,+BAA2BC,oBAAS,SAAS,gBAAgB;CACnE,MAAM,wBAAwB,UAC5BC,0CAAc,wBAAwB,CACxC;;;;CAKA,MAAM,+BAA2BF,gBAC/B,SACA,yBAAyB,WAC3B;CACA,MAAM,uCAAmCC,oBACvC,SACA,wBACF;CACA,MAAM,gCAAgC,UACpCC,0CAAc,gCAAgC,CAChD;;;;CAKA,MAAM,6BAAyBF,gBAC7B,SACA,uBAAuB,WACzB;CACA,MAAM,qCAAiCC,oBACrC,SACA,sBACF;CACA,MAAM,8BAA8B,UAClCC,0CAAc,8BAA8B,CAC9C;;;;CAKA,MAAM,8BAA0BF,gBAC9B,SACA,wBAAwB,WAC1B;CACA,MAAM,sCAAkCC,oBACtC,SACA,uBACF;CACA,MAAM,+BAA+B,UACnCC,0CAAc,+BAA+B,CAC/C;;;;CAKA,MAAM,4BAAwBF,gBAC5B,SACA,sBAAsB,WACxB;CACA,MAAM,oCAAgCC,oBACpC,SACA,qBACF;CACA,MAAM,6BAA6B,UACjCC,0CAAc,6BAA6B,CAC7C;;;;CAKA,MAAM,wBAAoBF,gBAAK,WAAW,iBAAiB,WAAW;CACtE,MAAM,gCAA4BC,oBAAS,SAAS,iBAAiB;CAKrE,OAAO;EACL,gCAAgC;EAChC,yCAAyC;EACzC,uCAAuC;EACvC,wCAAwC;EACxC,sCAAsC;EACtC,0BAV6B,UAC7BC,0CAAc,yBAAyB,CASQ;CACjD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builtConfigKeys.cjs","names":[],"sources":["../../../src/utils/builtConfigKeys.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Canonical list of configuration sections exposed as named exports by\n * `@intlayer/config/built`.\n *\n * At build time, bundler integrations (Vite, webpack, …) alias\n * `@intlayer/config/built` to the generated `.intlayer/config/configuration.mjs`\n * file (see {@link getAlias} and `generateConfigurationContent`). For that alias\n * to be transparent, the generated file MUST expose exactly the same named\n * exports as `built.ts`; otherwise a consumer importing one of them (e.g.\n * `import { analytics } from '@intlayer/config/built'`) triggers a\n * `MISSING_EXPORT` bundler error.\n *\n * Deriving both `built.ts` and the generator from this single array guarantees\n * they can never drift: adding a section here is the only change required to\n * expose it in every build target.\n */\nexport const BUILT_CONFIG_KEYS = [\n 'internationalization',\n 'dictionary',\n 'routing',\n 'content',\n 'system',\n 'editor',\n 'analytics',\n 'log',\n 'ai',\n 'build',\n 'compiler',\n 'schemas',\n 'plugins',\n] as const satisfies readonly (keyof IntlayerConfig)[];\n\n/**\n * Union of the configuration section names exposed by `@intlayer/config/built`.\n */\nexport type BuiltConfigKey = (typeof BUILT_CONFIG_KEYS)[number];\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"builtConfigKeys.cjs","names":[],"sources":["../../../src/utils/builtConfigKeys.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Canonical list of configuration sections exposed as named exports by\n * `@intlayer/config/built`.\n *\n * At build time, bundler integrations (Vite, webpack, …) alias\n * `@intlayer/config/built` to the generated `.intlayer/config/configuration.mjs`\n * file (see {@link getAlias} and `generateConfigurationContent`). For that alias\n * to be transparent, the generated file MUST expose exactly the same named\n * exports as `built.ts`; otherwise a consumer importing one of them (e.g.\n * `import { analytics } from '@intlayer/config/built'`) triggers a\n * `MISSING_EXPORT` bundler error.\n *\n * Deriving both `built.ts` and the generator from this single array guarantees\n * they can never drift: adding a section here is the only change required to\n * expose it in every build target.\n */\nexport const BUILT_CONFIG_KEYS = [\n 'internationalization',\n 'dictionary',\n 'routing',\n 'content',\n 'system',\n 'editor',\n 'analytics',\n 'log',\n 'ai',\n 'build',\n 'compiler',\n 'schemas',\n 'plugins',\n] as const satisfies readonly (keyof IntlayerConfig)[];\n\n/**\n * Union of the configuration section names exposed by `@intlayer/config/built`.\n */\nexport type BuiltConfigKey = (typeof BUILT_CONFIG_KEYS)[number];\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
@@ -58,7 +58,8 @@ const cacheDisk = (intlayerConfig, keys, options) => {
|
|
|
58
58
|
let raw = await (0, node_fs_promises.readFile)(filePath);
|
|
59
59
|
const flag = raw[0];
|
|
60
60
|
raw = raw.subarray(1);
|
|
61
|
-
const
|
|
61
|
+
const payload = flag === 1 ? (0, node_zlib.gunzipSync)(raw) : raw;
|
|
62
|
+
const deserialized = (0, node_v8.deserialize)(payload);
|
|
62
63
|
let value;
|
|
63
64
|
const maybeObj = deserialized;
|
|
64
65
|
if (!!maybeObj && typeof maybeObj === "object" && typeof maybeObj.version === "string" && typeof maybeObj.timestamp === "number" && Object.hasOwn(maybeObj, "data")) {
|
|
@@ -157,7 +158,8 @@ const cacheDisk = (intlayerConfig, keys, options) => {
|
|
|
157
158
|
let raw = await (0, node_fs_promises.readFile)(filePath);
|
|
158
159
|
const flag = raw[0];
|
|
159
160
|
raw = raw.subarray(1);
|
|
160
|
-
const
|
|
161
|
+
const payload = flag === 1 ? (0, node_zlib.gunzipSync)(raw) : raw;
|
|
162
|
+
const maybeObj = (0, node_v8.deserialize)(payload);
|
|
161
163
|
if (!!maybeObj && typeof maybeObj === "object" && typeof maybeObj.version === "string" && typeof maybeObj.timestamp === "number" && Object.hasOwn(maybeObj, "data")) {
|
|
162
164
|
const entry = maybeObj;
|
|
163
165
|
if (entry.version !== _intlayer_types_package_json.default.version) return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cacheDisk.cjs","names":["computeKeyId","configPackageJson"],"sources":["../../../src/utils/cacheDisk.ts"],"sourcesContent":["import {\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { deserialize, serialize } from 'node:v8';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport configPackageJson from '@intlayer/types/package.json' with {\n type: 'json',\n};\nimport { type CacheKey, clearAllCache, computeKeyId } from './cacheMemory';\n\n/** ------------------------- Persistence layer ------------------------- **/\n\n/** Cache envelope structure stored on disk */\ntype CacheEnvelope = {\n /** Version of the config package (for cache invalidation) */\n version: string;\n /** Timestamp when the cache entry was created (in milliseconds) */\n timestamp: number;\n /** Data payload (the actual cached value) */\n data: unknown;\n};\n\ntype LocalCacheOptions = {\n /** Preferred new option name */\n persistent?: boolean;\n /** Time-to-live in ms; if expired, disk entry is ignored. */\n ttlMs?: number;\n /** Max age in ms based on stored creation timestamp; invalidates on exceed. */\n maxTimeMs?: number;\n /** Optional namespace to separate different logical caches. */\n namespace?: string;\n /** Gzip values on disk (on by default for blobs > 1KB). */\n compress?: boolean;\n};\n\nconst DEFAULTS: Required<Pick<LocalCacheOptions, 'compress'>> = {\n compress: true,\n};\n\nconst ensureDir = async (dir: string) => {\n await mkdir(dir, { recursive: true });\n};\n\nconst atomicWriteFile = async (\n file: string,\n data: Buffer,\n tempDir?: string\n) => {\n if (tempDir) {\n try {\n await ensureDir(tempDir);\n } catch {}\n }\n\n const tempFileName = `${basename(file)}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n const tmp = tempDir\n ? join(tempDir, tempFileName)\n : `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n try {\n await writeFile(tmp, data);\n await rename(tmp, file);\n } catch (error) {\n try {\n await rm(tmp, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n};\n\nconst shouldUseCompression = (buf: Buffer, force?: boolean) =>\n force === true || (force !== false && buf.byteLength > 1024);\n\n/** Derive on-disk path from config dir + namespace + key id. */\nconst cachePath = (cacheDir: string, id: string, ns?: string) =>\n join(cacheDir, ns ? join(ns, id) : id);\n\n/** ------------------------- Local cache facade ------------------------- **/\n\nconst cacheMap = new Map<string, any>();\n\n/** Clears the in-memory portion of the disk cache without touching disk files. */\nexport const clearDiskCacheMemory = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheDisk = (\n intlayerConfig: IntlayerConfig,\n keys: CacheKey[],\n options?: LocalCacheOptions\n) => {\n const { cacheDir, tempDir } = intlayerConfig.system;\n const buildCacheEnabled = intlayerConfig.build.cache ?? true;\n const persistent =\n options?.persistent === true ||\n (typeof options?.persistent === 'undefined' && buildCacheEnabled);\n\n const { compress, ttlMs, maxTimeMs, namespace } = {\n ...DEFAULTS,\n ...options,\n };\n\n // single stable id for this key tuple (works for both memory & disk)\n const id = computeKeyId(keys);\n const filePath = cachePath(cacheDir, id, namespace);\n\n const readFromDisk = async (): Promise<unknown | undefined> => {\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n\n if (!statValue) return undefined;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return undefined;\n }\n let raw = await readFile(filePath);\n // header: 1 byte flag (0x00 raw, 0x01 gzip)\n const flag = raw[0];\n\n raw = raw.subarray(1);\n\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n let value: unknown;\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof (maybeObj as any).version === 'string' &&\n typeof (maybeObj as any).timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n\n if (entry.version !== configPackageJson.version) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n\n value = entry.data;\n } else {\n // Backward compatibility: old entries had raw serialized value.\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n value = deserialized;\n }\n\n // hydrate memory cache as well\n cacheMap.set(id, value);\n return value;\n } catch {\n return undefined;\n }\n };\n\n const writeToDisk = async (value: unknown) => {\n try {\n await ensureDir(dirname(filePath));\n const envelope: CacheEnvelope = {\n version: configPackageJson.version,\n timestamp: Date.now(),\n data: value,\n };\n const payload = Buffer.from(serialize(envelope));\n\n const gz = shouldUseCompression(payload, compress)\n ? gzipSync(payload)\n : payload;\n\n // prepend a 1-byte header indicating compression\n const buf = Buffer.concat([\n Buffer.from([gz === payload ? 0x00 : 0x01]),\n gz,\n ]);\n\n await atomicWriteFile(filePath, buf, tempDir);\n } catch {\n // swallow disk errors for cache writes\n }\n };\n\n return {\n /** In-memory first, then disk (if enabled), otherwise undefined. */\n get: async <T>(): Promise<T | undefined> => {\n const mem = cacheMap.get(id);\n\n if (mem !== undefined) return mem as T;\n\n if (persistent && buildCacheEnabled) {\n return (await readFromDisk()) as T | undefined;\n }\n return undefined;\n },\n /** Sets in-memory (always) and persists to disk if enabled. */\n set: async (value: unknown): Promise<void> => {\n cacheMap.set(id, value);\n\n if (persistent && buildCacheEnabled) {\n await writeToDisk(value);\n }\n },\n /** Clears only this entry from memory and disk. */\n clear: async (): Promise<void> => {\n cacheMap.delete(id);\n\n try {\n await unlink(filePath);\n } catch {}\n },\n /** Clears ALL cached entries (memory Map and entire cacheDir namespace if persistent). */\n clearAll: async (): Promise<void> => {\n clearAllCache();\n if (persistent && buildCacheEnabled) {\n // remove only the current namespace (if provided), else the root dir\n const base = namespace ? join(cacheDir, namespace) : cacheDir;\n\n try {\n await rm(base, { recursive: true, force: true });\n } catch {}\n\n try {\n await mkdir(base, { recursive: true });\n } catch {}\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n isValid: async (): Promise<boolean> => {\n const cachedValue = cacheMap.get(id);\n if (cachedValue !== undefined) return true;\n\n // If persistence is disabled or build cache disabled, only memory can be valid\n if (!persistent || !buildCacheEnabled) return false;\n\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n if (!statValue) return false;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return false;\n }\n\n let raw = await readFile(filePath);\n const flag = raw[0];\n raw = raw.subarray(1);\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof maybeObj.version === 'string' &&\n typeof maybeObj.timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n if (entry.version !== configPackageJson.version) return false;\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) return false;\n }\n return true;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) return false;\n }\n return true;\n } catch {\n return false;\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n id,\n /** Expose the absolute file path for debugging. */\n filePath,\n };\n};\n"],"mappings":";;;;;;;;;;;AA2CA,MAAM,WAA0D,EAC9D,UAAU,KACZ;AAEA,MAAM,YAAY,OAAO,QAAgB;CACvC,kCAAY,KAAK,EAAE,WAAW,KAAK,CAAC;AACtC;AAEA,MAAM,kBAAkB,OACtB,MACA,MACA,YACG;CACH,IAAI,SACF,IAAI;EACF,MAAM,UAAU,OAAO;CACzB,QAAQ,CAAC;CAGX,MAAM,eAAe,2BAAY,IAAI,EAAE,OAAO,QAAQ,IAAI,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;CAC/F,MAAM,MAAM,8BACH,SAAS,YAAY,IAC1B,GAAG,KAAK,OAAO,QAA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c,YAAY,YAAY,GAE/C;SADY,KAAK,IAAI,IAAI,UAAU,UACzB,WAAW,OAAO;IAAK;IAEnC,OAAO;GACT,QAAQ;IACN,OAAO;GACT;EACF;;EAEA;;EAEA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"cacheDisk.cjs","names":["mkdir","basename","join","writeFile","rename","rm","computeKeyId","stat","readFile","gunzipSync","deserialize","configPackageJson","unlink","dirname","serialize","gzipSync"],"sources":["../../../src/utils/cacheDisk.ts"],"sourcesContent":["import {\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { deserialize, serialize } from 'node:v8';\nimport { gunzipSync, gzipSync } from 'node:zlib';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport configPackageJson from '@intlayer/types/package.json' with {\n type: 'json',\n};\nimport { type CacheKey, clearAllCache, computeKeyId } from './cacheMemory';\n\n/** ------------------------- Persistence layer ------------------------- **/\n\n/** Cache envelope structure stored on disk */\ntype CacheEnvelope = {\n /** Version of the config package (for cache invalidation) */\n version: string;\n /** Timestamp when the cache entry was created (in milliseconds) */\n timestamp: number;\n /** Data payload (the actual cached value) */\n data: unknown;\n};\n\ntype LocalCacheOptions = {\n /** Preferred new option name */\n persistent?: boolean;\n /** Time-to-live in ms; if expired, disk entry is ignored. */\n ttlMs?: number;\n /** Max age in ms based on stored creation timestamp; invalidates on exceed. */\n maxTimeMs?: number;\n /** Optional namespace to separate different logical caches. */\n namespace?: string;\n /** Gzip values on disk (on by default for blobs > 1KB). */\n compress?: boolean;\n};\n\nconst DEFAULTS: Required<Pick<LocalCacheOptions, 'compress'>> = {\n compress: true,\n};\n\nconst ensureDir = async (dir: string) => {\n await mkdir(dir, { recursive: true });\n};\n\nconst atomicWriteFile = async (\n file: string,\n data: Buffer,\n tempDir?: string\n) => {\n if (tempDir) {\n try {\n await ensureDir(tempDir);\n } catch {}\n }\n\n const tempFileName = `${basename(file)}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n const tmp = tempDir\n ? join(tempDir, tempFileName)\n : `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n try {\n await writeFile(tmp, data);\n await rename(tmp, file);\n } catch (error) {\n try {\n await rm(tmp, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n};\n\nconst shouldUseCompression = (buf: Buffer, force?: boolean) =>\n force === true || (force !== false && buf.byteLength > 1024);\n\n/** Derive on-disk path from config dir + namespace + key id. */\nconst cachePath = (cacheDir: string, id: string, ns?: string) =>\n join(cacheDir, ns ? join(ns, id) : id);\n\n/** ------------------------- Local cache facade ------------------------- **/\n\nconst cacheMap = new Map<string, any>();\n\n/** Clears the in-memory portion of the disk cache without touching disk files. */\nexport const clearDiskCacheMemory = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheDisk = (\n intlayerConfig: IntlayerConfig,\n keys: CacheKey[],\n options?: LocalCacheOptions\n) => {\n const { cacheDir, tempDir } = intlayerConfig.system;\n const buildCacheEnabled = intlayerConfig.build.cache ?? true;\n const persistent =\n options?.persistent === true ||\n (typeof options?.persistent === 'undefined' && buildCacheEnabled);\n\n const { compress, ttlMs, maxTimeMs, namespace } = {\n ...DEFAULTS,\n ...options,\n };\n\n // single stable id for this key tuple (works for both memory & disk)\n const id = computeKeyId(keys);\n const filePath = cachePath(cacheDir, id, namespace);\n\n const readFromDisk = async (): Promise<unknown | undefined> => {\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n\n if (!statValue) return undefined;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return undefined;\n }\n let raw = await readFile(filePath);\n // header: 1 byte flag (0x00 raw, 0x01 gzip)\n const flag = raw[0];\n\n raw = raw.subarray(1);\n\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n let value: unknown;\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof (maybeObj as any).version === 'string' &&\n typeof (maybeObj as any).timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n\n if (entry.version !== configPackageJson.version) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n\n value = entry.data;\n } else {\n // Backward compatibility: old entries had raw serialized value.\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) {\n try {\n await unlink(filePath);\n } catch {}\n return undefined;\n }\n }\n value = deserialized;\n }\n\n // hydrate memory cache as well\n cacheMap.set(id, value);\n return value;\n } catch {\n return undefined;\n }\n };\n\n const writeToDisk = async (value: unknown) => {\n try {\n await ensureDir(dirname(filePath));\n const envelope: CacheEnvelope = {\n version: configPackageJson.version,\n timestamp: Date.now(),\n data: value,\n };\n const payload = Buffer.from(serialize(envelope));\n\n const gz = shouldUseCompression(payload, compress)\n ? gzipSync(payload)\n : payload;\n\n // prepend a 1-byte header indicating compression\n const buf = Buffer.concat([\n Buffer.from([gz === payload ? 0x00 : 0x01]),\n gz,\n ]);\n\n await atomicWriteFile(filePath, buf, tempDir);\n } catch {\n // swallow disk errors for cache writes\n }\n };\n\n return {\n /** In-memory first, then disk (if enabled), otherwise undefined. */\n get: async <T>(): Promise<T | undefined> => {\n const mem = cacheMap.get(id);\n\n if (mem !== undefined) return mem as T;\n\n if (persistent && buildCacheEnabled) {\n return (await readFromDisk()) as T | undefined;\n }\n return undefined;\n },\n /** Sets in-memory (always) and persists to disk if enabled. */\n set: async (value: unknown): Promise<void> => {\n cacheMap.set(id, value);\n\n if (persistent && buildCacheEnabled) {\n await writeToDisk(value);\n }\n },\n /** Clears only this entry from memory and disk. */\n clear: async (): Promise<void> => {\n cacheMap.delete(id);\n\n try {\n await unlink(filePath);\n } catch {}\n },\n /** Clears ALL cached entries (memory Map and entire cacheDir namespace if persistent). */\n clearAll: async (): Promise<void> => {\n clearAllCache();\n if (persistent && buildCacheEnabled) {\n // remove only the current namespace (if provided), else the root dir\n const base = namespace ? join(cacheDir, namespace) : cacheDir;\n\n try {\n await rm(base, { recursive: true, force: true });\n } catch {}\n\n try {\n await mkdir(base, { recursive: true });\n } catch {}\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n isValid: async (): Promise<boolean> => {\n const cachedValue = cacheMap.get(id);\n if (cachedValue !== undefined) return true;\n\n // If persistence is disabled or build cache disabled, only memory can be valid\n if (!persistent || !buildCacheEnabled) return false;\n\n try {\n const statValue = await stat(filePath).catch(() => undefined);\n if (!statValue) return false;\n\n if (typeof ttlMs === 'number' && ttlMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > ttlMs) return false;\n }\n\n let raw = await readFile(filePath);\n const flag = raw[0];\n raw = raw.subarray(1);\n const payload = flag === 0x01 ? gunzipSync(raw) : raw;\n const deserialized = deserialize(payload) as unknown;\n\n const maybeObj = deserialized as Record<string, unknown> | null;\n const isEnvelope =\n !!maybeObj &&\n typeof maybeObj === 'object' &&\n typeof maybeObj.version === 'string' &&\n typeof maybeObj.timestamp === 'number' &&\n Object.hasOwn(maybeObj, 'data');\n\n if (isEnvelope) {\n const entry = maybeObj as CacheEnvelope;\n if (entry.version !== configPackageJson.version) return false;\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - entry.timestamp;\n if (age > maxTimeMs) return false;\n }\n return true;\n }\n\n if (typeof maxTimeMs === 'number' && maxTimeMs > 0) {\n const age = Date.now() - statValue.mtimeMs;\n if (age > maxTimeMs) return false;\n }\n return true;\n } catch {\n return false;\n }\n },\n /** Expose the computed id (useful if you want to key other structures). */\n id,\n /** Expose the absolute file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UAAMO,uBAAK,QAAQ,CAAC,CAAC,YAAY,MAAS;IAC5D,IAAI,CAAC,WAAW,OAAO;IAEvB,IAAI,OAAO,UAAU,YAAY,QAAQ,GAEvC;SADY,KAAK,IAAI,IAAI,UAAU,UACzB,OAAO,OAAO;IAAK;IAG/B,IAAI,MAAM,UAAMC,2BAAS,QAAQ;IACjC,MAAM,OAAO,IAAI;IACjB,MAAM,IAAI,SAAS,CAAC;IACpB,MAAM,UAAU,SAAS,QAAOC,sBAAW,GAAG,IAAI;IAGlD,MAAM,eAFeC,qBAAY,OAEL;IAQ5B,IANE,CAAC,CAAC,YACF,OAAO,aAAa,YACpB,OAAO,SAAS,YAAY,YAC5B,OAAO,SAAS,cAAc,YAC9B,OAAO,OAAO,UAAU,MAAM,GAEhB;KACd,MAAM,QAAQ;KACd,IAAI,MAAM,YAAYC,qCAAkB,SAAS,OAAO;KAExD,IAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;UADY,KAAK,IAAI,IAAI,MAAM,YACrB,WAAW,OAAO;KAAK;KAEnC,OAAO;IACT;IAEA,IAAI,OAAO,cAAc,YAAY,YAAY,GAE/C;SADY,KAAK,IAAI,IAAI,UAAU,UACzB,WAAW,OAAO;IAAK;IAEnC,OAAO;GACT,QAAQ;IACN,OAAO;GACT;EACF;;EAEA;;EAEA;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cacheMemory.cjs","names":[],"sources":["../../../src/utils/cacheMemory.ts"],"sourcesContent":["import { createHash, type Hash } from 'node:crypto';\n\n/** ------------------------- Utilities ------------------------- **/\n\n/** Prefer a fast non-crypto hash if available, then fast crypto, then sha256. */\nconst pickHashAlgorithm = (): string => {\n try {\n // Node 20+ supports xxhash64 (very fast). We feature-detect at module load.\n createHash('xxhash64').update('test').digest();\n return 'xxhash64';\n } catch {}\n try {\n // sha1 is faster than sha256 and sufficient for cache keys.\n createHash('sha1').update('test').digest();\n return 'sha1';\n } catch {}\n\n return 'sha256';\n};\nconst HASH_ALGORITHM = pickHashAlgorithm();\n\n/** Base64url without padding for compact, file-system-safe ids. */\nconst toBase64Url = (buffer: Buffer): string =>\n buffer\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/g, '');\n\n/** Token helpers to minimize collisions while streaming to the hasher. */\nconst token = {\n start: (hasher: Hash, tag: string) => hasher.update(`<${tag}>`),\n sep: (hasher: Hash) => hasher.update('|'),\n end: (hasher: Hash, tag: string) => hasher.update(`</${tag}>`),\n str: (hasher: Hash, stringValue: string) => {\n // length prefix to avoid ambiguity: len#value\n hasher.update(`${stringValue.length}#`);\n hasher.update(stringValue);\n },\n num: (hasher: Hash, numberValue: number) =>\n hasher.update(\n Number.isNaN(numberValue)\n ? 'NaN'\n : numberValue === Infinity\n ? 'Inf'\n : numberValue === -Infinity\n ? '-Inf'\n : String(numberValue)\n ),\n big: (hasher: Hash, bigintValue: bigint) =>\n hasher.update(bigintValue.toString(10)),\n bool: (hasher: Hash, booleanValue: boolean) =>\n hasher.update(booleanValue ? '1' : '0'),\n};\n\n/** ------------------- Canonical, streaming hasher ------------------- **/\n\ntype Seen = WeakSet<object>;\n\n/**\n * Streams a canonical representation of `value` into `hasher` without\n * constructing large intermediate strings. Objects/Maps/Sets are normalized.\n */\nconst stableHashValue = (hasher: Hash, value: unknown, seen: Seen): void => {\n const valueType = typeof value;\n\n if (value === null) {\n token.start(hasher, 'null');\n token.end(hasher, 'null');\n return;\n }\n\n if (valueType === 'undefined') {\n token.start(hasher, 'undef');\n token.end(hasher, 'undef');\n return;\n }\n\n if (valueType === 'number') {\n token.start(hasher, 'num');\n token.num(hasher, value as number);\n token.end(hasher, 'num');\n return;\n }\n\n if (valueType === 'bigint') {\n token.start(hasher, 'big');\n token.big(hasher, value as bigint);\n token.end(hasher, 'big');\n return;\n }\n\n if (valueType === 'boolean') {\n token.start(hasher, 'bool');\n token.bool(hasher, value as boolean);\n token.end(hasher, 'bool');\n return;\n }\n\n if (valueType === 'string') {\n token.start(hasher, 'str');\n token.str(hasher, value as string);\n token.end(hasher, 'str');\n return;\n }\n\n if (valueType === 'symbol') {\n token.start(hasher, 'sym');\n token.str(hasher, String(value));\n token.end(hasher, 'sym');\n return;\n }\n\n if (valueType === 'function') {\n // Stable-ish fingerprint: name and arity (avoid source text).\n const functionValue = value as Function;\n token.start(hasher, 'fn');\n token.str(hasher, functionValue.name ?? '');\n token.sep(hasher);\n token.num(hasher, functionValue.length);\n token.end(hasher, 'fn');\n return;\n }\n\n // Arrays and typed arrays\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n token.start(hasher, 'arr');\n token.str(hasher, 'Circular');\n token.end(hasher, 'arr');\n return;\n }\n seen.add(value);\n token.start(hasher, 'arr');\n for (let i = 0; i < value.length; i++) {\n token.sep(hasher);\n stableHashValue(hasher, value[i], seen);\n }\n token.end(hasher, 'arr');\n seen.delete(value);\n return;\n }\n\n // Node/Builtins\n if (value instanceof Date) {\n token.start(hasher, 'date');\n token.str(hasher, (value as Date).toISOString());\n token.end(hasher, 'date');\n return;\n }\n\n if (value instanceof RegExp) {\n const regex = value as RegExp;\n token.start(hasher, 're');\n token.str(hasher, regex.source);\n token.sep(hasher);\n token.str(hasher, regex.flags);\n token.end(hasher, 're');\n return;\n }\n\n if (value instanceof Set) {\n const setValue = value as Set<unknown>;\n if (seen.has(setValue)) {\n token.start(hasher, 'set');\n token.str(hasher, 'Circular');\n token.end(hasher, 'set');\n return;\n }\n seen.add(setValue);\n // Normalize by item fingerprints (strings) to sort deterministically.\n const items: string[] = [];\n for (const v of setValue) items.push(stableStringify(v)); // small, bounded use of stringify\n items.sort();\n token.start(hasher, 'set');\n for (const item of items) {\n token.sep(hasher);\n token.str(hasher, item);\n }\n token.end(hasher, 'set');\n seen.delete(setValue);\n return;\n }\n\n if (value instanceof Map) {\n const mapObject = value as Map<unknown, unknown>;\n if (seen.has(mapObject)) {\n token.start(hasher, 'map');\n token.str(hasher, 'Circular');\n token.end(hasher, 'map');\n return;\n }\n seen.add(mapObject);\n // Normalize by sorted key fingerprints.\n const entries: Array<[string, unknown]> = [];\n for (const [k, v] of mapObject.entries())\n entries.push([stableStringify(k), v]);\n entries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n token.start(hasher, 'map');\n for (const [keyFingerprint, entryValue] of entries) {\n token.sep(hasher);\n token.str(hasher, keyFingerprint);\n token.sep(hasher);\n stableHashValue(hasher, entryValue, seen);\n }\n token.end(hasher, 'map');\n seen.delete(mapObject);\n return;\n }\n\n // ArrayBuffer & typed arrays\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n token.start(hasher, 'typed');\n token.str(hasher, Object.getPrototypeOf(view).constructor.name);\n token.sep(hasher);\n hasher.update(Buffer.from(view.buffer, view.byteOffset, view.byteLength));\n token.end(hasher, 'typed');\n return;\n }\n if (value instanceof ArrayBuffer) {\n const buffer = Buffer.from(value as ArrayBuffer);\n token.start(hasher, 'ab');\n hasher.update(buffer);\n token.end(hasher, 'ab');\n return;\n }\n\n // URL\n if (typeof URL !== 'undefined' && value instanceof URL) {\n token.start(hasher, 'url');\n token.str(hasher, (value as URL).toString());\n token.end(hasher, 'url');\n return;\n }\n\n // Errors\n if (value instanceof Error) {\n const errorValue = value as Error;\n token.start(hasher, 'err');\n token.str(hasher, errorValue.name || '');\n token.sep(hasher);\n token.str(hasher, errorValue.message || '');\n token.sep(hasher);\n token.str(hasher, errorValue.stack || '');\n token.end(hasher, 'err');\n return;\n }\n\n // Generic objects\n if (valueType === 'object') {\n const objectValue = value as Record<string, unknown>;\n if (seen.has(objectValue)) {\n token.start(hasher, 'obj');\n token.str(hasher, 'Circular');\n token.end(hasher, 'obj');\n return;\n }\n seen.add(objectValue);\n\n const keys = Object.keys(objectValue).sort();\n token.start(hasher, 'obj');\n for (const key of keys) {\n token.sep(hasher);\n token.str(hasher, key);\n token.sep(hasher);\n stableHashValue(hasher, (objectValue as any)[key], seen);\n }\n token.end(hasher, 'obj');\n\n seen.delete(objectValue);\n return;\n }\n\n // Fallback\n token.start(hasher, 'other');\n token.str(hasher, String(value));\n token.end(hasher, 'other');\n};\n\n/** Public stringify kept for convenience / debugging (now faster & broader). */\nexport const stableStringify = (\n value: unknown,\n _stack = new WeakSet<object>()\n): string => {\n const hasher = createHash(HASH_ALGORITHM);\n stableHashValue(hasher, value, _stack);\n return toBase64Url(hasher.digest());\n};\n\n/** Compute a compact, stable id for arbitrary key tuples. */\nexport const computeKeyId = (keyParts: unknown[]): string => {\n const h = createHash(HASH_ALGORITHM);\n token.start(h, 'keys');\n for (let i = 0; i < keyParts.length; i++) {\n token.sep(h);\n stableHashValue(h, keyParts[i], new WeakSet());\n }\n token.end(h, 'keys');\n return toBase64Url(h.digest());\n};\n\n/** ------------------------- In-memory cache ------------------------- **/\n\nexport type CacheKey = unknown;\nconst cacheMap = new Map<string, any>();\n\nexport const getCache = <T>(...key: CacheKey[]): T | undefined => {\n return cacheMap.get(computeKeyId(key));\n};\n\ntype CacheSetArgs<T> = [...keys: CacheKey[], value: T];\n\nexport const setCache = <T>(...args: CacheSetArgs<T>): void => {\n const value = args[args.length - 1] as T;\n const key = args.slice(0, -1) as CacheKey[];\n cacheMap.set(computeKeyId(key), value);\n};\n\nexport const clearCache = (idOrKey: string): void => {\n // Accept either our computed id or a legacy string id the caller already computed.\n cacheMap.delete(idOrKey);\n};\n\nexport const clearAllCache = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheMemory = {\n get: getCache,\n set: setCache,\n clear: clearCache,\n};\n"],"mappings":";;;;;;AAKA,MAAM,0BAAkC;CACtC,IAAI;EAEF,4BAAW,UAAU,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,OAAO;EAC7C,OAAO;CACT,QAAQ,CAAC;CACT,IAAI;EAEF,4BAAW,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,OAAO;EACzC,OAAO;CACT,QAAQ,CAAC;CAET,OAAO;AACT;AACA,MAAM,iBAAiB,k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AAa,sBAA4B;CACvC,SAAS,MAAM;AACjB;AAEA,MAAa,cAAc;CACzB,KAAK;CACL,KAAK;CACL,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"cacheMemory.cjs","names":["createHash"],"sources":["../../../src/utils/cacheMemory.ts"],"sourcesContent":["import { createHash, type Hash } from 'node:crypto';\n\n/** ------------------------- Utilities ------------------------- **/\n\n/** Prefer a fast non-crypto hash if available, then fast crypto, then sha256. */\nconst pickHashAlgorithm = (): string => {\n try {\n // Node 20+ supports xxhash64 (very fast). We feature-detect at module load.\n createHash('xxhash64').update('test').digest();\n return 'xxhash64';\n } catch {}\n try {\n // sha1 is faster than sha256 and sufficient for cache keys.\n createHash('sha1').update('test').digest();\n return 'sha1';\n } catch {}\n\n return 'sha256';\n};\nconst HASH_ALGORITHM = pickHashAlgorithm();\n\n/** Base64url without padding for compact, file-system-safe ids. */\nconst toBase64Url = (buffer: Buffer): string =>\n buffer\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/g, '');\n\n/** Token helpers to minimize collisions while streaming to the hasher. */\nconst token = {\n start: (hasher: Hash, tag: string) => hasher.update(`<${tag}>`),\n sep: (hasher: Hash) => hasher.update('|'),\n end: (hasher: Hash, tag: string) => hasher.update(`</${tag}>`),\n str: (hasher: Hash, stringValue: string) => {\n // length prefix to avoid ambiguity: len#value\n hasher.update(`${stringValue.length}#`);\n hasher.update(stringValue);\n },\n num: (hasher: Hash, numberValue: number) =>\n hasher.update(\n Number.isNaN(numberValue)\n ? 'NaN'\n : numberValue === Infinity\n ? 'Inf'\n : numberValue === -Infinity\n ? '-Inf'\n : String(numberValue)\n ),\n big: (hasher: Hash, bigintValue: bigint) =>\n hasher.update(bigintValue.toString(10)),\n bool: (hasher: Hash, booleanValue: boolean) =>\n hasher.update(booleanValue ? '1' : '0'),\n};\n\n/** ------------------- Canonical, streaming hasher ------------------- **/\n\ntype Seen = WeakSet<object>;\n\n/**\n * Streams a canonical representation of `value` into `hasher` without\n * constructing large intermediate strings. Objects/Maps/Sets are normalized.\n */\nconst stableHashValue = (hasher: Hash, value: unknown, seen: Seen): void => {\n const valueType = typeof value;\n\n if (value === null) {\n token.start(hasher, 'null');\n token.end(hasher, 'null');\n return;\n }\n\n if (valueType === 'undefined') {\n token.start(hasher, 'undef');\n token.end(hasher, 'undef');\n return;\n }\n\n if (valueType === 'number') {\n token.start(hasher, 'num');\n token.num(hasher, value as number);\n token.end(hasher, 'num');\n return;\n }\n\n if (valueType === 'bigint') {\n token.start(hasher, 'big');\n token.big(hasher, value as bigint);\n token.end(hasher, 'big');\n return;\n }\n\n if (valueType === 'boolean') {\n token.start(hasher, 'bool');\n token.bool(hasher, value as boolean);\n token.end(hasher, 'bool');\n return;\n }\n\n if (valueType === 'string') {\n token.start(hasher, 'str');\n token.str(hasher, value as string);\n token.end(hasher, 'str');\n return;\n }\n\n if (valueType === 'symbol') {\n token.start(hasher, 'sym');\n token.str(hasher, String(value));\n token.end(hasher, 'sym');\n return;\n }\n\n if (valueType === 'function') {\n // Stable-ish fingerprint: name and arity (avoid source text).\n const functionValue = value as Function;\n token.start(hasher, 'fn');\n token.str(hasher, functionValue.name ?? '');\n token.sep(hasher);\n token.num(hasher, functionValue.length);\n token.end(hasher, 'fn');\n return;\n }\n\n // Arrays and typed arrays\n if (Array.isArray(value)) {\n if (seen.has(value)) {\n token.start(hasher, 'arr');\n token.str(hasher, 'Circular');\n token.end(hasher, 'arr');\n return;\n }\n seen.add(value);\n token.start(hasher, 'arr');\n for (let i = 0; i < value.length; i++) {\n token.sep(hasher);\n stableHashValue(hasher, value[i], seen);\n }\n token.end(hasher, 'arr');\n seen.delete(value);\n return;\n }\n\n // Node/Builtins\n if (value instanceof Date) {\n token.start(hasher, 'date');\n token.str(hasher, (value as Date).toISOString());\n token.end(hasher, 'date');\n return;\n }\n\n if (value instanceof RegExp) {\n const regex = value as RegExp;\n token.start(hasher, 're');\n token.str(hasher, regex.source);\n token.sep(hasher);\n token.str(hasher, regex.flags);\n token.end(hasher, 're');\n return;\n }\n\n if (value instanceof Set) {\n const setValue = value as Set<unknown>;\n if (seen.has(setValue)) {\n token.start(hasher, 'set');\n token.str(hasher, 'Circular');\n token.end(hasher, 'set');\n return;\n }\n seen.add(setValue);\n // Normalize by item fingerprints (strings) to sort deterministically.\n const items: string[] = [];\n for (const v of setValue) items.push(stableStringify(v)); // small, bounded use of stringify\n items.sort();\n token.start(hasher, 'set');\n for (const item of items) {\n token.sep(hasher);\n token.str(hasher, item);\n }\n token.end(hasher, 'set');\n seen.delete(setValue);\n return;\n }\n\n if (value instanceof Map) {\n const mapObject = value as Map<unknown, unknown>;\n if (seen.has(mapObject)) {\n token.start(hasher, 'map');\n token.str(hasher, 'Circular');\n token.end(hasher, 'map');\n return;\n }\n seen.add(mapObject);\n // Normalize by sorted key fingerprints.\n const entries: Array<[string, unknown]> = [];\n for (const [k, v] of mapObject.entries())\n entries.push([stableStringify(k), v]);\n entries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n token.start(hasher, 'map');\n for (const [keyFingerprint, entryValue] of entries) {\n token.sep(hasher);\n token.str(hasher, keyFingerprint);\n token.sep(hasher);\n stableHashValue(hasher, entryValue, seen);\n }\n token.end(hasher, 'map');\n seen.delete(mapObject);\n return;\n }\n\n // ArrayBuffer & typed arrays\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n token.start(hasher, 'typed');\n token.str(hasher, Object.getPrototypeOf(view).constructor.name);\n token.sep(hasher);\n hasher.update(Buffer.from(view.buffer, view.byteOffset, view.byteLength));\n token.end(hasher, 'typed');\n return;\n }\n if (value instanceof ArrayBuffer) {\n const buffer = Buffer.from(value as ArrayBuffer);\n token.start(hasher, 'ab');\n hasher.update(buffer);\n token.end(hasher, 'ab');\n return;\n }\n\n // URL\n if (typeof URL !== 'undefined' && value instanceof URL) {\n token.start(hasher, 'url');\n token.str(hasher, (value as URL).toString());\n token.end(hasher, 'url');\n return;\n }\n\n // Errors\n if (value instanceof Error) {\n const errorValue = value as Error;\n token.start(hasher, 'err');\n token.str(hasher, errorValue.name || '');\n token.sep(hasher);\n token.str(hasher, errorValue.message || '');\n token.sep(hasher);\n token.str(hasher, errorValue.stack || '');\n token.end(hasher, 'err');\n return;\n }\n\n // Generic objects\n if (valueType === 'object') {\n const objectValue = value as Record<string, unknown>;\n if (seen.has(objectValue)) {\n token.start(hasher, 'obj');\n token.str(hasher, 'Circular');\n token.end(hasher, 'obj');\n return;\n }\n seen.add(objectValue);\n\n const keys = Object.keys(objectValue).sort();\n token.start(hasher, 'obj');\n for (const key of keys) {\n token.sep(hasher);\n token.str(hasher, key);\n token.sep(hasher);\n stableHashValue(hasher, (objectValue as any)[key], seen);\n }\n token.end(hasher, 'obj');\n\n seen.delete(objectValue);\n return;\n }\n\n // Fallback\n token.start(hasher, 'other');\n token.str(hasher, String(value));\n token.end(hasher, 'other');\n};\n\n/** Public stringify kept for convenience / debugging (now faster & broader). */\nexport const stableStringify = (\n value: unknown,\n _stack = new WeakSet<object>()\n): string => {\n const hasher = createHash(HASH_ALGORITHM);\n stableHashValue(hasher, value, _stack);\n return toBase64Url(hasher.digest());\n};\n\n/** Compute a compact, stable id for arbitrary key tuples. */\nexport const computeKeyId = (keyParts: unknown[]): string => {\n const h = createHash(HASH_ALGORITHM);\n token.start(h, 'keys');\n for (let i = 0; i < keyParts.length; i++) {\n token.sep(h);\n stableHashValue(h, keyParts[i], new WeakSet());\n }\n token.end(h, 'keys');\n return toBase64Url(h.digest());\n};\n\n/** ------------------------- In-memory cache ------------------------- **/\n\nexport type CacheKey = unknown;\nconst cacheMap = new Map<string, any>();\n\nexport const getCache = <T>(...key: CacheKey[]): T | undefined => {\n return cacheMap.get(computeKeyId(key));\n};\n\ntype CacheSetArgs<T> = [...keys: CacheKey[], value: T];\n\nexport const setCache = <T>(...args: CacheSetArgs<T>): void => {\n const value = args[args.length - 1] as T;\n const key = args.slice(0, -1) as CacheKey[];\n cacheMap.set(computeKeyId(key), value);\n};\n\nexport const clearCache = (idOrKey: string): void => {\n // Accept either our computed id or a legacy string id the caller already computed.\n cacheMap.delete(idOrKey);\n};\n\nexport const clearAllCache = (): void => {\n cacheMap.clear();\n};\n\nexport const cacheMemory = {\n get: getCache,\n set: setCache,\n clear: clearCache,\n};\n"],"mappings":";;;;;;AAKA,MAAM,0BAAkC;CACtC,IAAI;EAEF,4BAAW,UAAU,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,OAAO;EAC7C,OAAO;CACT,QAAQ,CAAC;CACT,IAAI;EAEF,4BAAW,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,OAAO;EACzC,OAAO;CACT,QAAQ,CAAC;CAET,OAAO;AACT;AACA,MAAM,iBAAiB,kBAAkB;;AAGzC,MAAM,eAAe,WACnB,OACG,SAAS,QAAQ,CAAC,CAClB,QAAQ,OAAO,GAAG,CAAC,CACnB,QAAQ,OAAO,GAAG,CAAC,CACnB,QAAQ,QAAQ,EAAE;;AAGvB,MAAM,QAAQ;CACZ,QAAQ,QAAc,QAAgB,OAAO,OAAO,IAAI,IAAI,EAAE;CAC9D,MAAM,WAAiB,OAAO,OAAO,GAAG;CACxC,MAAM,QAAc,QAAgB,OAAO,OAAO,KAAK,IAAI,EAAE;CAC7D,MAAM,QAAc,gBAAwB;EAE1C,OAAO,OAAO,GAAG,YAAY,OAAO,EAAE;EACtC,OAAO,OAAO,WAAW;CAC3B;CACA,MAAM,QAAc,gBAClB,OAAO,OACL,OAAO,MAAM,WAAW,IACpB,QACA,gBAAgB,WACd,QACA,gBAAgB,YACd,SACA,OAAO,WAAW,CAC5B;CACF,MAAM,QAAc,gBAClB,OAAO,OAAO,YAAY,SAAS,EAAE,CAAC;CACxC,OAAO,QAAc,iBACnB,OAAO,OAAO,eAAe,MAAM,GAAG;AAC1C;;;;;AAUA,MAAM,mBAAmB,QAAc,OAAgB,SAAqB;CAC1E,MAAM,YAAY,OAAO;CAEzB,IAAI,UAA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EACxC,MAAM,IAAI,CAAC;EACX,gBAAgB,GAAG,SAAS,oBAAI,IAAI,QAAQ,CAAC;CAC/C;CACA,MAAM,IAAI,GAAG,MAAM;CACnB,OAAO,YAAY,EAAE,OAAO,CAAC;AAC/B;AAKA,MAAM,2BAAW,IAAI,IAAiB;AAEtC,MAAa,YAAe,GAAG,QAAmC;CAChE,OAAO,SAAS,IAAI,aAAa,GAAG,CAAC;AACvC;AAIA,MAAa,YAAe,GAAG,SAAgC;CAC7D,MAAM,QAAQ,KAAK,KAAK,SAAS;CACjC,MAAM,MAAM,KAAK,MAAM,GAAG,EAAE;CAC5B,SAAS,IAAI,aAAa,GAAG,GAAG,KAAK;AACvC;AAEA,MAAa,cAAc,YAA0B;CAEnD,SAAS,OAAO,OAAO;AACzB;AAEA,MAAa,sBAA4B;CACvC,SAAS,MAAM;AACjB;AAEA,MAAa,cAAc;CACzB,KAAK;CACL,KAAK;CACL,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compareVersions.cjs","names":[],"sources":["../../../src/utils/compareVersions.ts"],"sourcesContent":["/**\n * Compare two semver-like version strings (e.g. \"15.10.4\" vs \"15.3.5\").\n *\n * @param version1 - first version string\n * @param version2 - second version string\n * @param comparison - type of comparison: 'gt', 'lt', 'eq', 'gte', 'lte'\n * @returns boolean indicating if version1 meets the specified comparison condition vs version2\n */\nexport const compareVersions = (\n version1: string,\n comparison: '>' | '<' | '=' | '≥' | '≤',\n version2: string\n): boolean => {\n const v1Parts = version1.split('.').map(Number);\n const v2Parts = version2.split('.').map(Number);\n const maxLen = Math.max(v1Parts.length, v2Parts.length);\n\n // Compute a basic -1, 0, or 1 comparison\n let result = 0;\n for (let i = 0; i < maxLen; i++) {\n const part1 = v1Parts[i] || 0;\n const part2 = v2Parts[i] || 0;\n if (part1 > part2) {\n result = 1;\n break;\n } else if (part1 < part2) {\n result = -1;\n break;\n }\n }\n\n switch (comparison) {\n case '>':\n return result === 1;\n case '<':\n return result === -1;\n case '=':\n return result === 0;\n case '≥':\n return result === 0 || result === 1;\n case '≤':\n return result === 0 || result === -1;\n }\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"compareVersions.cjs","names":[],"sources":["../../../src/utils/compareVersions.ts"],"sourcesContent":["/**\n * Compare two semver-like version strings (e.g. \"15.10.4\" vs \"15.3.5\").\n *\n * @param version1 - first version string\n * @param version2 - second version string\n * @param comparison - type of comparison: 'gt', 'lt', 'eq', 'gte', 'lte'\n * @returns boolean indicating if version1 meets the specified comparison condition vs version2\n */\nexport const compareVersions = (\n version1: string,\n comparison: '>' | '<' | '=' | '≥' | '≤',\n version2: string\n): boolean => {\n const v1Parts = version1.split('.').map(Number);\n const v2Parts = version2.split('.').map(Number);\n const maxLen = Math.max(v1Parts.length, v2Parts.length);\n\n // Compute a basic -1, 0, or 1 comparison\n let result = 0;\n for (let i = 0; i < maxLen; i++) {\n const part1 = v1Parts[i] || 0;\n const part2 = v2Parts[i] || 0;\n if (part1 > part2) {\n result = 1;\n break;\n } else if (part1 < part2) {\n result = -1;\n break;\n }\n }\n\n switch (comparison) {\n case '>':\n return result === 1;\n case '<':\n return result === -1;\n case '=':\n return result === 0;\n case '≥':\n return result === 0 || result === 1;\n case '≤':\n return result === 0 || result === -1;\n }\n};\n"],"mappings":";;;;;;;;;;AAQA,MAAa,mBACX,UACA,YACA,aACY;CACZ,MAAM,UAAU,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC9C,MAAM,UAAU,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAC9C,MAAM,SAAS,KAAK,IAAI,QAAQ,QAAQ,QAAQ,MAAM;CAGtD,IAAI,SAAS;CACb,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK;EAC/B,MAAM,QAAQ,QAAQ,MAAM;EAC5B,MAAM,QAAQ,QAAQ,MAAM;EAC5B,IAAI,QAAQ,OAAO;GACjB,SAAS;GACT;EACF,OAAO,IAAI,QAAQ,OAAO;GACxB,SAAS;GACT;EACF;CACF;CAEA,QAAQ,YAAR;EACE,KAAK,KACH,OAAO,WAAW;EACpB,KAAK,KACH,OAAO,WAAW;EACpB,KAAK,KACH,OAAO,WAAW;EACpB,KAAK,KACH,OAAO,WAAW,KAAK,WAAW;EACpC,KAAK,KACH,OAAO,WAAW,KAAK,WAAW;CACtC;AACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
|
|
3
2
|
//#region src/utils/extractErrorMessage.ts
|
|
4
3
|
const extractErrorMessage = (error) => {
|
|
5
4
|
const trimToSingleLine = (text) => text.split(/\r?\n/).map((stringValue) => stringValue.trim()).filter(Boolean)[0] ?? text.trim();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractErrorMessage.cjs","names":[],"sources":["../../../src/utils/extractErrorMessage.ts"],"sourcesContent":["export const extractErrorMessage = (error: unknown): string => {\n const trimToSingleLine = (text: string): string =>\n text\n .split(/\\r?\\n/)\n .map((stringValue) => stringValue.trim())\n .filter(Boolean)[0] ?? text.trim();\n\n const looksLikeJson = (value: string): boolean => {\n const stringValue = value.trim();\n\n if (!stringValue) return false;\n const first = stringValue[0];\n return first === '{' || first === '[' || first === '\"';\n };\n\n const sanitizeUnexpectedTokenMessage = (text: string): string => {\n // If the text mentions an invalid JSON parse, try to extract the meaningful part\n const t = text.trim();\n\n if (/Unexpected token/i.test(t) && /not valid JSON/i.test(t)) {\n const quoted = t.match(/\"([^\"]+)\"/);\n\n if (quoted?.[1]) return quoted[1];\n // Fallback: drop the leading parser error description\n const afterColon = t.split(':').slice(1).join(':').trim();\n\n if (afterColon) return afterColon;\n }\n return t;\n };\n\n const pickFieldsFromObject = (\n value: unknown,\n seen: Set<unknown>\n ): string | undefined => {\n if (!value || typeof value !== 'object') return undefined;\n\n if (seen.has(value)) return undefined;\n\n seen.add(value);\n\n // If the value itself is an array (e.g. ZodError.issues), iterate its items\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const fromItem = pickFieldsFromObject(item, seen);\n\n if (fromItem) return fromItem;\n\n if (typeof (item as any)?.message === 'string')\n return (item as any).message;\n }\n return undefined;\n }\n\n const obj = value as Record<string, unknown>;\n\n // Check for message first (highest priority)\n\n if (typeof obj.message === 'string' && obj.message.trim()) {\n return obj.message;\n }\n\n // Check for error_description\n\n if (\n typeof obj.error_description === 'string' &&\n obj.error_description.trim()\n ) {\n return obj.error_description;\n }\n\n // Check for error\n\n if (typeof obj.error === 'string' && obj.error.trim()) {\n return obj.error;\n }\n\n // Handle title and code combination\n const title = typeof obj.title === 'string' ? obj.title.trim() : '';\n const code = typeof obj.code === 'string' ? obj.code.trim() : '';\n\n if (title && code) {\n return `${title} (${code})`;\n }\n\n if (title) {\n return title;\n }\n\n if (code) {\n return code;\n }\n\n // Check for statusText\n\n if (typeof obj.statusText === 'string' && obj.statusText.trim()) {\n return obj.statusText;\n }\n\n // Common nested structures (Axios/Fetch-like)\n const response = obj.response as Record<string, unknown> | undefined;\n\n if (response && typeof response === 'object') {\n const data = response.data as unknown;\n const fromData = pickFieldsFromObject(data, seen);\n\n if (fromData) return fromData;\n }\n\n const data = obj.data as unknown;\n const fromData = pickFieldsFromObject(data, seen);\n\n if (fromData) return fromData;\n\n // Nested cause chain\n const cause = (obj as { cause?: unknown }).cause;\n const fromCause =\n pickFieldsFromObject(cause, seen) ??\n (typeof (cause as any)?.message === 'string'\n ? (cause as any).message\n : undefined);\n\n if (fromCause) return fromCause;\n\n // Arrays of errors\n const errors = obj.errors as unknown;\n\n if (Array.isArray(errors)) {\n for (const item of errors) {\n const fromItem = pickFieldsFromObject(item, seen);\n\n if (fromItem) return fromItem;\n\n if (typeof (item as any)?.message === 'string')\n return (item as any).message;\n }\n }\n\n return undefined;\n };\n\n const tryParseJsonString = (maybeJson: string): string | undefined => {\n if (!looksLikeJson(maybeJson)) return undefined;\n try {\n const parsed = JSON.parse(maybeJson);\n const picked = pickFieldsFromObject(parsed, new Set());\n\n if (picked) return picked;\n\n if (typeof parsed === 'string') return parsed;\n return undefined;\n } catch {\n return undefined;\n }\n };\n\n if (typeof error === 'string') {\n const cleaned = sanitizeUnexpectedTokenMessage(error);\n return tryParseJsonString(cleaned) ?? trimToSingleLine(cleaned);\n }\n\n if (error && typeof error === 'object') {\n // Native Error instance\n\n if (error instanceof Error) {\n const cleaned = sanitizeUnexpectedTokenMessage(error.message);\n const fromMessage = tryParseJsonString(cleaned);\n\n if (fromMessage) return trimToSingleLine(fromMessage);\n // Dive into cause when present\n const fromCause = extractErrorMessage(error.cause as unknown);\n\n if (fromCause && fromCause !== 'An unknown error occurred')\n return trimToSingleLine(fromCause);\n return trimToSingleLine(cleaned);\n }\n\n // Generic object\n const seen = new Set<unknown>();\n const fromObject = pickFieldsFromObject(error, seen);\n\n if (fromObject) {\n const cleaned = sanitizeUnexpectedTokenMessage(fromObject);\n return tryParseJsonString(cleaned) ?? trimToSingleLine(cleaned);\n }\n\n try {\n const serialized = JSON.stringify(error);\n return trimToSingleLine(serialized);\n } catch {\n return trimToSingleLine(String(error));\n }\n }\n\n return 'An unknown error occurred';\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"extractErrorMessage.cjs","names":[],"sources":["../../../src/utils/extractErrorMessage.ts"],"sourcesContent":["export const extractErrorMessage = (error: unknown): string => {\n const trimToSingleLine = (text: string): string =>\n text\n .split(/\\r?\\n/)\n .map((stringValue) => stringValue.trim())\n .filter(Boolean)[0] ?? text.trim();\n\n const looksLikeJson = (value: string): boolean => {\n const stringValue = value.trim();\n\n if (!stringValue) return false;\n const first = stringValue[0];\n return first === '{' || first === '[' || first === '\"';\n };\n\n const sanitizeUnexpectedTokenMessage = (text: string): string => {\n // If the text mentions an invalid JSON parse, try to extract the meaningful part\n const t = text.trim();\n\n if (/Unexpected token/i.test(t) && /not valid JSON/i.test(t)) {\n const quoted = t.match(/\"([^\"]+)\"/);\n\n if (quoted?.[1]) return quoted[1];\n // Fallback: drop the leading parser error description\n const afterColon = t.split(':').slice(1).join(':').trim();\n\n if (afterColon) return afterColon;\n }\n return t;\n };\n\n const pickFieldsFromObject = (\n value: unknown,\n seen: Set<unknown>\n ): string | undefined => {\n if (!value || typeof value !== 'object') return undefined;\n\n if (seen.has(value)) return undefined;\n\n seen.add(value);\n\n // If the value itself is an array (e.g. ZodError.issues), iterate its items\n\n if (Array.isArray(value)) {\n for (const item of value) {\n const fromItem = pickFieldsFromObject(item, seen);\n\n if (fromItem) return fromItem;\n\n if (typeof (item as any)?.message === 'string')\n return (item as any).message;\n }\n return undefined;\n }\n\n const obj = value as Record<string, unknown>;\n\n // Check for message first (highest priority)\n\n if (typeof obj.message === 'string' && obj.message.trim()) {\n return obj.message;\n }\n\n // Check for error_description\n\n if (\n typeof obj.error_description === 'string' &&\n obj.error_description.trim()\n ) {\n return obj.error_description;\n }\n\n // Check for error\n\n if (typeof obj.error === 'string' && obj.error.trim()) {\n return obj.error;\n }\n\n // Handle title and code combination\n const title = typeof obj.title === 'string' ? obj.title.trim() : '';\n const code = typeof obj.code === 'string' ? obj.code.trim() : '';\n\n if (title && code) {\n return `${title} (${code})`;\n }\n\n if (title) {\n return title;\n }\n\n if (code) {\n return code;\n }\n\n // Check for statusText\n\n if (typeof obj.statusText === 'string' && obj.statusText.trim()) {\n return obj.statusText;\n }\n\n // Common nested structures (Axios/Fetch-like)\n const response = obj.response as Record<string, unknown> | undefined;\n\n if (response && typeof response === 'object') {\n const data = response.data as unknown;\n const fromData = pickFieldsFromObject(data, seen);\n\n if (fromData) return fromData;\n }\n\n const data = obj.data as unknown;\n const fromData = pickFieldsFromObject(data, seen);\n\n if (fromData) return fromData;\n\n // Nested cause chain\n const cause = (obj as { cause?: unknown }).cause;\n const fromCause =\n pickFieldsFromObject(cause, seen) ??\n (typeof (cause as any)?.message === 'string'\n ? (cause as any).message\n : undefined);\n\n if (fromCause) return fromCause;\n\n // Arrays of errors\n const errors = obj.errors as unknown;\n\n if (Array.isArray(errors)) {\n for (const item of errors) {\n const fromItem = pickFieldsFromObject(item, seen);\n\n if (fromItem) return fromItem;\n\n if (typeof (item as any)?.message === 'string')\n return (item as any).message;\n }\n }\n\n return undefined;\n };\n\n const tryParseJsonString = (maybeJson: string): string | undefined => {\n if (!looksLikeJson(maybeJson)) return undefined;\n try {\n const parsed = JSON.parse(maybeJson);\n const picked = pickFieldsFromObject(parsed, new Set());\n\n if (picked) return picked;\n\n if (typeof parsed === 'string') return parsed;\n return undefined;\n } catch {\n return undefined;\n }\n };\n\n if (typeof error === 'string') {\n const cleaned = sanitizeUnexpectedTokenMessage(error);\n return tryParseJsonString(cleaned) ?? trimToSingleLine(cleaned);\n }\n\n if (error && typeof error === 'object') {\n // Native Error instance\n\n if (error instanceof Error) {\n const cleaned = sanitizeUnexpectedTokenMessage(error.message);\n const fromMessage = tryParseJsonString(cleaned);\n\n if (fromMessage) return trimToSingleLine(fromMessage);\n // Dive into cause when present\n const fromCause = extractErrorMessage(error.cause as unknown);\n\n if (fromCause && fromCause !== 'An unknown error occurred')\n return trimToSingleLine(fromCause);\n return trimToSingleLine(cleaned);\n }\n\n // Generic object\n const seen = new Set<unknown>();\n const fromObject = pickFieldsFromObject(error, seen);\n\n if (fromObject) {\n const cleaned = sanitizeUnexpectedTokenMessage(fromObject);\n return tryParseJsonString(cleaned) ?? trimToSingleLine(cleaned);\n }\n\n try {\n const serialized = JSON.stringify(error);\n return trimToSingleLine(serialized);\n } catch {\n return trimToSingleLine(String(error));\n }\n }\n\n return 'An unknown error occurred';\n};\n"],"mappings":";;AAAA,MAAa,uBAAuB,UAA2B;CAC7D,MAAM,oBAAoB,SACxB,KACG,MAAM,OAAO,CAAC,CACd,KAAK,gBAAgB,YAAY,KAAK,CAAC,CAAC,CACxC,OAAO,OAAO,CAAC,CAAC,MAAM,KAAK,KAAK;CAErC,MAAM,iBAAiB,UAA2B;EAChD,MAAM,cAAc,MAAM,KAAK;EAE/B,IAAI,CAAC,aAAa,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AAiB,WAAW;GAEpD,MAAM,YAAY,oBAAoB,MAAM,KAAgB;GAE5D,IAAI,aAAa,cAAc,6BAC7B,OAAO,iBAAiB,SAAS;GACnC,OAAO,iBAAiB,OAAO;EACjC;EAIA,MAAM,aAAa,qBAAqB,uBAAO,IAD9B,IACiC,CAAC;EAEnD,IAAI,YAAY;GACd,MAAM,UAAU,+BAA+B,UAAU;GACzD,OAAO,mBAAmB,OAAO,KAAK,iBAAiB,OAAO;EAChE;EAEA,IAAI;GAEF,OAAO,iBADY,KAAK,UAAU,KACD,CAAC;EACpC,QAAQ;GACN,OAAO,iBAAiB,OAAO,KAAK,CAAC;EACvC;CACF;CAEA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getDictionarySelectorUsage.cjs","names":[],"sources":["../../../src/utils/getDictionarySelectorUsage.ts"],"sourcesContent":["import type {\n Dictionary,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\n\ntype DictionaryOrGroup = Dictionary | QualifiedDictionaryGroup;\n\n/**\n * Detects whether any built dictionary declares qualifier dimensions\n * (collections or variants).\n *\n * The merge step emits a {@link QualifiedDictionaryGroup} — carrying a\n * non-empty `qualifierTypes` array — for every key whose declarations use a\n * selector. When no group is present, the selector-object resolution path in\n * `getIntlayer` / `useIntlayer` is dead code, and bundlers can eliminate it via\n * the `INTLAYER_DICTIONARY_SELECTOR` env var.\n *\n * @example\n * getHasDictionarySelector(getDictionaries(config));\n * // true → at least one collection / variant / meta dictionary\n * // false → only plain dictionaries (selector logic can be stripped)\n */\nexport const getHasDictionarySelector = (\n dictionaries: Record<string, DictionaryOrGroup> | DictionaryOrGroup[]\n): boolean => {\n const dictionariesArray = Array.isArray(dictionaries)\n ? dictionaries\n : Object.values(dictionaries);\n\n return dictionariesArray.some((dictionary) => {\n const { qualifierTypes } = dictionary as QualifiedDictionaryGroup;\n\n return Array.isArray(qualifierTypes) && qualifierTypes.length > 0;\n });\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getDictionarySelectorUsage.cjs","names":[],"sources":["../../../src/utils/getDictionarySelectorUsage.ts"],"sourcesContent":["import type {\n Dictionary,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\n\ntype DictionaryOrGroup = Dictionary | QualifiedDictionaryGroup;\n\n/**\n * Detects whether any built dictionary declares qualifier dimensions\n * (collections or variants).\n *\n * The merge step emits a {@link QualifiedDictionaryGroup} — carrying a\n * non-empty `qualifierTypes` array — for every key whose declarations use a\n * selector. When no group is present, the selector-object resolution path in\n * `getIntlayer` / `useIntlayer` is dead code, and bundlers can eliminate it via\n * the `INTLAYER_DICTIONARY_SELECTOR` env var.\n *\n * @example\n * getHasDictionarySelector(getDictionaries(config));\n * // true → at least one collection / variant / meta dictionary\n * // false → only plain dictionaries (selector logic can be stripped)\n */\nexport const getHasDictionarySelector = (\n dictionaries: Record<string, DictionaryOrGroup> | DictionaryOrGroup[]\n): boolean => {\n const dictionariesArray = Array.isArray(dictionaries)\n ? dictionaries\n : Object.values(dictionaries);\n\n return dictionariesArray.some((dictionary) => {\n const { qualifierTypes } = dictionary as QualifiedDictionaryGroup;\n\n return Array.isArray(qualifierTypes) && qualifierTypes.length > 0;\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAa,4BACX,iBACY;CAKZ,QAJ0B,MAAM,QAAQ,YAAY,IAChD,eACA,OAAO,OAAO,YAAY,EAEN,CAAC,MAAM,eAAe;EAC5C,MAAM,EAAE,mBAAmB;EAE3B,OAAO,MAAM,QAAQ,cAAc,KAAK,eAAe,SAAS;CAClE,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getExtension.cjs","names":[],"sources":["../../../src/utils/getExtension.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const getExtension = (\n configuration: IntlayerConfig,\n format?: 'esm' | 'cjs' | undefined\n) => {\n const outputFormats = configuration.build.outputFormat;\n\n if (format === 'cjs') return 'cjs';\n if (format === 'esm') return 'mjs';\n\n if (outputFormats.includes('cjs')) return 'cjs';\n if (outputFormats.includes('esm')) return 'mjs';\n\n return 'cjs';\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"getExtension.cjs","names":[],"sources":["../../../src/utils/getExtension.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const getExtension = (\n configuration: IntlayerConfig,\n format?: 'esm' | 'cjs' | undefined\n) => {\n const outputFormats = configuration.build.outputFormat;\n\n if (format === 'cjs') return 'cjs';\n if (format === 'esm') return 'mjs';\n\n if (outputFormats.includes('cjs')) return 'cjs';\n if (outputFormats.includes('esm')) return 'mjs';\n\n return 'cjs';\n};\n"],"mappings":";;AAEA,MAAa,gBACX,eACA,WACG;CACH,MAAM,gBAAgB,cAAc,MAAM;CAE1C,IAAI,WAAW,OAAO,OAAO;CAC7B,IAAI,WAAW,OAAO,OAAO;CAE7B,IAAI,cAAc,SAAS,KAAK,GAAG,OAAO;CAC1C,IAAI,cAAc,SAAS,KAAK,GAAG,OAAO;CAE1C,OAAO;AACT"}
|