// @ts-check /* Called by ./run-rollup.js Makes browser IIFEs for packages with browser property. The body of the function is taken from the ES5 index.js generated by TS. */ const fse = require('fs-extra') const path = require('path') const removeBanner = require('./lib/remove-banner') const getBanner = require('./lib/get-banner') const wrapCode = require('./lib/wrap-code') const D = require('./defaults') const _done = () => true const JSLIB_GLOBAL = '(root.$ || root.jQuery || {}).jsbits || root.jsbits || (root.jsbits={})' /** * Creates the wrapper for an UMD module for the browser, browserify, etc. * * Based on https://github.com/umdjs/umd/blob/master/templates/returnExports.js * * @param {object} pkgJson package.json content * @param {string} objName Object name to add into the global jsbits */ const umdWrapper = (pkgJson, objName) => ` ${getBanner(pkgJson, 'UMD')} ;(function(root, factory) { if (typeof define == 'function' && define.amd) { define([], factory) } else if (typeof module == 'object' && module.exports) { module.exports = factory() } else { (${JSLIB_GLOBAL}).${objName} = factory() } })(typeof self !== 'undefined' ? self : this, function () { $${D.PLACEHOLDER} }); ` /** * Creates the wrapper for an IIFE that inject functions in browser globals. * * Based on https://github.com/umdjs/umd/blob/master/templates/returnExports.js * * @param {object} pkgJson package.json content * @param {string} objName Object name to add into the global jsbits */ const zipWrapper = (pkgJson, objName) => ` ${getBanner(pkgJson, 'UMD')} ;(function(root, factory) { (${JSLIB_GLOBAL}).${objName} = factory() })(typeof self !== 'undefined' ? self : this, function () { $${D.PLACEHOLDER} }); ` /** * Wrap the code. It store `code` in the closure to return at the last `then`. * * @param {string} outFile Output filename (absolute) * @param {string} code Code to replace and insert into the IIFE * @param {string} wrapper Code wrapper */ const doWrap = (outFile, code, wrapper) => { return wrapCode(code, wrapper, { export: 'return', method: outFile.endsWith(D.MINIFIED_NAME) ? 'minify' : 'cleanup', output: outFile, }) .then((wrapped) => fse.outputFile(outFile, wrapped, D.TEXT) && code) } /** * Returns a "task" that will call Rollup in the given folder. * @param {string} srcPath Path where the source files lives * @param {object} jsInfo Object from jsbits.json * @param {object} pkgJson Json object from package.json */ const makeBrowser = (srcPath, jsInfo, pkgJson) => { const file = path.join(srcPath, 'index.js') const name = jsInfo._NAME return fse.readFile(file, D.TEXT) .then(removeBanner) .then((code) => doWrap(path.join(srcPath, pkgJson.browser), code, umdWrapper(pkgJson, name))) .then((code) => doWrap(path.join(srcPath, D.MINIFIED_NAME), code, zipWrapper(pkgJson, name))) .then(_done) } module.exports = makeBrowser