|
| 1 | +import AbstractInput from "./AbstractInput"; |
| 2 | +import BufferInput from "./BufferInput"; |
| 3 | +import FolderInput from "./FolderInput"; |
| 4 | +import fs from "fs-extra"; |
| 5 | +import isBuffer from "./../output/isBuffer"; |
| 6 | +import MetadataConverter from "../converter/MetadataConverter"; |
| 7 | +import path from "path"; |
| 8 | + |
| 9 | +/** |
| 10 | + * @param {string|Buffer|ArrayBuffer|Uint8Array|Array} input |
| 11 | + * |
| 12 | + * @returns {Promise<AbstractInput>} |
| 13 | + * |
| 14 | + * @throws {Error} |
| 15 | + */ |
| 16 | +async function detectInput(input) { |
| 17 | + if (isBuffer(input)) { |
| 18 | + return new BufferInput(input); |
| 19 | + } |
| 20 | + |
| 21 | + if (Array.isArray(input)) { |
| 22 | + if (isBuffer(input[0])) { |
| 23 | + return new BufferInput(input[0], input[1]); |
| 24 | + } |
| 25 | + |
| 26 | + throw new Error(`Invalid array input!`); |
| 27 | + } |
| 28 | + |
| 29 | + if (typeof input !== "string") { |
| 30 | + throw new Error(`Invalid string input!`); |
| 31 | + } |
| 32 | + |
| 33 | + if (!fs) { |
| 34 | + throw new Error(`Browser only supports Buffer input!`); |
| 35 | + } |
| 36 | + |
| 37 | + if (!fs.existsSync(input)) { |
| 38 | + throw new Error(`The input ${input} does not exists!`); |
| 39 | + } |
| 40 | + |
| 41 | + if (fs.statSync(input).isDirectory()) { |
| 42 | + if (!fs.existsSync(path.join(input, MetadataConverter.PACK_MCMETA))) { // Prevents copy whole wrong folders |
| 43 | + throw new Error(`Invalid folder input ${input} - Missing ${MetadataConverter.PACK_MCMETA}!`); |
| 44 | + } |
| 45 | + |
| 46 | + return new FolderInput(input, input); |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + const ext = path.extname(input).toLowerCase().substr(1); |
| 51 | + |
| 52 | + switch (ext) { |
| 53 | + case "zip": |
| 54 | + return new BufferInput(await fs.readFile(input), input); |
| 55 | + |
| 56 | + default: |
| 57 | + throw new Error(`The input ${input} is no zip archive or folder!`); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export default detectInput; |
0 commit comments