import{MediaTypes as y}from"../../constants.js";const A="boundary-separator",d=n=>typeof n=="object"&&n!==null,$=(n,r)=>r?.contentMediaType?r.contentMediaType:r?.format==="binary"?"application/octet-stream":typeof n=="object"&&n!==null?"application/json":"text/plain",S=n=>{const r=[];if(n.event!==void 0&&r.push(`event: ${n.event}`),n.data!==void 0){const t=n.data;(typeof t=="string"?t:JSON.stringify(t)).split(`
`).forEach(o=>{r.push(`data: ${o}`)})}return n.id!==void 0&&r.push(`id: ${n.id}`),n.retry!==void 0&&r.push(`retry: ${n.retry}`),r.join(`
`)},l=(n,r)=>typeof n!="string"||n!=="string"?n:r?.format==="binary"?"[Binary data]":r?.format==="byte"?"[Base64 encoded data]":n,T=(n,r)=>{if(!r?.fields)return n;const t={...n};for(const e of r.fields)t[e.name]!==void 0&&(t[e.name]=l(t[e.name],e.schema));return t},O=(n,r,t)=>{const e=[`Content-Type: ${n}`];return t&&e.push(`Content-Transfer-Encoding: ${t}`),[...e,"",r].join(`\r
`)},v=(n,r)=>r.map(t=>`--${n}\r
${t}`).join(`\r
`),N=n=>{if(!n||typeof n!="object"||Array.isArray(n))return!1;const r=Object.keys(n);return r.length===0?!1:r.every(t=>/^\d+$/.test(t))},h=n=>Object.keys(n).map(t=>parseInt(t,10)).sort((t,e)=>t-e).map(t=>n[String(t)]),J=(n,r,t)=>{const e=[],o=s=>N(s)?h(s):s,u=(s,a)=>{const c=o(s);if(typeof c=="object"&&c!==null){const p=Array.isArray(c)?c.map(f=>typeof f=="object"&&f!==null?T(f,a):l(f,a)):T(c,a);e.push(O("application/json",JSON.stringify(p,null,2)))}else{const p=l(c,a),f=$(p,a),E=a?.format==="binary"?"binary":a?.format==="byte"?"base64":void 0;e.push(O(f,String(p),E))}},i=o(n);return Array.isArray(i)?i.forEach((s,a)=>u(s,r?.fields?.[a]?.schema)):u(i,r),v(A,e)},M=n=>Array.isArray(n)?n.map(r=>S(r)).join(`

`):S(n),_=(n,r)=>{const t="0x1E",e="0x0A";return typeof n=="string"?n:r?.type==="array"?`${t}${[JSON.stringify(n)]}${e}`:Array.isArray(n)&&n.length>=1?n.map(o=>`${t}${JSON.stringify(o)}${e}`).join(`
`):`${t}${JSON.stringify(n)}${e}`},g=(n,r)=>typeof n=="string"?n:r?.type==="array"?`${[JSON.stringify(n)]}`:Array.isArray(n)?n.map(t=>JSON.stringify(t)).join(`
`):JSON.stringify(n),C={[y.EVENT_STREAM]:{shouldConvert:d,convert:M,lineSeparator:`

`},[y.JSON_SEQ]:{shouldConvert:d,convert:_,lineSeparator:`
`},[y.JSONL]:{shouldConvert:d,convert:g,lineSeparator:`
`},[y.NDJSON]:{shouldConvert:d,convert:g,lineSeparator:`
`},[y.MULTIPART_MIXED]:{shouldConvert:n=>n!==null,convert:J,lineSeparator:`\r
`}};function m(n,r,t,e=!1){const o=C[r];if(o?.shouldConvert(n)){const u=o.convert(n,t);let i;return e?i=Array.from({length:3},()=>u).join(o.lineSeparator):i=u,r===y.MULTIPART_MIXED&&(i=i+`\r
--${A}--`),i}return n}export{m as convertSampleToString};
