import { Stream } from "stream"; import { File } from "@file/file"; import { OutputByType, OutputType } from "@util/output-type"; import { Compiler, IXmlifyedFile } from "./next-compiler"; /** * Use blanks to prettify */ export const PrettifyType = { NONE: "", WITH_2_BLANKS: " ", WITH_4_BLANKS: " ", WITH_TAB: "\t", } as const; const convertPrettifyType = ( prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], ): (typeof PrettifyType)[keyof typeof PrettifyType] | undefined => prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify; export class Packer { // eslint-disable-next-line require-await public static async pack( file: File, type: T, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], overrides: readonly IXmlifyedFile[] = [], ): Promise { const zip = this.compiler.compile(file, convertPrettifyType(prettify), overrides); return zip.generateAsync({ type, mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", compression: "DEFLATE", }); } public static toString( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], overrides: readonly IXmlifyedFile[] = [], ): Promise { return Packer.pack(file, "string", prettify, overrides); } public static toBuffer( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], overrides: readonly IXmlifyedFile[] = [], ): Promise { return Packer.pack(file, "nodebuffer", prettify, overrides); } public static toBase64String( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], overrides: readonly IXmlifyedFile[] = [], ): Promise { return Packer.pack(file, "base64", prettify, overrides); } public static toBlob( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], overrides: readonly IXmlifyedFile[] = [], ): Promise { return Packer.pack(file, "blob", prettify, overrides); } public static toArrayBuffer( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], overrides: readonly IXmlifyedFile[] = [], ): Promise { return Packer.pack(file, "arraybuffer", prettify, overrides); } public static toStream( file: File, prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], overrides: readonly IXmlifyedFile[] = [], ): Stream { const stream = new Stream(); const zip = this.compiler.compile(file, convertPrettifyType(prettify), overrides); zip.generateAsync({ type: "nodebuffer", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", compression: "DEFLATE", }).then((z) => { stream.emit("data", z); stream.emit("end"); }); return stream; } private static readonly compiler = new Compiler(); }