{"version":3,"file":"writeJSFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/writeJSFile.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, extname, join } from 'node:path';\nimport { getAppLogger, logger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport { getContentDeclarationFileTemplate } from '../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate';\nimport {\n  type Extension,\n  getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport { transformJSFile } from './transformJSFile';\n\n/**\n * Updates a JavaScript/TypeScript file based on the provided JSON instructions.\n * It targets a specific dictionary object within the file (identified by its 'key' property)\n * and updates its 'content' entries. Currently, it focuses on modifying arguments\n * of 't' (translation) function calls.\n */\nexport const writeJSFile = async (\n  filePath: string,\n  dictionary: Dictionary,\n  configuration: IntlayerConfig,\n  noMetadata?: boolean\n): Promise<void> => {\n  const mergedDictionary = {\n    ...configuration.dictionary,\n    ...dictionary,\n  };\n\n  const appLogger = getAppLogger(configuration);\n\n  // Check if the file exist\n  if (!existsSync(filePath)) {\n    const fileExtension = extname(filePath) as Extension;\n\n    const format = getFormatFromExtension(fileExtension);\n\n    appLogger('File does not exist, creating it', {\n      isVerbose: true,\n    });\n    const template = await getContentDeclarationFileTemplate(\n      mergedDictionary.key,\n      format,\n      // Filter out undefined values\n      Object.fromEntries(\n        Object.entries({\n          id: noMetadata ? undefined : mergedDictionary.id,\n          locale: noMetadata ? undefined : mergedDictionary.locale,\n          filled: noMetadata ? undefined : mergedDictionary.filled,\n          fill: noMetadata ? undefined : mergedDictionary.fill,\n          description: noMetadata ? undefined : mergedDictionary.description,\n          title: noMetadata ? undefined : mergedDictionary.title,\n          tags: noMetadata ? undefined : mergedDictionary.tags,\n          version: noMetadata ? undefined : mergedDictionary.version,\n          priority: noMetadata ? undefined : mergedDictionary.priority,\n          importMode: noMetadata ? undefined : mergedDictionary.importMode,\n        }).filter(([, value]) => value !== undefined)\n      ),\n      noMetadata\n    );\n\n    const tempDir = configuration.system?.tempDir;\n    if (tempDir) {\n      await mkdir(tempDir, { recursive: true });\n    }\n\n    const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n    const tempPath = tempDir\n      ? join(tempDir, tempFileName)\n      : `${filePath}.${tempFileName}`;\n    try {\n      await writeFile(tempPath, template, 'utf-8');\n      await rename(tempPath, filePath);\n    } catch (error) {\n      try {\n        await rm(tempPath, { force: true });\n      } catch {\n        // Ignore\n      }\n      throw error;\n    }\n  }\n\n  let fileContent = await readFile(filePath, 'utf-8');\n\n  if (fileContent === '') {\n    const format = getFormatFromExtension(extname(filePath) as Extension);\n\n    fileContent = await getContentDeclarationFileTemplate(\n      mergedDictionary.key,\n      format,\n      {},\n      noMetadata\n    );\n  }\n\n  const finalCode = await transformJSFile(\n    fileContent,\n    dictionary,\n    dictionary.locale as any,\n    noMetadata\n  );\n\n  // Write the modified code back to the file\n  const tempDir = configuration.system?.tempDir;\n  if (tempDir) {\n    await mkdir(tempDir, { recursive: true });\n  }\n\n  const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n  const tempPath = tempDir\n    ? join(tempDir, tempFileName)\n    : `${filePath}.${tempFileName}`;\n  try {\n    await writeFile(tempPath, finalCode, 'utf-8');\n    await rename(tempPath, filePath);\n    logger(`Successfully updated ${filePath}`, {\n      level: 'info',\n      isVerbose: true,\n    });\n  } catch (error) {\n    try {\n      await rm(tempPath, { force: true });\n    } catch {\n      // Ignore\n    }\n    const err = error as Error;\n    logger(`Failed to write updated file: ${filePath}`, {\n      level: 'error',\n    });\n    throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);\n  }\n\n  const formatCommand = detectFormatCommand(configuration);\n\n  if (formatCommand) {\n    try {\n      execSync(formatCommand.replace('{{file}}', filePath), {\n        stdio: 'inherit',\n        cwd: configuration.system.baseDir,\n      });\n    } catch (error) {\n      console.error(error);\n    }\n  }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAc,OACzB,UACA,YACA,eACA,eACkB;CAClB,MAAM,mBAAmB;EACvB,GAAG,cAAc;EACjB,GAAG;CACL;CAEA,MAAM,YAAY,aAAa,aAAa;CAG5C,IAAI,CAAC,WAAW,QAAQ,GAAG;EAGzB,MAAM,SAAS,uBAFO,QAAQ,QAEoB,CAAC;EAEnD,UAAU,oCAAoC,EAC5C,WAAW,KACb,CAAC;EACD,MAAM,WAAW,MAAM,kCACrB,iBAAiB,KACjB,QAEA,OAAO,YACL,OAAO,QAAQ;GACb,IAAI,aAAa,SAAY,iBAAiB;GAC9C,QAAQ,aAAa,SAAY,iBAAiB;GAClD,QAAQ,aAAa,SAAY,iBAAiB;GAClD,MAAM,aAAa,SAAY,iBAAiB;GAChD,aAAa,aAAa,SAAY,iBAAiB;GACvD,OAAO,aAAa,SAAY,iBAAiB;GACjD,MAAM,aAAa,SAAY,iBAAiB;GAChD,SAAS,aAAa,SAAY,iBAAiB;GACnD,UAAU,aAAa,SAAY,iBAAiB;GACpD,YAAY,aAAa,SAAY,iBAAiB;EACxD,CAAC,EAAE,QAAQ,GAAG,WAAW,UAAU,MAAS,CAC9C,GACA,UACF;EAEA,MAAM,UAAU,cAAc,QAAQ;EACtC,IAAI,SACF,MAAM,MAAM,SAAS,EAAE,WAAW,KAAK,CAAC;EAG1C,MAAM,eAAe,GAAG,SAAS,QAAQ,EAAE,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,EAAE;EAChG,MAAM,WAAW,UACb,KAAK,SAAS,YAAY,IAC1B,GAAG,SAAS,GAAG;EACnB,IAAI;GACF,MAAM,UAAU,UAAU,UAAU,OAAO;GAC3C,MAAM,OAAO,UAAU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