UNPKG

sammich.js

Version:

Too many JavaScript files? Put 'em in a sammich.

97 lines (77 loc) 2.34 kB
/* * Copyright (C) 2025 Ashei Juniperus - Available under the MPL 2.0 * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ const fs = require("fs"); const { readFileSync } = fs; const { readFile } = fs.promises; const MODULE_DELIMITER = "\n"; class Sammich { /** * @type {string} */ #sourceCode = ""; constructor() { this.#sourceCode = ""; } static async bundle(moduleSourceCodes) { const sammich = new Sammich(); for (const moduleSourceCode of moduleSourceCodes) { await sammich.add(moduleSourceCode); } return sammich.toString(); } static async bundleFiles(inputFilePaths) { const sammich = new Sammich(); for (const inputFilePath of inputFilePaths) { await sammich.addFile(inputFilePath); } return sammich.toString(); } /** * Add source code to the `Sammich`. * * @param {string} sourceCode The source code to add to the `Sammich`. */ add(sourceCode) { this.#sourceCode += sourceCode + MODULE_DELIMITER; } /** * Add source code from a file to the `Sammich`. * * @param {string} modulePath The path to the file to add to the `Sammich`. */ async addFile(modulePath) { const sourceCode = await readFile(modulePath, "utf-8"); this.add(sourceCode); } /** * Add source code from a file to the `Sammich`. * * @param {string} modulePath The path to the file to add to the `Sammich`. */ addFileSync(modulePath) { const sourceCode = readFileSync(modulePath, "utf-8"); this.add(sourceCode); } /** * Convert the `Sammich` to a JavaScript function. * * @returns {Function} The `Sammich` represented as a JavaScript function. */ toFunction() { return new Function(this.toString()); } /** * Convert the `Sammich` to a string of JavaScript source code. * * @returns {string} The `Sammich` represented as a string of JavaScript source code. */ toString() { return this.#sourceCode.trim(); } } module.exports = Sammich;