{"version":3,"file":"writeMarkdownFile.cjs","names":["MARKDOWN","detectFormatCommand"],"sources":["../../../src/writeContentDeclaration/writeMarkdownFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { MARKDOWN } from '@intlayer/types/nodeType';\nimport { detectFormatCommand } from '../detectFormatCommand';\n\nconst stringifyYamlFrontmatter = (fields: Record<string, any>): string =>\n  Object.entries(fields)\n    .filter(([, value]) => value !== undefined && value !== null)\n    .map(([key, value]) => {\n      if (Array.isArray(value)) {\n        return `${key}:\\n${value.map((item) => `  - ${JSON.stringify(item)}`).join('\\n')}`;\n      }\n      if (\n        typeof value === 'string' &&\n        (value.includes(':') || value.includes('\\n') || value.includes('#'))\n      ) {\n        return `${key}: ${JSON.stringify(value)}`;\n      }\n      return `${key}: ${value}`;\n    })\n    .join('\\n');\n\n// Strips YAML frontmatter from a markdown string, returning only the body\nconst getMarkdownBody = (content: string): string => {\n  const lines = content.split(/\\r?\\n/);\n  const firstNonEmptyIndex = lines.findIndex((line) => line.trim() !== '');\n\n  if (firstNonEmptyIndex === -1 || lines[firstNonEmptyIndex].trim() !== '---') {\n    return content;\n  }\n\n  let endIndex = -1;\n  for (let i = firstNonEmptyIndex + 1; i < lines.length; i++) {\n    if (lines[i].trim() === '---') {\n      endIndex = i;\n      break;\n    }\n  }\n\n  if (endIndex === -1) return content;\n\n  return lines\n    .slice(endIndex + 1)\n    .join('\\n')\n    .trimStart();\n};\n\n// Fields that are auto-generated / internal and must not appear in frontmatter\nconst EXCLUDED_FRONTMATTER_KEYS = new Set<string>([\n  'content',\n  '$schema',\n  'filePath',\n  'localId',\n  'localIds',\n  'projectIds',\n]);\n\nexport const writeMarkdownFile = async (\n  absoluteFilePath: string,\n  dictionary: Dictionary,\n  configuration: IntlayerConfig\n): Promise<void> => {\n  const content = dictionary.content as any;\n  const markdownRaw =\n    typeof content === 'object' && content?.nodeType === MARKDOWN\n      ? (content[MARKDOWN] ?? '')\n      : '';\n  // content.markdown now stores the full file (frontmatter + body); extract only the body\n  const markdownBody = getMarkdownBody(markdownRaw);\n\n  const frontmatterFields = Object.fromEntries(\n    Object.entries(dictionary).filter(\n      ([k, v]) => !EXCLUDED_FRONTMATTER_KEYS.has(k) && v !== undefined\n    )\n  );\n\n  const frontmatterStr = stringifyYamlFrontmatter(frontmatterFields);\n  const fileContent = `---\\n${frontmatterStr}\\n---\\n\\n${markdownBody}`;\n\n  const dir = dirname(absoluteFilePath);\n  await mkdir(dir, { recursive: true });\n\n  const tempDir = configuration.system?.tempDir;\n  if (tempDir) await mkdir(tempDir, { recursive: true });\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\n  try {\n    await writeFile(tempPath, fileContent, '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  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"],"mappings":";;;;;;;;;AAQA,MAAM,4BAA4B,WAChC,OAAO,QAAQ,OAAO,CACnB,QAAQ,GAAG,WAAW,UAAU,UAAa,UAAU,KAAK,CAC5D,KAAK,CAAC,KAAK,WAAW;AACrB,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,GAAG,IAAI,KAAK,MAAM,KAAK,SAAS,OAAO,KAAK,UAAU,KAAK,GAAG,CAAC,KAAK,KAAK;AAElF,KACE,OAAO,UAAU,aACh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