@intlayer/chokidar 8.4.2 → 8.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs +5 -4
- package/dist/cjs/buildIntlayerDictionary/writeDynamicDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs +4 -4
- package/dist/cjs/buildIntlayerDictionary/writeFetchDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeMergedDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs +1 -1
- package/dist/cjs/buildIntlayerDictionary/writeRemoteDictionary.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.cjs.map +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs +1 -1
- package/dist/cjs/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.cjs.map +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs +1 -1
- package/dist/cjs/filterInvalidDictionaries.cjs.map +1 -1
- package/dist/cjs/init/index.cjs +1 -1
- package/dist/cjs/init/index.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/log.cjs +3 -3
- package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
- package/dist/cjs/logConfigDetails.cjs +2 -2
- package/dist/cjs/logConfigDetails.cjs.map +1 -1
- package/dist/cjs/prepareIntlayer.cjs +1 -1
- package/dist/cjs/prepareIntlayer.cjs.map +1 -1
- package/dist/cjs/utils/formatter.cjs +1 -1
- package/dist/cjs/utils/formatter.cjs.map +1 -1
- package/dist/cjs/writeConfiguration/index.cjs +1 -1
- package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +1 -1
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs +1 -1
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs +5 -4
- package/dist/esm/buildIntlayerDictionary/writeDynamicDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeFetchDictionary.mjs +4 -4
- package/dist/esm/buildIntlayerDictionary/writeFetchDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs +1 -1
- package/dist/esm/buildIntlayerDictionary/writeMergedDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs +1 -1
- package/dist/esm/buildIntlayerDictionary/writeRemoteDictionary.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltDynamicDictionariesPath.mjs.map +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs +1 -1
- package/dist/esm/createDictionaryEntryPoint/getBuiltFetchDictionariesPath.mjs.map +1 -1
- package/dist/esm/filterInvalidDictionaries.mjs +1 -1
- package/dist/esm/filterInvalidDictionaries.mjs.map +1 -1
- package/dist/esm/init/index.mjs +1 -1
- package/dist/esm/init/index.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadDictionaries.mjs +1 -1
- package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/log.mjs +1 -1
- package/dist/esm/loadDictionaries/log.mjs.map +1 -1
- package/dist/esm/logConfigDetails.mjs +2 -2
- package/dist/esm/logConfigDetails.mjs.map +1 -1
- package/dist/esm/prepareIntlayer.mjs +1 -1
- package/dist/esm/prepareIntlayer.mjs.map +1 -1
- package/dist/esm/utils/formatter.mjs +1 -1
- package/dist/esm/utils/formatter.mjs.map +1 -1
- package/dist/esm/writeConfiguration/index.mjs +1 -1
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +1 -1
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
- package/dist/types/build.d.ts +1 -1
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts +1 -1
- package/dist/types/buildIntlayerDictionary/index.d.ts +1 -1
- package/dist/types/buildIntlayerDictionary/writeDynamicDictionary.d.ts +2 -2
- package/dist/types/buildIntlayerDictionary/writeFetchDictionary.d.ts +15 -8
- package/dist/types/buildIntlayerDictionary/writeFetchDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/writeMergedDictionary.d.ts +1 -1
- package/dist/types/buildIntlayerDictionary/writeRemoteDictionary.d.ts +2 -2
- package/dist/types/buildIntlayerDictionary/writeRemoteDictionary.d.ts.map +1 -1
- package/dist/types/{buildIntlayerDictionary-BGj5jDFy.d.ts → buildIntlayerDictionary-C-LWgPIL.d.ts} +7 -6
- package/dist/types/buildIntlayerDictionary-C-LWgPIL.d.ts.map +1 -0
- package/dist/types/init/index.d.ts.map +1 -1
- package/dist/types/prepareIntlayer.d.ts.map +1 -1
- package/dist/types/utils/formatter.d.ts +0 -1
- package/dist/types/utils/formatter.d.ts.map +1 -1
- package/dist/types/writeConfiguration/index.d.ts.map +1 -1
- package/dist/types/writeDynamicDictionary-BE0mF2zZ.d.ts +49 -0
- package/dist/types/writeDynamicDictionary-BE0mF2zZ.d.ts.map +1 -0
- package/dist/types/{writeMergedDictionary-C4EvgXbL.d.ts → writeMergedDictionary-CMeghcRI.d.ts} +3 -3
- package/dist/types/writeMergedDictionary-CMeghcRI.d.ts.map +1 -0
- package/package.json +8 -8
- package/dist/types/buildIntlayerDictionary-BGj5jDFy.d.ts.map +0 -1
- package/dist/types/writeDynamicDictionary-DE3SJg-g.d.ts +0 -36
- package/dist/types/writeDynamicDictionary-DE3SJg-g.d.ts.map +0 -1
- package/dist/types/writeMergedDictionary-C4EvgXbL.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadDictionaries.cjs","names":["DictionariesLogger","ANSIColors","filterInvalidDictionaries","formatDictionaries","loadContentDeclarations","loadRemoteDictionaries"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import {\n ANSIColors,\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const resolvedPlugins = await Promise.all(plugins ?? []);\n\n const pluginsWithLoadDictionaries = resolvedPlugins.filter(\n (plugin) => plugin.loadDictionaries\n );\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":"iVA8BI,EAA+C,EAAE,CACrD,MAAM,EAAS,IAAIA,EAAAA,mBAEb,EAA6B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EAAyB,EAC7C,mBAAoB,EAAyB,EAC9C,CACF"}
|
|
1
|
+
{"version":3,"file":"loadDictionaries.cjs","names":["DictionariesLogger","ANSIColors","filterInvalidDictionaries","formatDictionaries","loadContentDeclarations","loadRemoteDictionaries"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import * as ANSIColors from '@intlayer/config/colors';\nimport {\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const resolvedPlugins = await Promise.all(plugins ?? []);\n\n const pluginsWithLoadDictionaries = resolvedPlugins.filter(\n (plugin) => plugin.loadDictionaries\n );\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":"iYA8BA,IAAI,EAA+C,EAAE,CACrD,MAAM,EAAS,IAAIA,EAAAA,mBAEb,EAA6B,GAAmC,CACpE,IAAM,EAAgC,CAAC,GAAG,EAAuB,CAEjE,IAAK,IAAM,KAAY,EAAU,CAC/B,IAAM,EAAQ,EAAQ,UACnB,GACC,EAAE,gBAAkB,EAAS,eAAiB,EAAE,OAAS,EAAS,KACrE,CACG,GAAS,EACX,EAAQ,GAAS,EAEjB,EAAQ,KAAK,EAAS,CAO1B,MAHA,GAAyB,EACzB,EAAO,OAAO,EAAS,CAEhB,GAQH,EAAW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AO,CAE/C,IAAM,EAAyB,KAAK,KAAK,CAMnC,EAAkC,MAAMC,EAAAA,wBAJhC,MAAM,QAAQ,EAAyB,CACjD,EACA,CAAC,EAAyB,CAI5B,EACA,EACD,CACE,KAAM,GACLF,EAAAA,0BAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiBC,EAAAA,mBAAmB,EAAa,CAAC,CAErD,EAAwB,KAAK,KAAK,CAWxC,EATgC,EAAkB,IAC/C,IACE,CACC,cAAe,EAAW,IAC1B,KAAM,QACN,OAAQ,QACT,EACJ,CAEiD,CAElD,IAAM,EAAwB,GAC5B,EAAc,OAAO,UAAY,EAAc,OAAO,cAGpD,GAEF,EAAO,gBAAgB,GAAK,CAG9B,IAAI,EAAmC,EAAE,CAErC,IACF,EAAqB,MAAME,EAAAA,uBACzB,EACA,EACA,CACE,uBAA0B,EAAO,kBAAkB,CACnD,sBAAyB,EAAO,iBAAiB,CACjD,QAAU,GAAM,EAAO,eAAe,EAAE,CACzC,CACF,CACE,KAAM,GACLH,EAAAA,0BAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiBC,EAAAA,mBAAmB,EAAa,CAAC,EAG7D,IAAM,EAAyB,KAAK,KAAK,CAOzC,OAJA,EAAO,QAAQ,CAEf,EAAa,EAAc,CAEpB,CACL,oBACA,qBACA,qBACA,KAAM,CACJ,kBAAmB,EAAwB,EAC3C,mBAAoB,EAAyB,EAC7C,mBAAoB,EAAyB,EAC9C,CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`);let t=require(`@intlayer/config/logger`),n=require(`@intlayer/config/utils`),r=require(`@intlayer/config/
|
|
2
|
-
`);if(
|
|
3
|
-
`)}this.renderedLines=
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`);let t=require(`@intlayer/config/logger`),n=require(`@intlayer/config/utils`),r=require(`@intlayer/config/colors`);r=e.t(r);let i=require(`@intlayer/config/built`);i=e.t(i);var a=class{statuses=[];spinnerTimer=null;spinnerIndex=0;renderedLines=0;spinnerFrames=t.spinnerFrames;isFinished=!1;prefix;lastRenderedState=``;remoteCheckInProgress=!1;expectRemote=!1;remoteError;pluginTotal=0;pluginDone=0;pluginError;constructor(){this.prefix=(0,t.getPrefix)(i.default?.log?.prefix)??``}setExpectRemote(e){this.expectRemote=e}startRemoteCheck(){this.isFinished||(this.remoteCheckInProgress=!0,this.startSpinner(),this.render())}stopRemoteCheck(){this.remoteCheckInProgress=!1}update(e){if(this.isFinished)return;for(let t of e){let e=this.statuses.findIndex(e=>e.dictionaryKey===t.dictionaryKey&&e.type===t.type);e>=0?this.statuses[e]=t:this.statuses.push(t)}let{remoteTotal:t}=this.computeProgress();this.expectRemote&&!this.remoteCheckInProgress&&t===0||(this.startSpinner(),this.render())}finish(){this.isFinished=!0,this.stopSpinner(),this.render()}startSpinner(){this.spinnerTimer||this.isFinished||(this.spinnerTimer=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.render()},100))}stopSpinner(){this.spinnerTimer&&=(clearInterval(this.spinnerTimer),null)}setRemoteError=e=>{this.remoteError=(0,n.extractErrorMessage)(e),this.stopRemoteCheck(),this.render()};setPluginTotal(e){this.isFinished||(this.pluginTotal=e,e>0&&this.startSpinner(),this.render())}setPluginDone(e){this.isFinished||(this.pluginDone=e,this.render())}setPluginError(e){this.isFinished||(this.pluginError=(0,n.extractErrorMessage)(e),this.render())}render(){let{localTotal:e,localDone:n,remoteTotal:i,remoteDone:a,pluginTotal:o,pluginDone:s}=this.computeProgress(),c=this.spinnerFrames[this.spinnerIndex],l=(0,t.colorize)(c,r.BLUE),u=[],d=n===e,f=a===i,p=s===o;this.expectRemote&&this.remoteCheckInProgress&&i===0||(d?u.push(`${this.prefix} ${t.v} Local content: ${(0,t.colorize)(`${n}`,r.GREEN)}${(0,t.colorize)(`/${e}`,r.GREY)}`):u.push(`${this.prefix} ${l} Local content: ${(0,t.colorize)(`${n}`,r.BLUE)}${(0,t.colorize)(`/${e}`,r.GREY)}`)),(i>0||this.remoteCheckInProgress||this.remoteError)&&(this.remoteError?u.push(`${this.prefix} ${t.x} Remote content: ${(0,t.colorize)(this.remoteError,r.RED)}`):i===0?u.push(`${this.prefix} ${l} Remote content: ${(0,t.colorize)(`Check server`,r.BLUE)}`):f?u.push(`${this.prefix} ${t.v} Remote content: ${(0,t.colorize)(`${a}`,r.GREEN)}${(0,t.colorize)(`/${i}`,r.GREY)}`):u.push(`${this.prefix} ${l} Remote content: ${(0,t.colorize)(`${a}`,r.BLUE)}${(0,t.colorize)(`/${i}`,r.GREY)}`)),(o>0||this.pluginError)&&(this.pluginError?u.push(`${this.prefix} ${t.x} Plugin content: ${(0,t.colorize)(this.pluginError,r.RED)}`):p?u.push(`${this.prefix} ${t.v} Plugin content: ${(0,t.colorize)(`${s}`,r.GREEN)}${(0,t.colorize)(`/${o}`,r.GREY)}`):u.push(`${this.prefix} ${l} Plugin content: ${(0,t.colorize)(`${s}`,r.BLUE)}${(0,t.colorize)(`/${o}`,r.GREY)}`));let m=u.join(`
|
|
2
|
+
`);if(m===this.lastRenderedState)return;this.lastRenderedState=m,this.renderedLines>0&&process.stdout.write(`\x1b[${this.renderedLines}F`);let h=Math.max(this.renderedLines,u.length);for(let e=0;e<h;e++){process.stdout.write(`\x1B[2K`);let t=u[e];t!==void 0&&process.stdout.write(t),process.stdout.write(`
|
|
3
|
+
`)}this.renderedLines=u.length}computeProgress(){let e=new Set(this.statuses.filter(e=>e.type===`local`).map(e=>e.dictionaryKey)),t=new Set(this.statuses.filter(e=>e.type===`local`&&(e.status===`built`||e.status===`error`)).map(e=>e.dictionaryKey)),n=new Set(this.statuses.filter(e=>e.type===`remote`).map(e=>e.dictionaryKey)),r=new Set(this.statuses.filter(e=>e.type===`remote`&&(e.status===`fetched`||e.status===`imported`||e.status===`error`)).map(e=>e.dictionaryKey));return{localTotal:e.size,localDone:t.size,remoteTotal:n.size,remoteDone:r.size,pluginTotal:this.pluginTotal,pluginDone:this.pluginDone}}};exports.DictionariesLogger=a;
|
|
4
4
|
//# sourceMappingURL=log.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.cjs","names":["spinnerFrames","configuration","ANSIColors","v","x"],"sources":["../../../src/loadDictionaries/log.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport {\n ANSIColors,\n colorize,\n getPrefix,\n spinnerFrames,\n v,\n x,\n} from '@intlayer/config/logger';\nimport { extractErrorMessage } from '@intlayer/config/utils';\nimport type { DictionariesStatus } from './loadDictionaries';\n\nexport class DictionariesLogger {\n private statuses: DictionariesStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private readonly prefix: string;\n private lastRenderedState: string = '';\n private remoteCheckInProgress = false;\n private expectRemote = false;\n private remoteError: string | undefined;\n private pluginTotal = 0;\n private pluginDone = 0;\n private pluginError: string | undefined;\n\n constructor() {\n this.prefix = getPrefix(configuration?.log?.prefix) ?? '';\n }\n\n setExpectRemote(expect: boolean) {\n this.expectRemote = expect;\n }\n\n startRemoteCheck() {\n if (this.isFinished) return;\n this.remoteCheckInProgress = true;\n this.startSpinner();\n this.render();\n }\n\n stopRemoteCheck() {\n this.remoteCheckInProgress = false;\n }\n\n update(newStatuses: DictionariesStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) =>\n s.dictionaryKey === status.dictionaryKey && s.type === status.type\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n // If we expect remote fetch later, avoid rendering a local-only line first\n const { remoteTotal } = this.computeProgress();\n if (this.expectRemote && !this.remoteCheckInProgress && remoteTotal === 0) {\n // Do not start spinner or render yet; wait until remote check starts\n return;\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n // Render final state and keep it visible\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n public setRemoteError = (error?: Error) => {\n this.remoteError = extractErrorMessage(error);\n // Avoid rendering a transient remote-only line while the remote check flag is still true\n // Ensure local + remote are rendered together after a failure\n this.stopRemoteCheck();\n this.render();\n };\n\n setPluginTotal(total: number) {\n if (this.isFinished) return;\n this.pluginTotal = total;\n if (total > 0) {\n this.startSpinner();\n }\n this.render();\n }\n\n setPluginDone(done: number) {\n if (this.isFinished) return;\n this.pluginDone = done;\n this.render();\n }\n\n setPluginError(error?: Error) {\n if (this.isFinished) return;\n this.pluginError = extractErrorMessage(error);\n this.render();\n }\n\n private render() {\n const {\n localTotal,\n localDone,\n remoteTotal,\n remoteDone,\n pluginTotal,\n pluginDone,\n } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const clock = colorize(frame, ANSIColors.BLUE);\n const lines: string[] = [];\n\n const isLocalDone = localDone === localTotal;\n const isRemoteDone = remoteDone === remoteTotal;\n const isPluginDone = pluginDone === pluginTotal;\n\n const suppressLocalWhileCheckingRemote =\n this.expectRemote && this.remoteCheckInProgress && remoteTotal === 0;\n\n if (!suppressLocalWhileCheckingRemote) {\n if (isLocalDone) {\n lines.push(\n `${this.prefix} ${v} Local content: ${colorize(`${localDone}`, ANSIColors.GREEN)}${colorize(`/${localTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Local content: ${colorize(`${localDone}`, ANSIColors.BLUE)}${colorize(`/${localTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Single remote line: show error, check, or progress counts\n if (remoteTotal > 0 || this.remoteCheckInProgress || this.remoteError) {\n if (this.remoteError) {\n lines.push(\n `${this.prefix} ${x} Remote content: ${colorize(\n this.remoteError,\n ANSIColors.RED\n )}`\n );\n } else if (remoteTotal === 0) {\n lines.push(\n `${this.prefix} ${clock} Remote content: ${colorize('Check server', ANSIColors.BLUE)}`\n );\n } else if (isRemoteDone) {\n lines.push(\n `${this.prefix} ${v} Remote content: ${colorize(`${remoteDone}`, ANSIColors.GREEN)}${colorize(`/${remoteTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Remote content: ${colorize(`${remoteDone}`, ANSIColors.BLUE)}${colorize(`/${remoteTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Plugin line: show error or progress counts\n if (pluginTotal > 0 || this.pluginError) {\n if (this.pluginError) {\n lines.push(\n `${this.prefix} ${x} Plugin content: ${colorize(\n this.pluginError,\n ANSIColors.RED\n )}`\n );\n } else if (isPluginDone) {\n lines.push(\n `${this.prefix} ${v} Plugin content: ${colorize(`${pluginDone}`, ANSIColors.GREEN)}${colorize(`/${pluginTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Plugin content: ${colorize(`${pluginDone}`, ANSIColors.BLUE)}${colorize(`/${pluginTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Check if the state has changed to avoid duplicate rendering\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const localKeys = new Set(\n this.statuses\n .filter((s) => s.type === 'local')\n .map((s) => s.dictionaryKey)\n );\n\n const localDoneKeys = new Set(\n this.statuses\n .filter(\n (s) =>\n s.type === 'local' && (s.status === 'built' || s.status === 'error')\n )\n .map((s) => s.dictionaryKey)\n );\n\n const remoteKeys = new Set(\n this.statuses\n .filter((s) => s.type === 'remote')\n .map((s) => s.dictionaryKey)\n );\n\n const remoteDoneKeys = new Set(\n this.statuses\n .filter(\n (s) =>\n s.type === 'remote' &&\n (s.status === 'fetched' ||\n s.status === 'imported' ||\n s.status === 'error')\n )\n .map((s) => s.dictionaryKey)\n );\n\n return {\n localTotal: localKeys.size,\n localDone: localDoneKeys.size,\n remoteTotal: remoteKeys.size,\n remoteDone: remoteDoneKeys.size,\n pluginTotal: this.pluginTotal,\n pluginDone: this.pluginDone,\n } as const;\n }\n}\n"],"mappings":"sOAYA,IAAa,EAAb,KAAgC,CAC9B,SAAyC,EAAE,CAC3C,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,OACA,kBAAoC,GACpC,sBAAgC,GAChC,aAAuB,GACvB,YACA,YAAsB,EACtB,WAAqB,EACrB,YAEA,aAAc,CACZ,KAAK,QAAA,EAAA,EAAA,WAAmBC,EAAAA,SAAe,KAAK,OAAO,EAAI,GAGzD,gBAAgB,EAAiB,CAC/B,KAAK,aAAe,EAGtB,kBAAmB,CACb,KAAK,aACT,KAAK,sBAAwB,GAC7B,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,iBAAkB,CAChB,KAAK,sBAAwB,GAG/B,OAAO,EAAmC,CACxC,GAAI,KAAK,WAAY,OACrB,IAAK,IAAM,KAAU,EAAa,CAChC,IAAM,EAAQ,KAAK,SAAS,UACzB,GACC,EAAE,gBAAkB,EAAO,eAAiB,EAAE,OAAS,EAAO,KACjE,CACG,GAAS,EACX,KAAK,SAAS,GAAS,EAEvB,KAAK,SAAS,KAAK,EAAO,CAK9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ries/log.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n getPrefix,\n spinnerFrames,\n v,\n x,\n} from '@intlayer/config/logger';\nimport { extractErrorMessage } from '@intlayer/config/utils';\nimport type { DictionariesStatus } from './loadDictionaries';\n\nexport class DictionariesLogger {\n private statuses: DictionariesStatus[] = [];\n private spinnerTimer: NodeJS.Timeout | null = null;\n private spinnerIndex = 0;\n private renderedLines = 0;\n private readonly spinnerFrames = spinnerFrames;\n private isFinished = false;\n private readonly prefix: string;\n private lastRenderedState: string = '';\n private remoteCheckInProgress = false;\n private expectRemote = false;\n private remoteError: string | undefined;\n private pluginTotal = 0;\n private pluginDone = 0;\n private pluginError: string | undefined;\n\n constructor() {\n this.prefix = getPrefix(configuration?.log?.prefix) ?? '';\n }\n\n setExpectRemote(expect: boolean) {\n this.expectRemote = expect;\n }\n\n startRemoteCheck() {\n if (this.isFinished) return;\n this.remoteCheckInProgress = true;\n this.startSpinner();\n this.render();\n }\n\n stopRemoteCheck() {\n this.remoteCheckInProgress = false;\n }\n\n update(newStatuses: DictionariesStatus[]) {\n if (this.isFinished) return;\n for (const status of newStatuses) {\n const index = this.statuses.findIndex(\n (s) =>\n s.dictionaryKey === status.dictionaryKey && s.type === status.type\n );\n if (index >= 0) {\n this.statuses[index] = status;\n } else {\n this.statuses.push(status);\n }\n }\n\n // If we expect remote fetch later, avoid rendering a local-only line first\n const { remoteTotal } = this.computeProgress();\n if (this.expectRemote && !this.remoteCheckInProgress && remoteTotal === 0) {\n // Do not start spinner or render yet; wait until remote check starts\n return;\n }\n\n this.startSpinner();\n this.render();\n }\n\n finish() {\n this.isFinished = true;\n this.stopSpinner();\n // Render final state and keep it visible\n this.render();\n }\n\n private startSpinner() {\n if (this.spinnerTimer || this.isFinished) return;\n this.spinnerTimer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % this.spinnerFrames.length;\n this.render();\n }, 100);\n }\n\n private stopSpinner() {\n if (!this.spinnerTimer) return;\n clearInterval(this.spinnerTimer);\n this.spinnerTimer = null;\n }\n\n public setRemoteError = (error?: Error) => {\n this.remoteError = extractErrorMessage(error);\n // Avoid rendering a transient remote-only line while the remote check flag is still true\n // Ensure local + remote are rendered together after a failure\n this.stopRemoteCheck();\n this.render();\n };\n\n setPluginTotal(total: number) {\n if (this.isFinished) return;\n this.pluginTotal = total;\n if (total > 0) {\n this.startSpinner();\n }\n this.render();\n }\n\n setPluginDone(done: number) {\n if (this.isFinished) return;\n this.pluginDone = done;\n this.render();\n }\n\n setPluginError(error?: Error) {\n if (this.isFinished) return;\n this.pluginError = extractErrorMessage(error);\n this.render();\n }\n\n private render() {\n const {\n localTotal,\n localDone,\n remoteTotal,\n remoteDone,\n pluginTotal,\n pluginDone,\n } = this.computeProgress();\n\n const frame = this.spinnerFrames[this.spinnerIndex];\n const clock = colorize(frame, ANSIColors.BLUE);\n const lines: string[] = [];\n\n const isLocalDone = localDone === localTotal;\n const isRemoteDone = remoteDone === remoteTotal;\n const isPluginDone = pluginDone === pluginTotal;\n\n const suppressLocalWhileCheckingRemote =\n this.expectRemote && this.remoteCheckInProgress && remoteTotal === 0;\n\n if (!suppressLocalWhileCheckingRemote) {\n if (isLocalDone) {\n lines.push(\n `${this.prefix} ${v} Local content: ${colorize(`${localDone}`, ANSIColors.GREEN)}${colorize(`/${localTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Local content: ${colorize(`${localDone}`, ANSIColors.BLUE)}${colorize(`/${localTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Single remote line: show error, check, or progress counts\n if (remoteTotal > 0 || this.remoteCheckInProgress || this.remoteError) {\n if (this.remoteError) {\n lines.push(\n `${this.prefix} ${x} Remote content: ${colorize(\n this.remoteError,\n ANSIColors.RED\n )}`\n );\n } else if (remoteTotal === 0) {\n lines.push(\n `${this.prefix} ${clock} Remote content: ${colorize('Check server', ANSIColors.BLUE)}`\n );\n } else if (isRemoteDone) {\n lines.push(\n `${this.prefix} ${v} Remote content: ${colorize(`${remoteDone}`, ANSIColors.GREEN)}${colorize(`/${remoteTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Remote content: ${colorize(`${remoteDone}`, ANSIColors.BLUE)}${colorize(`/${remoteTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Plugin line: show error or progress counts\n if (pluginTotal > 0 || this.pluginError) {\n if (this.pluginError) {\n lines.push(\n `${this.prefix} ${x} Plugin content: ${colorize(\n this.pluginError,\n ANSIColors.RED\n )}`\n );\n } else if (isPluginDone) {\n lines.push(\n `${this.prefix} ${v} Plugin content: ${colorize(`${pluginDone}`, ANSIColors.GREEN)}${colorize(`/${pluginTotal}`, ANSIColors.GREY)}`\n );\n } else {\n lines.push(\n `${this.prefix} ${clock} Plugin content: ${colorize(`${pluginDone}`, ANSIColors.BLUE)}${colorize(`/${pluginTotal}`, ANSIColors.GREY)}`\n );\n }\n }\n\n // Check if the state has changed to avoid duplicate rendering\n const currentState = lines.join('\\n');\n if (currentState === this.lastRenderedState) {\n return;\n }\n this.lastRenderedState = currentState;\n\n if (this.renderedLines > 0) {\n process.stdout.write(`\\x1b[${this.renderedLines}F`);\n }\n\n const totalLinesToClear = Math.max(this.renderedLines, lines.length);\n for (let i = 0; i < totalLinesToClear; i++) {\n process.stdout.write('\\x1b[2K');\n const line = lines[i];\n if (line !== undefined) {\n process.stdout.write(line);\n }\n process.stdout.write('\\n');\n }\n\n this.renderedLines = lines.length;\n }\n\n private computeProgress() {\n const localKeys = new Set(\n this.statuses\n .filter((s) => s.type === 'local')\n .map((s) => s.dictionaryKey)\n );\n\n const localDoneKeys = new Set(\n this.statuses\n .filter(\n (s) =>\n s.type === 'local' && (s.status === 'built' || s.status === 'error')\n )\n .map((s) => s.dictionaryKey)\n );\n\n const remoteKeys = new Set(\n this.statuses\n .filter((s) => s.type === 'remote')\n .map((s) => s.dictionaryKey)\n );\n\n const remoteDoneKeys = new Set(\n this.statuses\n .filter(\n (s) =>\n s.type === 'remote' &&\n (s.status === 'fetched' ||\n s.status === 'imported' ||\n s.status === 'error')\n )\n .map((s) => s.dictionaryKey)\n );\n\n return {\n localTotal: localKeys.size,\n localDone: localDoneKeys.size,\n remoteTotal: remoteKeys.size,\n remoteDone: remoteDoneKeys.size,\n pluginTotal: this.pluginTotal,\n pluginDone: this.pluginDone,\n } as const;\n }\n}\n"],"mappings":"wRAYA,IAAa,EAAb,KAAgC,CAC9B,SAAyC,EAAE,CAC3C,aAA8C,KAC9C,aAAuB,EACvB,cAAwB,EACxB,cAAiCA,EAAAA,cACjC,WAAqB,GACrB,OACA,kBAAoC,GACpC,sBAAgC,GAChC,aAAuB,GACvB,YACA,YAAsB,EACtB,WAAqB,EACrB,YAEA,aAAc,CACZ,KAAK,QAAA,EAAA,EAAA,WAAmBC,EAAAA,SAAe,KAAK,OAAO,EAAI,GAGzD,gBAAgB,EAAiB,CAC/B,KAAK,aAAe,EAGtB,kBAAmB,CACb,KAAK,aACT,KAAK,sBAAwB,GAC7B,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,iBAAkB,CAChB,KAAK,sBAAwB,GAG/B,OAAO,EAAmC,CACxC,GAAI,KAAK,WAAY,OACrB,IAAK,IAAM,KAAU,EAAa,CAChC,IAAM,EAAQ,KAAK,SAAS,UACzB,GACC,EAAE,gBAAkB,EAAO,eAAiB,EAAE,OAAS,EAAO,KACjE,CACG,GAAS,EACX,KAAK,SAAS,GAAS,EAEvB,KAAK,SAAS,KAAK,EAAO,CAK9B,GAAM,CAAE,eAAgB,KAAK,iBAAiB,CAC1C,KAAK,cAAgB,CAAC,KAAK,uBAAyB,IAAgB,IAKxE,KAAK,cAAc,CACnB,KAAK,QAAQ,EAGf,QAAS,CACP,KAAK,WAAa,GAClB,KAAK,aAAa,CAElB,KAAK,QAAQ,CAGf,cAAuB,CACjB,KAAK,cAAgB,KAAK,aAC9B,KAAK,aA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,MAAM,UAAU,CAC/B,IAAM,EAAO,EAAM,GACf,IAAS,IAAA,IACX,QAAQ,OAAO,MAAM,EAAK,CAE5B,QAAQ,OAAO,MAAM;EAAK,CAG5B,KAAK,cAAgB,EAAM,OAG7B,iBAA0B,CACxB,IAAM,EAAY,IAAI,IACpB,KAAK,SACF,OAAQ,GAAM,EAAE,OAAS,QAAQ,CACjC,IAAK,GAAM,EAAE,cAAc,CAC/B,CAEK,EAAgB,IAAI,IACxB,KAAK,SACF,OACE,GACC,EAAE,OAAS,UAAY,EAAE,SAAW,SAAW,EAAE,SAAW,SAC/D,CACA,IAAK,GAAM,EAAE,cAAc,CAC/B,CAEK,EAAa,IAAI,IACrB,KAAK,SACF,OAAQ,GAAM,EAAE,OAAS,SAAS,CAClC,IAAK,GAAM,EAAE,cAAc,CAC/B,CAEK,EAAiB,IAAI,IACzB,KAAK,SACF,OACE,GACC,EAAE,OAAS,WACV,EAAE,SAAW,WACZ,EAAE,SAAW,YACb,EAAE,SAAW,SAClB,CACA,IAAK,GAAM,EAAE,cAAc,CAC/B,CAED,MAAO,CACL,WAAY,EAAU,KACtB,UAAW,EAAc,KACzB,YAAa,EAAW,KACxB,WAAY,EAAe,KAC3B,YAAa,KAAK,YAClB,WAAY,KAAK,WAClB"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
2
|
-
`)}`),
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./utils/formatter.cjs`),n=require(`./utils/runOnce.cjs`);let r=require(`node:path`),i=require(`@intlayer/config/logger`),a=require(`@intlayer/config/node`),o=require(`@intlayer/config/colors`);o=e.t(o);let s=require(`@intlayer/config/env`);const c=e=>{let{configuration:c,customConfiguration:l,numCustomConfiguration:u,configurationFilePath:d}=(0,a.getConfigurationAndFilePath)(e),f=(0,i.getAppLogger)(c);n.runOnce((0,r.join)(c.system.baseDir,`.intlayer`,`cache`,`intlayer-config-locaded.lock`),()=>{if(u===0)f(`Configuration file not found, using default configuration.`,{isVerbose:!0});else{let n=c.system.baseDir,i=(0,r.relative)(n,d);if(u===1){let n=(0,s.getEnvFilePath)(e?.env,e?.envFile);f(`Configuration loaded ${t.formatPath(i)}${n?` - Env: ${t.formatPath(n)}`:``}`,{isVerbose:!0})}else f(`Multiple configuration files found, using ${t.formatPath(i)}.`,{isVerbose:!0})}if(l){let e=a.intlayerConfigSchema.safeParse(l);e.success||f(`${i.x} Invalid configuration:\n${e.error.issues.map(e=>`${(0,i.colorizePath)(` - ${e.path.join(`.`)}:`)} ${(0,i.colorize)(e.message,o.GREY_DARK)}`).join(`
|
|
2
|
+
`)}`),l.build?.importMode&&f(`${(0,i.colorize)(`build.importMode`,o.BLUE)} is deprecated, use ${(0,i.colorize)(`dictionary.importMode`,o.BLUE)} instead`),l.compiler?.transformPattern&&f(`${(0,i.colorize)(`compiler.transformPattern`,o.BLUE)} is deprecated, use ${(0,i.colorize)(`build.traversePattern`,o.BLUE)} instead`),l.compiler?.excludePattern&&f(`${(0,i.colorize)(`compiler.excludePattern`,o.BLUE)} is deprecated, use ${(0,i.colorize)(`build.traversePattern`,o.BLUE)} instead`)}},{cacheTimeoutMs:1e3*60})};exports.logConfigDetails=c;
|
|
3
3
|
//# sourceMappingURL=logConfigDetails.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logConfigDetails.cjs","names":["formatPath","intlayerConfigSchema","x","ANSIColors"],"sources":["../../src/logConfigDetails.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport { getEnvFilePath } from '@intlayer/config/env';\nimport {\n
|
|
1
|
+
{"version":3,"file":"logConfigDetails.cjs","names":["formatPath","intlayerConfigSchema","x","ANSIColors"],"sources":["../../src/logConfigDetails.ts"],"sourcesContent":["import { join, relative } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { getEnvFilePath } from '@intlayer/config/env';\nimport {\n colorize,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfigurationAndFilePath,\n intlayerConfigSchema,\n} from '@intlayer/config/node';\nimport { formatPath, runOnce } from './utils';\n\nexport const logConfigDetails = (options?: GetConfigurationOptions) => {\n const {\n configuration,\n customConfiguration,\n numCustomConfiguration,\n configurationFilePath,\n } = getConfigurationAndFilePath(options);\n const appLogger = getAppLogger(configuration);\n\n runOnce(\n join(\n configuration.system.baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-config-locaded.lock'\n ),\n () => {\n if (numCustomConfiguration === 0) {\n appLogger(\n 'Configuration file not found, using default configuration.',\n {\n isVerbose: true,\n }\n );\n } else {\n const baseDir = configuration.system.baseDir;\n const relativeOutputPath = relative(baseDir, configurationFilePath!);\n\n if (numCustomConfiguration === 1) {\n const dotEnvFilePath = getEnvFilePath(options?.env, options?.envFile);\n\n appLogger(\n `Configuration loaded ${formatPath(relativeOutputPath)}${dotEnvFilePath ? ` - Env: ${formatPath(dotEnvFilePath)}` : ''}`,\n {\n isVerbose: true,\n }\n );\n } else {\n appLogger(\n `Multiple configuration files found, using ${formatPath(relativeOutputPath)}.`,\n {\n isVerbose: true,\n }\n );\n }\n }\n\n if (customConfiguration) {\n const validation = intlayerConfigSchema.safeParse(customConfiguration);\n\n if (!validation.success) {\n const errorMessages = validation.error.issues\n .map((error) => {\n const path = colorizePath(` - ${error.path.join('.')}:`);\n const message = colorize(error.message, ANSIColors.GREY_DARK);\n return `${path} ${message}`;\n })\n .join('\\n');\n const errorMessage = `${x} Invalid configuration:\\n${errorMessages}`;\n\n appLogger(errorMessage);\n }\n\n if (customConfiguration.build?.importMode) {\n appLogger(\n `${colorize('build.importMode', ANSIColors.BLUE)} is deprecated, use ${colorize('dictionary.importMode', ANSIColors.BLUE)} instead`\n );\n }\n if (customConfiguration.compiler?.transformPattern) {\n appLogger(\n `${colorize('compiler.transformPattern', ANSIColors.BLUE)} is deprecated, use ${colorize('build.traversePattern', ANSIColors.BLUE)} instead`\n );\n }\n if (customConfiguration.compiler?.excludePattern) {\n appLogger(\n `${colorize('compiler.excludePattern', ANSIColors.BLUE)} is deprecated, use ${colorize('build.traversePattern', ANSIColors.BLUE)} instead`\n );\n }\n }\n },\n {\n cacheTimeoutMs: 1000 * 60, // 1 minute\n }\n );\n};\n"],"mappings":"sWAgBA,MAAa,EAAoB,GAAsC,CACrE,GAAM,CACJ,gBACA,sBACA,yBACA,0BAAA,EAAA,EAAA,6BAC8B,EAAQ,CAClC,GAAA,EAAA,EAAA,cAAyB,EAAc,CAE7C,EAAA,SAAA,EAAA,EAAA,MAEI,EAAc,OAAO,QACrB,YACA,QACA,+BACD,KACK,CACJ,GAAI,IAA2B,EAC7B,EACE,6DACA,CACE,UAAW,GACZ,CACF,KACI,CACL,IAAM,EAAU,EAAc,OAAO,QAC/B,GAAA,EAAA,EAAA,UAA8B,EAAS,EAAuB,CAEpE,GAAI,IAA2B,EAAG,CAChC,IAAM,GAAA,EAAA,EAAA,gBAAgC,GAAS,IAAK,GAAS,QAAQ,CAErE,EACE,wBAAwBA,EAAAA,WAAW,EAAmB,GAAG,EAAiB,WAAWA,EAAAA,WAAW,EAAe,GAAK,KACpH,CACE,UAAW,GACZ,CACF,MAED,EACE,6CAA6CA,EAAAA,WAAW,EAAmB,CAAC,GAC5E,CACE,UAAW,GACZ,CACF,CAIL,GAAI,EAAqB,CACvB,IAAM,EAAaC,EAAAA,qBAAqB,UAAU,EAAoB,CAEjE,EAAW,SAUd,EAFqB,GAAGC,EAAAA,EAAE,2BAPJ,EAAW,MAAM,OACpC,IAAK,GAGG,IAAA,EAAA,EAAA,cAFmB,MAAM,EAAM,KAAK,KAAK,IAAI,CAAC,GAAG,CAEzC,IAAA,EAAA,EAAA,UADU,EAAM,QAASC,EAAW,UAAU,GAE7D,CACD,KAAK;EAAK,GAGU,CAGrB,EAAoB,OAAO,YAC7B,EACE,IAAA,EAAA,EAAA,UAAY,mBAAoBA,EAAW,KAAK,CAAC,uBAAA,EAAA,EAAA,UAA+B,wBAAyBA,EAAW,KAAK,CAAC,UAC3H,CAEC,EAAoB,UAAU,kBAChC,EACE,IAAA,EAAA,EAAA,UAAY,4BAA6BA,EAAW,KAAK,CAAC,uBAAA,EAAA,EAAA,UAA+B,wBAAyBA,EAAW,KAAK,CAAC,UACpI,CAEC,EAAoB,UAAU,gBAChC,EACE,IAAA,EAAA,EAAA,UAAY,0BAA2BA,EAAW,KAAK,CAAC,uBAAA,EAAA,EAAA,UAA+B,wBAAyBA,EAAW,KAAK,CAAC,UAClI,GAIP,CACE,eAAgB,IAAO,GACxB,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./createDictionaryEntryPoint/createDictionaryEntryPoint.cjs`),n=require(`./buildIntlayerDictionary/buildIntlayerDictionary.cjs`),r=require(`./utils/runOnce.cjs`),i=require(`./createType/createModuleAugmentation.cjs`),a=require(`./createType/createType.cjs`),o=require(`./listDictionariesPath.cjs`),s=require(`./loadDictionaries/loadDictionaries.cjs`),c=require(`./buildIntlayerDictionary/writeRemoteDictionary.cjs`),l=require(`./cleanOutputDir.cjs`),u=require(`./writeConfiguration/index.cjs`);let d=require(`node:fs/promises`),f=require(`node:path`),p=require(`@intlayer/config/logger`),m=require(`@intlayer/config/utils`),h=require(`@intlayer/config/package.json`);
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./chunk-Bmb41Sf3.cjs`),t=require(`./createDictionaryEntryPoint/createDictionaryEntryPoint.cjs`),n=require(`./buildIntlayerDictionary/buildIntlayerDictionary.cjs`),r=require(`./utils/runOnce.cjs`),i=require(`./createType/createModuleAugmentation.cjs`),a=require(`./createType/createType.cjs`),o=require(`./listDictionariesPath.cjs`),s=require(`./loadDictionaries/loadDictionaries.cjs`),c=require(`./buildIntlayerDictionary/writeRemoteDictionary.cjs`),l=require(`./cleanOutputDir.cjs`),u=require(`./writeConfiguration/index.cjs`);let d=require(`node:fs/promises`),f=require(`node:path`),p=require(`@intlayer/config/logger`),m=require(`@intlayer/config/utils`),h=require(`@intlayer/config/colors`);h=e.t(h);let g=require(`@intlayer/config/package.json`);g=e.t(g);const _={clean:!1,env:`prod`,format:[`cjs`,`esm`],cacheTimeoutMs:1e3*60*60},v=async(e,v)=>{let y=(0,p.getAppLogger)(e),b=(0,f.join)(e.system.cacheDir,`intlayer-prepared.lock`),x=(0,m.cacheDisk)(e,[`intlayer-version`]),S=await x.get(),C=!!(S&&S===g.default.version),w=await u.isCachedConfigurationUpToDate(e),T=await o.listDictionariesWithStats(e),E=!1;try{let e=await(0,d.stat)(b);E=T.some(t=>t.stats.mtime.getTime()>e.mtime.getTime())}catch{}let D=(await Promise.all(e.plugins??[])).some(e=>!!e.loadDictionaries),{clean:O,format:k,forceRun:A,onIsCached:j,cacheTimeoutMs:M,env:N}={..._,forceRun:!C||!w||E||D,...v??{}};await r.runOnce(b,async()=>{(O||!C)&&await l.cleanOutputDir(e),await x.set(g.default.version);let r=Date.now();y([`Preparing Intlayer`,(0,p.colorize)(`(v${g.default.version})`,h.GREY_DARK)]),await u.writeConfiguration(e);let o=Date.now();y([`Configuration written`,(0,p.colorize)(`(${o-r}ms)`,h.GREY_DARK)],{isVerbose:!0});let d=await s.loadDictionaries(T.map(e=>e.path),e),f=Date.now();y([`Content loaded`,(0,p.colorize)([d.remoteDictionaries.length+d.pluginDictionaries.length>0?[`(Total: ${f-o}ms`,d.localDictionaries.length>0?` - Local: ${d.time.localDictionaries}ms`:``,d.remoteDictionaries.length>0?` - Remote: ${d.time.remoteDictionaries}ms`:``,d.pluginDictionaries.length>0?` - Plugin: ${d.time.pluginDictionaries}ms`:``,`)`].join(``):`(${f-o}ms)`].join(``),h.GREY_DARK)],{isVerbose:!0});let m=await n.buildDictionary([...d.localDictionaries,...d.remoteDictionaries,...d.pluginDictionaries],e,{formats:k,importOtherDictionaries:!1,env:N});await c.writeRemoteDictionary(d.remoteDictionaries,e),await a.createTypes(Object.values(m?.mergedDictionaries??{}).map(e=>e.dictionary),e),await t.createDictionaryEntryPoint(e);let _=Date.now();y([`Dictionaries built`,(0,p.colorize)(`(${_-r}ms)`,h.GREY_DARK)]),await i.createModuleAugmentation(e),y([`Module augmentation built`,(0,p.colorize)(`(${Date.now()-_}ms)`,h.GREY_DARK)],{isVerbose:!0});for await(let t of e.plugins??[]){let{unmergedDictionaries:n,mergedDictionaries:r}=m;await t.afterBuild?.({dictionaries:{unmergedDictionaries:n,mergedDictionaries:r},configuration:e})}y([`Done`,(0,p.colorize)(`${Date.now()-r}ms`,h.GREEN)],{level:`info`,isVerbose:!0})},{forceRun:A,onIsCached:j,cacheTimeoutMs:M})};exports.prepareIntlayer=v;
|
|
2
2
|
//# sourceMappingURL=prepareIntlayer.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepareIntlayer.cjs","names":["packageJson","isCachedConfigurationUpToDate","listDictionariesWithStats","runOnce","cleanOutputDir","ANSIColors","writeConfiguration","loadDictionaries","buildDictionary","writeRemoteDictionary","createTypes","createDictionaryEntryPoint","createModuleAugmentation"],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { cacheDisk } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n env?: 'prod' | 'dev';\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n env: 'prod',\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const resolvedPlugins = await Promise.all(configuration.plugins ?? []);\n const hasPluginLoadDictionaries = resolvedPlugins.some((plugin) =>\n Boolean(plugin.loadDictionaries)\n ); // Disable cache if any plugin because it can have custom behavior\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs, env } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun:\n !isCorrectVersion ||\n !isConfigSimilar ||\n isDictionaryChanged ||\n hasPluginLoadDictionaries,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? ` - Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? ` - Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? ` - Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n { formats: format, importOtherDictionaries: false, env }\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesToBuild = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionary);\n\n await createTypes(dictionariesToBuild, configuration);\n\n await createDictionaryEntryPoint(configuration);\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`, colorize(`${preparationElapsedMs}ms`, ANSIColors.GREEN)],\n {\n level: 'info',\n isVerbose: true,\n }\n );\n },\n {\n forceRun,\n onIsCached,\n cacheTimeoutMs,\n }\n );\n};\n"],"mappings":"0xBA4BA,MAAM,EAAmC,CACvC,MAAO,GACP,IAAK,OACL,OAAQ,CAAC,MAAO,MAAM,CACtB,eAAgB,IAAO,GAAK,GAC7B,CAEY,EAAkB,MAC7B,EACA,IACG,CACH,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,GAAA,EAAA,EAAA,MACJ,EAAc,OAAO,SACrB,yBACD,CAEK,GAAA,EAAA,EAAA,WAAyB,EAAe,CAAC,mBAAmB,CAAC,CAC7D,EAAuB,MAAM,EAAa,KAAK,CAC/C,EAAmB,GACvB,G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UAAW,GACZ,CACF,EAEH,CACE,WACA,aACA,iBACD,CACF"}
|
|
1
|
+
{"version":3,"file":"prepareIntlayer.cjs","names":["packageJson","isCachedConfigurationUpToDate","listDictionariesWithStats","runOnce","cleanOutputDir","ANSIColors","writeConfiguration","loadDictionaries","buildDictionary","writeRemoteDictionary","createTypes","createDictionaryEntryPoint","createModuleAugmentation"],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { cacheDisk } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n env?: 'prod' | 'dev';\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n env: 'prod',\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const resolvedPlugins = await Promise.all(configuration.plugins ?? []);\n const hasPluginLoadDictionaries = resolvedPlugins.some((plugin) =>\n Boolean(plugin.loadDictionaries)\n ); // Disable cache if any plugin because it can have custom behavior\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs, env } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun:\n !isCorrectVersion ||\n !isConfigSimilar ||\n isDictionaryChanged ||\n hasPluginLoadDictionaries,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? ` - Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? ` - Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? ` - Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n { formats: format, importOtherDictionaries: false, env }\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesToBuild = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionary);\n\n await createTypes(dictionariesToBuild, configuration);\n\n await createDictionaryEntryPoint(configuration);\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`, colorize(`${preparationElapsedMs}ms`, ANSIColors.GREEN)],\n {\n level: 'info',\n isVerbose: true,\n }\n );\n },\n {\n forceRun,\n onIsCached,\n cacheTimeoutMs,\n }\n );\n};\n"],"mappings":"40BA6BA,MAAM,EAAmC,CACvC,MAAO,GACP,IAAK,OACL,OAAQ,CAAC,MAAO,MAAM,CACtB,eAAgB,IAAO,GAAK,GAC7B,CAEY,EAAkB,MAC7B,EACA,IACG,CACH,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,GAAA,EAAA,EAAA,MACJ,EAAc,OAAO,SACrB,yBACD,CAEK,GAAA,EAAA,EAAA,WAAyB,EAAe,CAAC,mBAAmB,CAAC,CAC7D,EAAuB,MAAM,EAAa,KAAK,CAC/C,EAAmB,GACvB,GAAwB,IAAyBA,EAAAA,QAAY,SAGzD,EAAkB,MAAMC,EAAAA,8BAA8B,EAAc,CAGpE,EAAwB,MAAMC,EAAAA,0BAA0B,EAAc,CACxE,EAAsB,GAC1B,GAAI,CAEF,IAAM,EAAgB,MAAA,EAAA,EAAA,MAAW,EAAa,CAC9C,EAAsB,EAAsB,KACzC,GACC,EAAW,MAAM,MAAM,SAAS,CAAG,EAAc,MAAM,SAAS,CACnE,MACK,EAGR,IAAM,GADkB,MAAM,QAAQ,IAAI,EAAc,SAAW,EAAE,CAAC,EACpB,KAAM,GACtD,EAAQ,EAAO,iBAChB,CAEK,CAAE,QAAO,SAAQ,WAAU,aAAY,iBAAgB,OAAQ,CACnE,GAAG,EACH,SACE,CAAC,GACD,CAAC,GACD,GACA,EACF,GAAI,GAAW,EAAE,CAClB,CAGD,MAAMC,EA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oB,oBAAsB,EAAE,CAC7C,CAAC,IAAK,GAAe,EAAW,WAAW,CAEL,EAAc,CAErD,MAAMC,EAAAA,2BAA2B,EAAc,CAE/C,IAAM,EAAwB,KAAK,KAAK,CAExC,EAAU,CACR,sBAAA,EAAA,EAAA,UAEE,IAAI,EAAwB,EAAmB,KAC/CN,EAAW,UACZ,CACF,CAAC,CAEF,MAAMO,EAAAA,yBAAyB,EAAc,CAI7C,EACE,CACE,6BAAA,EAAA,EAAA,UAEE,IAN8B,KAAK,KAAK,CAMN,EAAsB,KACxDP,EAAW,UACZ,CACF,CACD,CACE,UAAW,GACZ,CACF,CAID,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CAAE,CACtD,GAAM,CAAE,uBAAsB,sBAAuB,EAErD,MAAM,EAAO,aAAa,CACxB,aAAc,CACZ,uBACA,qBACD,CACD,gBACD,CAAC,CAIJ,EACE,CAAC,QAAA,EAAA,EAAA,UAAiB,GAFS,KAAK,KAAK,CAAG,EAEE,IAAKA,EAAW,MAAM,CAAC,CACjE,CACE,MAAO,OACP,UAAW,GACZ,CACF,EAEH,CACE,WACA,aACA,iBACD,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`);let t=require(`node:path`),n=require(`@intlayer/config/logger`),r=require(`@intlayer/config/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../chunk-Bmb41Sf3.cjs`);let t=require(`node:path`),n=require(`@intlayer/config/logger`),r=require(`@intlayer/config/colors`);r=e.t(r);let i=require(`@intlayer/config/built`);i=e.t(i);let a=require(`@intlayer/core/localization`),o=require(`@intlayer/types/locales`);const s=(e,r)=>[e].flat().map(e=>e.startsWith(`/`)?(0,t.relative)(i.default.system.baseDir,e):e).map(e=>r===!1?e:(0,n.colorizePath)(e,r)).join(`, `),c=(e,t=r.GREEN)=>[e].flat().map(e=>`${(0,a.getLocaleName)(e,o.ENGLISH)} (${e})`).map(e=>t===!1?e:(0,n.colorize)(e,t)).join(`, `);exports.formatLocale=c,exports.formatPath=s;
|
|
2
2
|
//# sourceMappingURL=formatter.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatter.cjs","names":["configuration","ANSIColors","ENGLISH"],"sources":["../../../src/utils/formatter.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport configuration from '@intlayer/config/built';\nimport
|
|
1
|
+
{"version":3,"file":"formatter.cjs","names":["configuration","ANSIColors","ENGLISH"],"sources":["../../../src/utils/formatter.ts"],"sourcesContent":["import { relative } from 'node:path';\nimport configuration from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, colorizePath } from '@intlayer/config/logger';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport { ENGLISH } from '@intlayer/types/locales';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\nexport const formatPath = (\n path: string | string[],\n color?: ANSIColors | false\n) =>\n [path]\n .flat()\n .map((path) =>\n path.startsWith('/') ? relative(configuration.system.baseDir, path) : path\n )\n .map((relativePath) =>\n color === false ? relativePath : colorizePath(relativePath, color)\n )\n .join(`, `);\n\nexport const formatLocale = (\n locale: LocalesValues | LocalesValues[],\n color: ANSIColors | false = ANSIColors.GREEN\n) =>\n [locale]\n .flat()\n .map((locale) => `${getLocaleName(locale, ENGLISH)} (${locale})`)\n .map((text) => (color === false ? text : colorize(text, color)))\n .join(`, `);\n"],"mappings":"6VAQA,MAAa,GACX,EACA,IAEA,CAAC,EAAK,CACH,MAAM,CACN,IAAK,GACJ,EAAK,WAAW,IAAI,EAAA,EAAA,EAAA,UAAYA,EAAAA,QAAc,OAAO,QAAS,EAAK,CAAG,EACvE,CACA,IAAK,GACJ,IAAU,GAAQ,GAAA,EAAA,EAAA,cAA4B,EAAc,EAAM,CACnE,CACA,KAAK,KAAK,CAEF,GACX,EACA,EAA4BC,EAAW,QAEvC,CAAC,EAAO,CACL,MAAM,CACN,IAAK,GAAW,IAAA,EAAA,EAAA,eAAiB,EAAQC,EAAAA,QAAQ,CAAC,IAAI,EAAO,GAAG,CAChE,IAAK,GAAU,IAAU,GAAQ,GAAA,EAAA,EAAA,UAAgB,EAAM,EAAM,CAAE,CAC/D,KAAK,KAAK"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../chunk-Bmb41Sf3.cjs`);const e=require(`../writeJsonIfChanged.cjs`);let t=require(`node:fs/promises`),n=require(`node:path`),r=require(`node:util`);const i=async e=>{let r=await(0,t.readFile)((0,n.join)(e.system.configDir,`configuration.json`),`utf8`);return JSON.parse(r)},a=async e=>{
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../chunk-Bmb41Sf3.cjs`);const e=require(`../writeJsonIfChanged.cjs`);let t=require(`node:fs/promises`),n=require(`node:path`),r=require(`node:util`);const i=async e=>{let r=await(0,t.readFile)((0,n.join)(e.system.configDir,`configuration.json`),`utf8`);return JSON.parse(r)},a=async e=>{let t=o(e);return(0,r.isDeepStrictEqual)(await i(e),t)},o=e=>JSON.parse(JSON.stringify({internationalization:{locales:e.internationalization.locales,defaultLocale:e.internationalization.defaultLocale},editor:e.editor,log:e.log,routing:e.routing,metadata:e.metadata})),s=async r=>{let{system:i}=r,{configDir:a}=i;await(0,t.mkdir)(a,{recursive:!0}),await e.writeJsonIfChanged((0,n.join)(a,`configuration.json`),o(r))};exports.isCachedConfigurationUpToDate=a,exports.writeConfiguration=s;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["writeJsonIfChanged"],"sources":["../../../src/writeConfiguration/index.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport type {\n CustomIntlayerConfig,\n IntlayerConfig,\n} from '@intlayer/types/config';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\n\nconst getCachedConfiguration = async (configuration: IntlayerConfig) => {\n const configFilePath = join(\n configuration.system.configDir,\n 'configuration.json'\n );\n\n const configurationContent = await readFile(configFilePath, 'utf8');\n return JSON.parse(configurationContent);\n};\n\nexport const isCachedConfigurationUpToDate = async (\n configuration: IntlayerConfig\n): Promise<boolean | null> => {\n
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["writeJsonIfChanged"],"sources":["../../../src/writeConfiguration/index.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport type {\n CustomIntlayerConfig,\n IntlayerConfig,\n} from '@intlayer/types/config';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\n\nconst getCachedConfiguration = async (configuration: IntlayerConfig) => {\n const configFilePath = join(\n configuration.system.configDir,\n 'configuration.json'\n );\n\n const configurationContent = await readFile(configFilePath, 'utf8');\n return JSON.parse(configurationContent);\n};\n\nexport const isCachedConfigurationUpToDate = async (\n configuration: IntlayerConfig\n): Promise<boolean | null> => {\n const cleanedConfiguration = cleanConfiguration(configuration);\n const cachedConfiguration = await getCachedConfiguration(configuration);\n\n const isSimilar = isDeepStrictEqual(\n cachedConfiguration,\n cleanedConfiguration\n );\n\n return isSimilar;\n};\n\nconst cleanConfiguration = (configuration: IntlayerConfig): IntlayerConfig => {\n const parsedConfiguration = JSON.parse(\n JSON.stringify({\n internationalization: {\n locales: configuration.internationalization.locales,\n defaultLocale: configuration.internationalization.defaultLocale,\n },\n editor: configuration.editor,\n log: configuration.log,\n routing: configuration.routing,\n metadata: configuration.metadata,\n } as CustomIntlayerConfig)\n );\n\n return parsedConfiguration;\n};\n\nexport const writeConfiguration = async (configuration: IntlayerConfig) => {\n const { system } = configuration;\n const { configDir } = system;\n\n // Ensure target directory exists\n // configDir is expected to be the directory where configuration.json will live\n await mkdir(configDir, { recursive: true });\n\n const configFilePath = join(configDir, 'configuration.json');\n\n const cleanedConfiguration = cleanConfiguration(configuration);\n\n await writeJsonIfChanged(configFilePath, cleanedConfiguration);\n};\n"],"mappings":"iOASA,MAAM,EAAyB,KAAO,IAAkC,CAMtE,IAAM,EAAuB,MAAA,EAAA,EAAA,WAAA,EAAA,EAAA,MAJ3B,EAAc,OAAO,UACrB,qBACD,CAE2D,OAAO,CACnE,OAAO,KAAK,MAAM,EAAqB,EAG5B,EAAgC,KAC3C,IAC4B,CAC5B,IAAM,EAAuB,EAAmB,EAAc,CAQ9D,OAAA,EAAA,EAAA,mBAP4B,MAAM,EAAuB,EAAc,CAIrE,EACD,EAKG,EAAsB,GACE,KAAK,MAC/B,KAAK,UAAU,CACb,qBAAsB,CACpB,QAAS,EAAc,qBAAqB,QAC5C,cAAe,EAAc,qBAAqB,cACnD,CACD,OAAQ,EAAc,OACtB,IAAK,EAAc,IACnB,QAAS,EAAc,QACvB,SAAU,EAAc,SACzB,CAAyB,CAC3B,CAKU,EAAqB,KAAO,IAAkC,CACzE,GAAM,CAAE,UAAW,EACb,CAAE,aAAc,EAItB,MAAA,EAAA,EAAA,OAAY,EAAW,CAAE,UAAW,GAAM,CAAC,CAM3C,MAAMA,EAAAA,oBAAAA,EAAAA,EAAAA,MAJsB,EAAW,qBAAqB,CAE/B,EAAmB,EAAc,CAEA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../chunk-Bmb41Sf3.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`../detectFormatCommand.cjs`),n=require(`./processContentDeclarationContent.cjs`),r=require(`./transformJSONFile.cjs`),i=require(`./writeJSFile.cjs`);let a=require(`node:fs/promises`),o=require(`node:path`),s=require(`@intlayer/
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../chunk-Bmb41Sf3.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`../detectFormatCommand.cjs`),n=require(`./processContentDeclarationContent.cjs`),r=require(`./transformJSONFile.cjs`),i=require(`./writeJSFile.cjs`);let a=require(`node:fs/promises`),o=require(`node:path`),s=require(`@intlayer/unmerged-dictionaries-entry`),c=require(`node:fs`),l=require(`@intlayer/config/defaultValues`),u=require(`@intlayer/core/plugins`),d=require(`node:child_process`),f=require(`node:util`);const p=async(t,r,i)=>{let a=await n.processContentDeclarationContent(t),s=a.content;t.locale?s=(0,u.getPerLocaleDictionary)(a,t.locale).content:i&&(s=(0,u.getFilteredLocalesDictionary)(a,i).content);let c={...t,content:s};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:c,configuration:r});t&&(c=t)}if(!(c.content&&c.key))return c;let l={key:t.key,id:t.id,title:t.title,description:t.description,tags:t.tags,locale:t.locale,fill:t.fill,filled:t.filled,priority:t.priority,importMode:t.importMode,version:t.version,content:s};return e.getFormatFromExtension(t.filePath?(0,o.extname)(t.filePath):`.json`)===`json`&&c.content&&c.key&&(l={$schema:`https://intlayer.org/schema.json`,...l}),l},m={newDictionariesPath:`intlayer-dictionaries`},h=async(e,t,n)=>{let{system:r,compiler:i}=t,{baseDir:a}=r,c=i?.noMetadata??l.COMPILER_NO_METADATA,{newDictionariesPath:u,localeList:d}={...m,...n},h=(0,o.join)(a,u),_=(0,s.getUnmergedDictionaries)(t)[e.key]?.find(t=>t.localId===e.localId),v=await p(e,t,d);if(_?.filePath){let n=(0,f.isDeepStrictEqual)(_,e),r=(0,o.resolve)(t.system.baseDir,_.filePath);return n?{status:`up-to-date`,path:r}:(await g(r,v,t,c),{status:`updated`,path:r})}if(e.filePath){let n=(0,o.resolve)(t.system.baseDir,e.filePath);return await g(n,v,t,c),{status:`created`,path:n}}let y=(0,o.join)(h,`${e.key}.content.json`);return await g(y,v,t,c),{status:`imported`,path:y}},g=async(e,n,s,l)=>{await(0,a.mkdir)((0,o.dirname)(e),{recursive:!0});let u=(0,o.extname)(e);if([`.json`,`.jsonc`,`.json5`].includes(u)){let i=`{}`;if((0,c.existsSync)(e))try{i=await(0,a.readFile)(e,`utf-8`)}catch{}let u=r.transformJSONFile(i,n,l),f=s.system?.tempDir;f&&await(0,a.mkdir)(f,{recursive:!0});let p=`${(0,o.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,m=f?(0,o.join)(f,p):`${e}.${p}`;try{await(0,a.writeFile)(m,u,`utf-8`),await(0,a.rename)(m,e)}catch(e){try{await(0,a.rm)(m,{force:!0})}catch{}throw e}let h=t.detectFormatCommand(s);if(h)try{(0,d.execSync)(h.replace(`{{file}}`,e),{stdio:`inherit`,cwd:s.system.baseDir})}catch(e){console.error(e)}return}await i.writeJSFile(e,n,s,l);try{await(0,a.rm)((0,o.join)(s.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};exports.writeContentDeclaration=h;
|
|
2
2
|
//# sourceMappingURL=writeContentDeclaration.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","DefaultValues","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata =\n compiler?.noMetadata ?? DefaultValues.Compiler.COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":"4jBAyBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IAAM,EACJ,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AAS,EAAa,CAC3B,GAAG,EAAiB,GAAG,IAC3B,GAAI,CACF,MAAA,EAAA,EAAA,WAAgB,EAAU,EAAoB,QAAQ,CACtD,MAAA,EAAA,EAAA,QAAa,EAAU,EAAiB,OACjC,EAAO,CACd,GAAI,CACF,MAAA,EAAA,EAAA,IAAS,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,MAAM,EAGR,IAAM,EAAgBC,EAAAA,oBAAoB,EAAc,CAExD,GAAI,EACF,GAAI,EACF,EAAA,EAAA,UAAS,EAAc,QAAQ,WAAY,EAAiB,CAAE,CAC5D,MAAO,UACP,IAAK,EAAc,OAAO,QAC3B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM,CAIxB,OAGF,MAAMC,EAAAA,YAAY,EAAkB,EAAY,EAAe,EAAW,CAI1E,GAAI,CAKF,MAAA,EAAA,EAAA,KAAA,EAAA,EAAA,MAHE,EAAc,OAAO,SACrB,yBACD,CACsB,CAAE,UAAW,GAAM,CAAC,MACrC"}
|
|
1
|
+
{"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","COMPILER_NO_METADATA","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { COMPILER_NO_METADATA } from '@intlayer/config/defaultValues';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata = compiler?.noMetadata ?? COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":"mkBAyBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IA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,EAAa,CAC3B,GAAG,EAAiB,GAAG,IAC3B,GAAI,CACF,MAAA,EAAA,EAAA,WAAgB,EAAU,EAAoB,QAAQ,CACtD,MAAA,EAAA,EAAA,QAAa,EAAU,EAAiB,OACjC,EAAO,CACd,GAAI,CACF,MAAA,EAAA,EAAA,IAAS,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,MAAM,EAGR,IAAM,EAAgBC,EAAAA,oBAAoB,EAAc,CAExD,GAAI,EACF,GAAI,EACF,EAAA,EAAA,UAAS,EAAc,QAAQ,WAAY,EAAiB,CAAE,CAC5D,MAAO,UACP,IAAK,EAAc,OAAO,QAC3B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM,CAIxB,OAGF,MAAMC,EAAAA,YAAY,EAAkB,EAAY,EAAe,EAAW,CAI1E,GAAI,CAKF,MAAA,EAAA,EAAA,KAAA,EAAA,EAAA,MAHE,EAAc,OAAO,SACrB,yBACD,CACsB,CAAE,UAAW,GAAM,CAAC,MACrC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{writeDynamicDictionary as e}from"./writeDynamicDictionary.mjs";import{writeFetchDictionary as t}from"./writeFetchDictionary.mjs";import{writeMergedDictionaries as n}from"./writeMergedDictionary.mjs";import{writeUnmergedDictionaries as r}from"./writeUnmergedDictionary.mjs";import{
|
|
1
|
+
import{writeDynamicDictionary as e}from"./writeDynamicDictionary.mjs";import{writeFetchDictionary as t}from"./writeFetchDictionary.mjs";import{writeMergedDictionaries as n}from"./writeMergedDictionary.mjs";import{writeUnmergedDictionaries as r}from"./writeUnmergedDictionary.mjs";import{getUnmergedDictionaries as i}from"@intlayer/unmerged-dictionaries-entry";import{IMPORT_MODE as a,OUTPUT_FORMAT as o}from"@intlayer/config/defaultValues";const s={formats:o,importOtherDictionaries:!0,env:`dev`},c=async(o,c,l)=>{let u=c?.build?.importMode??c?.dictionary?.importMode??a,{importOtherDictionaries:d,env:f,formats:p}={...s,...l},m=[...o];if(d){let e=i(c);for(let t of o){let n=e[t.key];if(n?.length>0){let e=n.filter(e=>e.localId!==t.localId);m.push(...e)}}}let h=await r(m,c,f),g=await n(h,c),_={},v=new Set;for(let[e,t]of Object.entries(g)){let n=t.dictionary.importMode??u;(n===`dynamic`||n===`fetch`)&&(_[e]=t),n===`fetch`&&v.add(e)}let y=null;Object.keys(_).length>0&&(y=await e(_,c,p));let b=null;if(y&&v.size>0){let e={};for(let t of v)y[t]&&(e[t]=y[t]);Object.keys(e).length>0&&(b=await t(e,c,p))}return{unmergedDictionaries:h,mergedDictionaries:g,dynamicDictionaries:y,fetchDictionaries:b}};export{c as buildDictionary};
|
|
2
2
|
//# sourceMappingURL=buildIntlayerDictionary.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildIntlayerDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/buildIntlayerDictionary.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"buildIntlayerDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/buildIntlayerDictionary.ts"],"sourcesContent":["import { IMPORT_MODE, OUTPUT_FORMAT } from '@intlayer/config/defaultValues';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport {\n type LocalizedDictionaryOutput,\n writeDynamicDictionary,\n} from './writeDynamicDictionary';\nimport { writeFetchDictionary } from './writeFetchDictionary';\nimport { writeMergedDictionaries } from './writeMergedDictionary';\nimport { writeUnmergedDictionaries } from './writeUnmergedDictionary';\n\nexport type BuildDictionariesOptions = Partial<{\n formats: typeof OUTPUT_FORMAT;\n importOtherDictionaries: boolean;\n env: 'prod' | 'dev';\n}>;\n\nconst defaultOptions = {\n formats: OUTPUT_FORMAT,\n importOtherDictionaries: true,\n env: 'dev',\n} as const satisfies BuildDictionariesOptions;\n\n/**\n * This function transpile the bundled code to to make dictionaries as JSON files\n */\nexport const buildDictionary = async (\n localDictionariesEntries: Dictionary[],\n configuration: IntlayerConfig,\n options?: BuildDictionariesOptions\n) => {\n const importMode =\n configuration?.build?.importMode ??\n configuration?.dictionary?.importMode ??\n IMPORT_MODE;\n\n const { importOtherDictionaries, env, formats } = {\n ...defaultOptions,\n ...options,\n };\n\n const unmergedDictionariesToUpdate: Dictionary[] = [\n ...localDictionariesEntries,\n ];\n\n if (importOtherDictionaries) {\n const prevUnmergedDictionaries: Record<string, Dictionary[]> =\n getUnmergedDictionaries(configuration);\n\n // Reinsert other dictionaries with the same key to avoid merging errors\n for (const dictionaryToWrite of localDictionariesEntries) {\n const allPrebuiltUnmergedDictionaries =\n prevUnmergedDictionaries[dictionaryToWrite.key];\n\n if (allPrebuiltUnmergedDictionaries?.length > 0) {\n // Do not add the same dictionary again by filtering out the one with the same localId\n const otherUnmergedDictionaries =\n allPrebuiltUnmergedDictionaries.filter(\n (unmergedDictionary) =>\n unmergedDictionary.localId !== dictionaryToWrite.localId\n );\n\n unmergedDictionariesToUpdate.push(...otherUnmergedDictionaries);\n }\n }\n }\n\n const unmergedDictionaries = await writeUnmergedDictionaries(\n unmergedDictionariesToUpdate,\n configuration,\n env\n );\n\n const mergedDictionaries = await writeMergedDictionaries(\n unmergedDictionaries,\n configuration\n );\n\n const dictionariesToBuildDynamic: typeof mergedDictionaries = {};\n const keysToBuildFetch = new Set<string>();\n\n for (const [key, mergedResult] of Object.entries(mergedDictionaries)) {\n const dictionary = mergedResult.dictionary;\n const mode = dictionary.importMode ?? importMode;\n\n if (mode === 'dynamic' || mode === 'fetch') {\n dictionariesToBuildDynamic[key] = mergedResult;\n }\n\n if (mode === 'fetch') {\n keysToBuildFetch.add(key);\n }\n }\n\n let dynamicDictionaries: LocalizedDictionaryOutput | null = null;\n\n if (Object.keys(dictionariesToBuildDynamic).length > 0) {\n dynamicDictionaries = await writeDynamicDictionary(\n dictionariesToBuildDynamic,\n configuration,\n formats\n );\n }\n\n let fetchDictionaries: LocalizedDictionaryOutput | null = null;\n\n if (dynamicDictionaries && keysToBuildFetch.size > 0) {\n const dictionariesToBuildFetch: LocalizedDictionaryOutput = {};\n\n for (const key of keysToBuildFetch) {\n if (dynamicDictionaries[key]) {\n dictionariesToBuildFetch[key] = dynamicDictionaries[key];\n }\n }\n\n if (Object.keys(dictionariesToBuildFetch).length > 0) {\n fetchDictionaries = await writeFetchDictionary(\n dictionariesToBuildFetch,\n configuration,\n formats\n );\n }\n }\n\n return {\n unmergedDictionaries,\n mergedDictionaries,\n dynamicDictionaries,\n fetchDictionaries,\n };\n};\n"],"mappings":"wbAkBA,MAAM,EAAiB,CACrB,QAAS,EACT,wBAAyB,GACzB,IAAK,MACN,CAKY,EAAkB,MAC7B,EACA,EACA,IACG,CACH,IAAM,EACJ,GAAe,OAAO,YACtB,GAAe,YAAY,YAC3B,EAEI,CAAE,0BAAyB,MAAK,WAAY,CAChD,GAAG,EACH,GAAG,EACJ,CAEK,EAA6C,CACjD,GAAG,EACJ,CAED,GAAI,EAAyB,CAC3B,IAAM,EACJ,EAAwB,EAAc,CAGxC,IAAK,IAAM,KAAqB,EAA0B,CACxD,IAAM,EACJ,EAAyB,EAAkB,KAE7C,GAAI,GAAiC,OAAS,EAAG,CAE/C,IAAM,EACJ,EAAgC,OAC7B,GACC,EAAmB,UAAY,EAAkB,QACpD,CAEH,EAA6B,KAAK,GAAG,EAA0B,GAKrE,IAAM,EAAuB,MAAM,EACjC,EACA,EACA,EACD,CAEK,EAAqB,MAAM,EAC/B,EACA,EACD,CAEK,EAAwD,EAAE,CAC1D,EAAmB,IAAI,IAE7B,IAAK,GAAM,CAAC,EAAK,KAAiB,OAAO,QAAQ,EAAmB,CAAE,CAEpE,IAAM,EADa,EAAa,WACR,YAAc,GAElC,IAAS,WAAa,IAAS,WACjC,EAA2B,GAAO,GAGhC,IAAS,SACX,EAAiB,IAAI,EAAI,CAI7B,IAAI,EAAwD,KAExD,OAAO,KAAK,EAA2B,CAAC,OAAS,IACnD,EAAsB,MAAM,EAC1B,EACA,EACA,EACD,EAGH,IAAI,EAAsD,KAE1D,GAAI,GAAuB,EAAiB,KAAO,EAAG,CACpD,IAAM,EAAsD,EAAE,CAE9D,IAAK,IAAM,KAAO,EACZ,EAAoB,KACtB,EAAyB,GAAO,EAAoB,IAIpD,OAAO,KAAK,EAAyB,CAAC,OAAS,IACjD,EAAoB,MAAM,EACxB,EACA,EACA,EACD,EAIL,MAAO,CACL,uBACA,qBACA,sBACA,oBACD"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import{parallelize as e}from"../utils/parallelize.mjs";import{writeFileIfChanged as t}from"../writeFileIfChanged.mjs";import{writeJsonIfChanged as n}from"../writeJsonIfChanged.mjs";import{mkdir as r}from"node:fs/promises";import{
|
|
2
|
-
`);return a+=`const content = {\n${
|
|
3
|
-
`),
|
|
4
|
-
`),a},d=
|
|
1
|
+
import{parallelize as e}from"../utils/parallelize.mjs";import{writeFileIfChanged as t}from"../writeFileIfChanged.mjs";import{writeJsonIfChanged as n}from"../writeJsonIfChanged.mjs";import{mkdir as r}from"node:fs/promises";import{resolve as i}from"node:path";import{colorizePath as a}from"@intlayer/config/logger";import{OUTPUT_FORMAT as o}from"@intlayer/config/defaultValues";import{getPerLocaleDictionary as s}from"@intlayer/core/plugins";const c=`json`,l=`_loadjson`,u=(e,t,n,r=`esm`)=>{let i=Object.keys(t).sort((e,t)=>String(e).localeCompare(String(t))).map(e=>` '${e}': () => loadContent('${n}', '${e}')`).join(`,
|
|
2
|
+
`),a=e;return a+=`const content = {\n${i}\n};\n\n`,r===`esm`&&(a+=`export default content;
|
|
3
|
+
`),r===`cjs`&&(a+=`module.exports = content;
|
|
4
|
+
`),a},d=(e,t)=>{let n=`const loadContent = (key) => ({\n${[...t].sort((e,t)=>String(e).localeCompare(String(t))).map(t=>e===`esm`?` '${t}': () => import(\`./${c}/\${key}/${t}.json\`).then(m => m.default)`:` '${t}': () => Promise.resolve(require(\`./${c}/\${key}/${t}.json\`))`).join(`,
|
|
5
|
+
`)}\n});\n`;return e===`esm`?`${n}\nexport { loadContent };\n`:`${n}\nmodule.exports = { loadContent };\n`},f=(e,t=`esm`)=>{let n=t===`cjs`?`cjs`:`mjs`;return t===`esm`?`import { loadContent } from './${l}.${n}';\n\nconst content = loadContent('${e}');\n\nexport default content;\n`:`const { loadContent } = require('./${l}.${n}');\n\nmodule.exports = loadContent('${e}');\n`},p=async(u,p,m=o)=>{let{locales:h,defaultLocale:g}=p.internationalization,{dynamicDictionariesDir:_}=p.system,v=i(_,c);await r(v,{recursive:!0}),await e(m,async e=>{let n=e===`cjs`?`cjs`:`mjs`;await t(i(_,`${l}.${n}`),d(e,h)).catch(e=>{console.error(`Error creating dynamic ${a(i(_,`${l}.${n}`))}:`,e)})});let y={};return await e(Object.entries(u).sort(([e],[t])=>String(e).localeCompare(String(t))),async([o,c])=>{if(o===`undefined`)return;let l={},u=i(v,o);await r(u,{recursive:!0}),await e(h,async e=>{let t=s(c.dictionary,e,g),r=i(u,`${e}.json`);await n(r,t).catch(t=>{console.error(`Error creating localized ${o}/${e}.json:`,t)}),l[e]={dictionaryPath:r,dictionary:t}}),y[o]=l,await e(m,async e=>{let n=e===`cjs`?`cjs`:`mjs`,r=f(o,e);await t(i(_,`${o}.${n}`),r).catch(e=>{console.error(`Error creating dynamic ${a(i(_,`${o}.${n}`))}:`,e)})})}),y};export{u as buildEntryPointContent,f as generateDictionaryEntryPoint,d as generateDynamicLoadContentModule,p as writeDynamicDictionary};
|
|
5
6
|
//# sourceMappingURL=writeDynamicDictionary.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeDynamicDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeDynamicDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport {
|
|
1
|
+
{"version":3,"file":"writeDynamicDictionary.mjs","names":[],"sources":["../../../src/buildIntlayerDictionary/writeDynamicDictionary.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { OUTPUT_FORMAT } from '@intlayer/config/defaultValues';\nimport { colorizePath } from '@intlayer/config/logger';\nimport { getPerLocaleDictionary } from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { parallelize } from '../utils/parallelize';\nimport { writeFileIfChanged } from '../writeFileIfChanged';\nimport { writeJsonIfChanged } from '../writeJsonIfChanged';\nimport type { MergedDictionaryOutput } from './writeMergedDictionary';\n\nexport type DictionaryResult = {\n dictionaryPath: string;\n dictionary: Dictionary;\n};\n\nexport type LocalizedDictionaryResult = Partial<\n Record<Locale, DictionaryResult>\n>;\n\nexport type LocalizedDictionaryOutput = Record<\n string,\n LocalizedDictionaryResult\n>;\n\nconst DICTIONARIES_SUBDIR = 'json'; // Necessary to add a static first dir for Turbopack\nconst LOAD_CONTENT_MODULE = '_loadjson';\n\n/**\n * Assembles the entry point file content from a pre-built preamble (import/require line),\n * the locale→path record, the dictionary key, and the output format.\n * Shared by all dictionary entry point generators.\n */\nexport const buildEntryPointContent = (\n preamble: string,\n localizedDictionariesPathsRecord: LocalizedDictionaryResult,\n key: string,\n format: 'cjs' | 'esm' = 'esm'\n): string => {\n const formattedDictionaryMap: string = Object.keys(\n localizedDictionariesPathsRecord\n )\n .sort((a, b) => String(a).localeCompare(String(b)))\n .map((locale) => ` '${locale}': () => loadContent('${key}', '${locale}')`)\n .join(',\\n');\n\n let content = preamble;\n content += `const content = {\\n${formattedDictionaryMap}\\n};\\n\\n`;\n if (format === 'esm') content += `export default content;\\n`;\n if (format === 'cjs') content += `module.exports = content;\\n`;\n\n return content;\n};\n\n/**\n * Generates the content of the shared `loadContent` module written once per\n * output directory. Locales are baked in so each dynamic import has only one\n * variable (`key`), making it statically analyzable by Vite/Rollup.\n */\nexport const generateDynamicLoadContentModule = (\n format: 'cjs' | 'esm',\n locales: string[]\n): string => {\n const sortedLocales = [...locales].sort((a, b) =>\n String(a).localeCompare(String(b))\n );\n\n const localeEntries = sortedLocales\n .map((locale) =>\n format === 'esm'\n ? ` '${locale}': () => import(\\`./${DICTIONARIES_SUBDIR}/\\${key}/${locale}.json\\`).then(m => m.default)`\n : ` '${locale}': () => Promise.resolve(require(\\`./${DICTIONARIES_SUBDIR}/\\${key}/${locale}.json\\`))`\n )\n .join(',\\n');\n\n const body = `const loadContent = (key) => ({\\n${localeEntries}\\n});\\n`;\n\n if (format === 'esm') return `${body}\\nexport { loadContent };\\n`;\n return `${body}\\nmodule.exports = { loadContent };\\n`;\n};\n\n/**\n * Generates the content of a dictionary entry point file.\n * `loadContent` is imported from the shared module and called with the key.\n */\nexport const generateDictionaryEntryPoint = (\n key: string,\n format: 'cjs' | 'esm' = 'esm'\n): string => {\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n if (format === 'esm') {\n return (\n `import { loadContent } from './${LOAD_CONTENT_MODULE}.${extension}';\\n\\n` +\n `const content = loadContent('${key}');\\n\\n` +\n `export default content;\\n`\n );\n }\n return (\n `const { loadContent } = require('./${LOAD_CONTENT_MODULE}.${extension}');\\n\\n` +\n `module.exports = loadContent('${key}');\\n`\n );\n};\n\n/**\n * Write the localized dictionaries to the dictionariesDir\n * @param mergedDictionaries - The merged dictionaries\n * @param configuration - The configuration\n * @returns The final dictionaries\n *\n * @example\n * ```ts\n * const unmergedDictionaries = await writeUnmergedDictionaries(dictionaries);\n * const finalDictionaries = await writeFinalDictionaries(unmergedDictionaries);\n * console.log(finalDictionaries);\n *\n * // .intlayer/dynamic_dictionary/dictionaries/en_home.json\n * // .intlayer/dynamic_dictionary/dictionaries/fr_home.json\n * ```\n */\nexport const writeDynamicDictionary = async (\n mergedDictionaries: MergedDictionaryOutput,\n configuration: IntlayerConfig,\n formats: ('cjs' | 'esm')[] = OUTPUT_FORMAT\n): Promise<LocalizedDictionaryOutput> => {\n const { locales, defaultLocale } = configuration.internationalization;\n const { dynamicDictionariesDir } = configuration.system;\n\n const dictDir = resolve(dynamicDictionariesDir, DICTIONARIES_SUBDIR);\n await mkdir(dictDir, { recursive: true });\n await parallelize(formats, async (format) => {\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n await writeFileIfChanged(\n resolve(dynamicDictionariesDir, `${LOAD_CONTENT_MODULE}.${extension}`),\n generateDynamicLoadContentModule(format, locales)\n ).catch((err) => {\n console.error(\n `Error creating dynamic ${colorizePath(resolve(dynamicDictionariesDir, `${LOAD_CONTENT_MODULE}.${extension}`))}:`,\n err\n );\n });\n });\n\n const resultDictionariesPaths: LocalizedDictionaryOutput = {};\n\n // Merge dictionaries with the same key and write to dictionariesDir\n await parallelize(\n Object.entries(mergedDictionaries).sort(([a], [b]) =>\n String(a).localeCompare(String(b))\n ),\n async ([key, dictionaryEntry]) => {\n if (key === 'undefined') return;\n\n const localizedDictionariesPathsRecord: LocalizedDictionaryResult = {};\n\n const keyDir = resolve(dictDir, key);\n await mkdir(keyDir, { recursive: true });\n\n await parallelize(locales, async (locale) => {\n const localizedDictionary = getPerLocaleDictionary(\n dictionaryEntry.dictionary,\n locale,\n defaultLocale\n );\n\n // Directory structure: json/key/locale.json\n const resultFilePath = resolve(keyDir, `${locale}.json`);\n\n await writeJsonIfChanged(resultFilePath, localizedDictionary).catch(\n (err) => {\n console.error(\n `Error creating localized ${key}/${locale}.json:`,\n err\n );\n }\n );\n\n localizedDictionariesPathsRecord[locale] = {\n dictionaryPath: resultFilePath,\n dictionary: localizedDictionary,\n };\n });\n\n resultDictionariesPaths[key] = localizedDictionariesPathsRecord;\n\n await parallelize(formats, async (format) => {\n const extension = format === 'cjs' ? 'cjs' : 'mjs';\n const content = generateDictionaryEntryPoint(key, format);\n\n await writeFileIfChanged(\n resolve(dynamicDictionariesDir, `${key}.${extension}`),\n content\n ).catch((err) => {\n console.error(\n `Error creating dynamic ${colorizePath(resolve(dynamicDictionariesDir, `${key}.${extension}`))}:`,\n err\n );\n });\n });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eFileIfChanged.mjs";import{mkdir as n}from"node:fs/promises";import{relative as r,resolve as i}from"node:path";import{colorizePath as a}from"@intlayer/config/logger";import{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
`)
|
|
1
|
+
import{parallelize as e}from"../utils/parallelize.mjs";import{writeFileIfChanged as t}from"../writeFileIfChanged.mjs";import{mkdir as n}from"node:fs/promises";import{relative as r,resolve as i}from"node:path";import{colorizePath as a}from"@intlayer/config/logger";import{normalizePath as o}from"@intlayer/config/utils";import{OUTPUT_FORMAT as s}from"@intlayer/config/defaultValues";const c=`_loadjson`,l=(e,t,n)=>{let r=[...n].sort((e,t)=>String(e).localeCompare(String(t))),i=e===`cjs`?`cjs`:`mjs`,a=`const loadContent = (key) => {
|
|
2
|
+
const dynContent = loadContentDyn(key);
|
|
3
|
+
return {\n${r.map(e=>` '${e}': async () => {\n try {\n const res = await fetch(\`\${configuration.editor.liveSyncURL}/dictionaries/\${key}/${e}\`);\n return await res.json();\n } catch {\n return dynContent['${e}']();\n }\n }`).join(`,
|
|
4
|
+
`)}\n };\n};\n`;return e===`esm`?`import { configuration } from 'intlayer';\nimport { loadContent as loadContentDyn } from '${t}/${c}.${i}';\n\n${a}\nexport { loadContent };\n`:`const { configuration } = require('intlayer');\nconst { loadContent: loadContentDyn } = require('${t}/${c}.${i}');\n\n${a}\nmodule.exports = { loadContent };\n`},u=(e,t=`esm`)=>{let n=t===`cjs`?`cjs`:`mjs`;return t===`esm`?`import { loadContent } from './${c}.${n}';\n\nconst content = loadContent('${e}');\n\nexport default content;\n`:`const { loadContent } = require('./${c}.${n}');\n\nmodule.exports = loadContent('${e}');\n`},d=async(d,f,p=s)=>{let{fetchDictionariesDir:m,dynamicDictionariesDir:h}=f.system,{locales:g}=f.internationalization,_=o(r(m,h));return _.startsWith(`.`)||(_=`./${_}`),await n(i(m),{recursive:!0}),await e(p,async e=>{let n=e===`cjs`?`cjs`:`mjs`;await t(i(m,`${c}.${n}`),l(e,_,g)).catch(e=>{console.error(`Error creating fetch ${a(i(m,`${c}.${n}`))}:`,e)})}),await e(Object.entries(d),async([n])=>{n!==`undefined`&&await e(p,async e=>{let r=e===`cjs`?`cjs`:`mjs`,o=u(n,e);await t(i(m,`${n}.${r}`),o).catch(e=>{console.error(`Error creating fetch ${a(i(m,`${n}.${r}`))}:`,e)})})}),{}};export{u as generateDictionaryEntryPoint,l as generateFetchLoadContentModule,d as writeFetchDictionary};
|
|
5
5
|
//# sourceMappingURL=writeFetchDictionary.mjs.map
|