import path from 'path'; import { type SSEStreamingApi } from 'hono/streaming'; import { VOLUMES_DIR } from '@iridiumcms/constants'; import { createWriteStream, createReadStream } from 'fs'; import { promisify } from 'util'; import { pipeline } from 'stream'; const pipelineAsync = promisify(pipeline); export const write = async (stream: ReadableStream, filename: string) => { const dir = path.resolve(VOLUMES_DIR, filename); const writeStream = createWriteStream(dir); // @ts-ignore await pipelineAsync(stream, writeStream); // Ensure the write stream is properly closed writeStream.end(); return dir; }; export const read = createReadStream; export const emitter = ({ name = '', category = '', stream, }: { name?: string; category?: string; stream: SSEStreamingApi; }) => { let id = 0; return { async emit(evt: string, msg: string) { return await stream.writeSSE({ id: `${id++}`, event: evt, data: JSON.stringify({ name, category, message: msg, }), }); }, async msg(msg: string) { return await this.emit('msg', msg); }, async close(evt = 'close', msg = 'complete') { return await this.emit(evt, msg); }, }; };