|
| 1 | +/* |
| 2 | + * Copyright (C) 2022 Elijah Olmos |
| 3 | + * |
| 4 | + * This program is free software: you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU Affero General Public License as |
| 6 | + * published by the Free Software Foundation, version 3. |
| 7 | + * |
| 8 | + * This program is distributed in the hope that it will be useful, |
| 9 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | + * GNU Affero General Public License for more details. |
| 12 | + * |
| 13 | + * You should have received a copy of the GNU Affero General Public License |
| 14 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 | + */ |
| 16 | + |
| 17 | +import { bold, green } from 'colorette'; |
| 18 | +import { strToU8, zip as zipCb } from 'fflate'; |
| 19 | +import filesize from 'filesize'; |
| 20 | +import { mkdir, readFile, writeFile } from 'node:fs/promises'; |
| 21 | +import { relative } from 'node:path'; |
| 22 | +import { promisify } from 'node:util'; |
| 23 | +import { OutputOptions } from 'rollup'; |
| 24 | + |
| 25 | +/** |
| 26 | + * @typedef ZipConfigOptions |
| 27 | + * @type {object} |
| 28 | + * @property {string} fileName - name of output zip file |
| 29 | + * @property {string} [dir] - Output directory, defaults to rollup output directory |
| 30 | + */ |
| 31 | + |
| 32 | +/** |
| 33 | + * @param {ZipConfigOptions} options |
| 34 | + */ |
| 35 | +export default function zip(options) { |
| 36 | + return { |
| 37 | + name: 'zip', |
| 38 | + /** |
| 39 | + * @param {OutputOptions} options |
| 40 | + * @param {Object.<string, {source: string | Uint8Array}>} bundle |
| 41 | + */ |
| 42 | + writeBundle: async function (_options, bundle) { |
| 43 | + const dir = options?.dir ?? _options?.dir ?? process.cwd(); |
| 44 | + const { fileName } = options; |
| 45 | + |
| 46 | + const data = await promisify(zipCb)( |
| 47 | + await Object.entries(bundle).reduce( |
| 48 | + async (acc, [name, { type, source }]) => ({ |
| 49 | + ...(await acc), |
| 50 | + [name]: |
| 51 | + type === 'asset' |
| 52 | + ? typeof source === 'string' |
| 53 | + ? strToU8(source) |
| 54 | + : source |
| 55 | + : await readFile(`${_options?.dir}/${name}`), |
| 56 | + }), |
| 57 | + {} |
| 58 | + ) |
| 59 | + ); |
| 60 | + //create dir if it does not exist |
| 61 | + await mkdir(`./${relative(process.cwd(), dir)}`, { recursive: true }); |
| 62 | + await writeFile(`./${relative(process.cwd(), dir)}/${fileName}`, data); |
| 63 | + console.log(green(`zipped to ${bold(`${dir}/${fileName}`)} (${filesize(data.byteLength)})`)); |
| 64 | + }, |
| 65 | + }; |
| 66 | +} |
0 commit comments