const ansiSgrPattern=RegExp(`${String.fromCodePoint(27)}\\[[0-9;]*m`,`gu`);function chunkToString(e,t){return typeof e==`string`?e:Buffer.from(e).toString(t)}function endsWithLineBreak(e){return e.endsWith(`
`)||e.endsWith(`\r`)}function stripAnsi(t){return t.replace(ansiSgrPattern,``)}function countRenderedLines(e){let t=process.stdout.columns;return e.split(/\r\n|\r|\n/u).reduce((e,n)=>{let r=Array.from(stripAnsi(n)).length;return t===void 0||t<=0?e+1:e+Math.max(1,Math.ceil(r/t))},0)}function getPromptCursor(e){let t=e.cursor;return typeof t==`number`?t:e.line.length}function createDevelopmentTerminal(){let e=process.stdout.write.bind(process.stdout),t=process.stderr.write.bind(process.stderr),n=null,r=null,writeOriginal=(e,t,n,r,i)=>Reflect.apply(t,e,[n,r,i]),clearPrompt=()=>{n!==null&&writeOriginal(process.stdout,e,`\x1B[2K\r`)},redrawPrompt=()=>{if(n===null)return;let{prompt:t,rl:r}=n,i=getPromptCursor(r),a=r.line.length-i;writeOriginal(process.stdout,e,`${t}${r.line}`),a>0&&writeOriginal(process.stdout,e,`\u001B[${a}D`)},clearLiveBlock=()=>{if(r!==null)for(let t=0;t<r.lineCount;t+=1)writeOriginal(process.stdout,e,`\x1B[1A`),writeOriginal(process.stdout,e,`\x1B[2K\r`)},renderLiveBlock=t=>{let n=t.length===0||!endsWithLineBreak(t);writeOriginal(process.stdout,e,t),n&&writeOriginal(process.stdout,e,`
`),r={lineCount:countRenderedLines(t),message:t}},printMessage=(e,t,r)=>{let i=n!==null,a=e.length===0||!endsWithLineBreak(e);i&&clearPrompt(),writeOriginal(r,t,e),a&&writeOriginal(r,t,`
`),i&&redrawPrompt()},patchStream=(e,t)=>(e.write=((i,a,o)=>{if(n===null&&r===null)return writeOriginal(e,t,i,a,o);let s=chunkToString(i,typeof a==`string`?a:void 0),c=r;n!==null&&clearPrompt(),c!==null&&(clearLiveBlock(),r=null);let l=writeOriginal(e,t,i,a,o);return s.length>0&&!endsWithLineBreak(s)&&writeOriginal(e,t,`
`),c!==null&&renderLiveBlock(c.message),n!==null&&redrawPrompt(),l}),()=>{e.write=t}),i=patchStream(process.stdout,e),a=patchStream(process.stderr,t);return{commitLive(){r=null},dispose(){n=null,r=null,i(),a()},output:new Proxy(process.stdout,{get(t,n,r){if(n===`write`)return(t,n,r)=>writeOriginal(process.stdout,e,t,n,r);let i=Reflect.get(t,n,r);return typeof i==`function`?i.bind(t):i}}),print(t){printMessage(t,e,process.stdout)},printError(e){printMessage(e,t,process.stderr)},startPrompt(e,t){n={prompt:t,rl:e}},stopPrompt(){n=null},updateLive(e){let t=n!==null;t&&clearPrompt(),r!==null&&(clearLiveBlock(),r=null),renderLiveBlock(e),t&&redrawPrompt()}}}export{createDevelopmentTerminal};