import{isPrimitive as j}from"../../../../utils/guards/is-primitive.js";import{getNodeAttribute as c}from"../markdoc/helpers/get-node-attribute.js";import{getVariable as N}from"../markdoc/helpers/get-variable.js";import{isTag as v}from"../markdoc/helpers/guards/is-tag.js";import{isNode as E}from"../markdoc/helpers/guards/is-node.js";import{isConditionalNode as S}from"../markdoc/helpers/guards/is-conditional-node.js";import{isVariable as w}from"../markdoc/helpers/guards/is-variable.js";import{isExampleNode as x}from"../markdoc/helpers/guards/is-example-node.js";import{isFenceNode as C}from"../markdoc/helpers/guards/is-fence-node.js";function n(i,r={}){const a=[];for(const e of i){if(j(e)){const t=r.isTrim?l(String(e)):String(e);t&&a.push(t)}else if(E(e))switch(e.type){case"text":a.push(n([c(e,"content")],r));break;case"code":a.push(`\`${n([c(e,"content")],r)}\``);break;case"blockquote":a.push(`> ${n(e.children,r)}
`);break;case"fence":const t=c(e,"process")===!1;a.push(d(e,r,t));break;case"list":const m=c(e,"ordered")||!1,u=c(e,"marker"),f=e.children.map((s,h)=>`${" ".repeat((r?.indent??0)*2)}${m?h+1:""}${u} ${n([s],{...r??{},indent:(r?.indent??0)+1})}`);a.push(`${f.join("")}
`);break;case"item":a.push(e.children.map(s=>`${n([s],r).trimEnd()}
`).join(""));break;case"thead":const p=e.children.map(s=>n([s],r));a.push(`${p}| ${" --- |".repeat(e.children?.[0]?.children.length)}
`);break;case"tr":const k=e.children.map(s=>n([s],r));a.push(`| ${k.join(" | ")} |
`);break;case"em":a.push(`*${n(e.children,r)}*`);break;case"strong":a.push(`**${n(e.children,r)}**`);break;case"softbreak":case"hardbreak":a.push(`
`);break;case"hr":a.push(`

---

`);break;case"heading":const b=c(e,"level")??0;a.push(`${"#".repeat(b)} ${n(e.children,r)}
`);break;case"image":const $=c(e,"alt")||"",o=c(e,"src")||"";a.push(`![${$}](${o})`);break;case"link":const g=c(e,"href")||"";a.push(`[${n(e.children,r)}](${g})`);break;case"paragraph":case"table":a.push(`${n(e.children,r)}
`);break;case"tag":if(S(e)&&r.skipConditionals)continue;if(x(e)){a.push(...e.children.map(s=>{if(C(s)){const h=c(s,"process")!==!0;return d(s,r,h)}return n([s],r)}));continue}a.push(`${n(e.children,r)}`);break;default:a.push(n(e.children,r));break}else v(e)&&a.push(n(e.children,r));w(e)&&a.push(n([N(e,r.variables)],r))}return r.isTrim?l(a.map(e=>l(e)).join("")):a.join("")}function l(i){return i.replace(/^[ \t\r\f]+|[ \t\r\f]+$/g,"")}function d(i,r={},a=!1){const e=c(i,"title");return`
\`\`\`${c(i,"language")||""}${e?` ${e}`:""}
${a?(c(i,"content")||"").trimEnd():n(i.children,r).trimEnd()}
\`\`\`
`}export{n as toMarkdown};
