@growing-web/esm-pack-core
Version:
esm pack build core.
1,104 lines (1,074 loc) • 32.8 kB
JavaScript
import nodePolyfills from 'rollup-plugin-node-polyfills';
import commonjs from '@rollup/plugin-commonjs';
import resolve$1 from '@rollup/plugin-node-resolve';
import esbuild from 'rollup-plugin-esbuild';
import rollupJSONPlugin from '@rollup/plugin-json';
import path$1 from 'pathe';
import fs$1 from 'fs-extra';
import { rollup } from 'rollup';
import fs from 'fs';
import path from 'path';
import execa from 'execa';
import isValidIdentifier from 'is-valid-identifier';
import resolve from 'resolve';
import inject from '@rollup/plugin-inject';
import { readPackageJSON } from 'pkg-types';
import fg from 'fast-glob';
import _ from 'lodash';
import { parse as parse$2 } from 'cjs-esm-exports';
import { init, parse as parse$1 } from 'es-module-lexer';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
// -- Unbuild CommonJS Shims --
import __cjs_url__ from 'url';
import __cjs_path__ from 'path';
import __cjs_mod__ from 'module';
const __filename = __cjs_url__.fileURLToPath(import.meta.url);
const __dirname = __cjs_path__.dirname(__filename);
const require = __cjs_mod__.createRequire(import.meta.url);
const APP_NAME = "esm-pack";
const EXTENSIONS = [
".ts",
".tsx",
".mjs",
".cjs",
".js",
".jsx",
".json"
];
const FILE_EXCLUDES = [
"tsconfig.json",
"eslint",
"tslint",
"prettier",
"stylelint",
"commitlint",
"turbo",
"main.package",
"vetur",
".vscode",
"build-info.json",
"build.json",
".env",
".gitignore",
".npmrc",
".yarnrc",
"pnpm-lock.yaml",
"package-lock.json",
"yarn.lock",
"nginx.conf"
];
const FILES_IGNORE = [
"**/src/**",
"**/bin/**",
"**/node_modules/**",
"**/vetur/**",
"**/.vscode/**",
"**/.idea/**",
"**/.changeset/**",
"**/.husky/**",
"**/.esmd/**",
"**/pnpm-lock.yaml/**",
"**/yarn.lock/**",
"**/package-lock.json/**",
"**/.prettierrc.json/**",
"**/.commitlintrc.json/**",
"**/ecosystem.config.js/**",
"**/scripts/**",
"**/.dockerignore/**",
"**/Dockerfile/**",
"**/.eslintrc.json/**",
"**/nest-cli.json/**",
"**/nodemon.json/**",
"**/nginx.conf/**",
"**/yarnrc/**",
"**/.gitignore/**",
"**/.markdownlint.yml/**"
];
const FILE_EXTENSIONS = [
...EXTENSIONS,
".less",
".scss",
".css",
".sass",
".postcss"
];
const { parse } = require("cjs-module-lexer");
function createTransformTarget(specifier, all = true) {
return {
specifier,
all,
default: false,
namespace: false,
named: []
};
}
function normalizePath(p) {
return p.split(path.win32.sep).join(path.posix.sep);
}
function isJavaScript(pathname) {
const ext = path.extname(pathname).toLowerCase();
return ext === ".js" || ext === ".mjs" || ext === ".cjs";
}
function isRemoteUrl(val) {
return /\w+:\/\//.test(val) || val.startsWith("//");
}
function isTruthy(item) {
return Boolean(item);
}
function isValidNamedExport(name) {
return name !== "default" && name !== "__esModule" && isValidIdentifier(name);
}
function rollupPluginWrapTargets(isTreeshake = false, target) {
if (!target) {
return null;
}
const installTargetSummaries = {};
const cjsScannedNamedExports = /* @__PURE__ */ new Map();
const transformTarget = createTransformTarget(target);
function cjsAutoDetectExportsStatic(filename, visited = /* @__PURE__ */ new Set()) {
const isMainEntrypoint = visited.size === 0;
if (visited.has(filename)) {
return [];
} else {
visited.add(filename);
}
const fileContents = fs.readFileSync(filename, "utf8");
try {
const { exports: exports2, reexports } = parse(fileContents);
let resolvedReexports = [];
if (reexports.length > 0) {
resolvedReexports = [].concat.apply([], reexports.map((e) => cjsAutoDetectExportsStatic(resolve.sync(e, { basedir: path.dirname(filename) }), visited)).filter(isTruthy));
}
const resolvedExports = Array.from(/* @__PURE__ */ new Set([...exports2, ...resolvedReexports])).filter(isValidNamedExport);
return isMainEntrypoint && resolvedExports.length === 0 ? void 0 : resolvedExports;
} catch (err) {
return void 0;
}
}
function cjsAutoDetectExportsRuntimeTrusted(normalizedFileName) {
try {
const { stdout } = execa.sync(`node`, ["-p", `JSON.stringify(Object.keys(require('${normalizedFileName}')))`], {
cwd: __dirname,
extendEnv: false
});
return JSON.parse(stdout).filter(isValidNamedExport);
} catch (err) {
return void 0;
}
}
function cjsAutoDetectExportsRuntimeUntrusted() {
try {
return exports.filter((identifier) => isValidIdentifier(identifier));
} catch (err) {
return void 0;
}
}
return {
name: "rollup-plugin-wrap-exports",
buildStart(inputOptions) {
const input = inputOptions.input;
for (const [key, val] of Object.entries(input)) {
if (isRemoteUrl(val)) {
continue;
}
if (!isJavaScript(val)) {
continue;
}
installTargetSummaries[val] = transformTarget;
const normalizedFileLoc = normalizePath(val);
const cjsExports = cjsAutoDetectExportsStatic(val) || cjsAutoDetectExportsRuntimeTrusted(normalizedFileLoc) || cjsAutoDetectExportsRuntimeUntrusted();
if (cjsExports && cjsExports.length > 0) {
cjsScannedNamedExports.set(normalizedFileLoc, cjsExports);
input[key] = `${APP_NAME}:${val}`;
}
}
},
resolveId(id) {
if (id.startsWith(`${APP_NAME}:`)) {
return id;
}
return null;
},
load(id) {
if (!id.startsWith(`${APP_NAME}:`)) {
return null;
}
const fileLoc = id.substring(`${APP_NAME}:`.length);
const installTargetSummary = installTargetSummaries[fileLoc];
let uniqueNamedExports = Array.from(new Set(installTargetSummary.named));
const normalizedFileLoc = normalizePath(fileLoc);
const scannedNamedExports = cjsScannedNamedExports.get(normalizedFileLoc);
if (scannedNamedExports && (!isTreeshake || installTargetSummary.namespace)) {
uniqueNamedExports = scannedNamedExports || [];
installTargetSummary.default = true;
}
const result = `
${installTargetSummary.namespace ? `export * from '${normalizedFileLoc}';` : ""}
${installTargetSummary.default ? `import _web_default_export_for_treeshaking__ from '${normalizedFileLoc}'; export default _web_default_export_for_treeshaking__;` : ""}
${`export {${uniqueNamedExports.join(",")}} from '${normalizedFileLoc}';`}
`;
return result;
}
};
}
function generateProcessPolyfill(env) {
return `/* ESM-PACK PROCESS POLYFILL (based on https://github.com/calvinmetcalf/node-process-es6) */
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
var cachedSetTimeout = defaultSetTimout;
var cachedClearTimeout = defaultClearTimeout;
var globalContext;
if (typeof window !== 'undefined') {
globalContext = window;
} else if (typeof self !== 'undefined') {
globalContext = self;
} else {
globalContext = {};
}
if (typeof globalContext.setTimeout === 'function') {
cachedSetTimeout = setTimeout;
}
if (typeof globalContext.clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
}
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
function nextTick(fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
}
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
var title = 'browser';
var platform = 'browser';
var browser = true;
var env = {};
var argv = [];
var version = ''; // empty string to avoid regexp issues
var versions = {};
var release = {};
var config = {};
function noop() {}
var on = noop;
var addListener = noop;
var once = noop;
var off = noop;
var removeListener = noop;
var removeAllListeners = noop;
var emit = noop;
function binding(name) {
throw new Error('process.binding is not supported');
}
function cwd () { return '/' }
function chdir (dir) {
throw new Error('process.chdir is not supported');
}function umask() { return 0; }
// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
var performance = globalContext.performance || {};
var performanceNow =
performance.now ||
performance.mozNow ||
performance.msNow ||
performance.oNow ||
performance.webkitNow ||
function(){ return (new Date()).getTime() };
// generate timestamp or delta
// see http://nodejs.org/api/process.html#process_process_hrtime
function hrtime(previousTimestamp){
var clocktime = performanceNow.call(performance)*1e-3;
var seconds = Math.floor(clocktime);
var nanoseconds = Math.floor((clocktime%1)*1e9);
if (previousTimestamp) {
seconds = seconds - previousTimestamp[0];
nanoseconds = nanoseconds - previousTimestamp[1];
if (nanoseconds<0) {
seconds--;
nanoseconds += 1e9;
}
}
return [seconds,nanoseconds]
}
var startTime = new Date();
function uptime() {
var currentTime = new Date();
var dif = currentTime - startTime;
return dif / 1000;
}
export default {
nextTick: nextTick,
title: title,
browser: browser,
env: ${JSON.stringify(env)},
argv: argv,
version: version,
versions: versions,
on: on,
addListener: addListener,
once: once,
off: off,
removeListener: removeListener,
removeAllListeners: removeAllListeners,
emit: emit,
binding: binding,
cwd: cwd,
chdir: chdir,
umask: umask,
hrtime: hrtime,
platform: platform,
release: release,
config: config,
uptime: uptime
};
export { addListener, argv, binding, browser, chdir, config, cwd, emit, env, hrtime, nextTick, off, on, once, platform, release, removeAllListeners, removeListener, title, umask, uptime, version, versions };
`;
}
const PROCESS_MODULE_NAME = "process";
function rollupPluginNodeProcessPolyfill(env = {}) {
const injectPlugin = inject({
process: PROCESS_MODULE_NAME,
include: /\.(cjs|js|jsx|mjs|ts|tsx)$/
});
return {
...injectPlugin,
name: "snowpack:rollup-plugin-node-process-polyfill",
resolveId(source) {
if (source === PROCESS_MODULE_NAME) {
return PROCESS_MODULE_NAME;
}
return null;
},
load(id) {
if (id === PROCESS_MODULE_NAME) {
return { code: generateProcessPolyfill(env), moduleSideEffects: false };
}
return null;
}
};
}
function fileResolveByExtension(pathname) {
if (fs$1.existsSync(pathname)) {
return pathname;
}
for (const ext of EXTENSIONS) {
const extFile = `${pathname}${ext}`;
if (fs$1.existsSync(extFile)) {
return extFile;
}
}
return null;
}
function fileReader(path) {
return fs$1.readFileSync(path, {
encoding: "utf-8"
});
}
function recursionExportsValues(exp) {
const files = [];
for (const value of Object.values(exp)) {
if (_.isString(value)) {
if (!value.endsWith("d.ts")) {
files.push(value);
}
} else if (_.isObject(value)) {
files.push(...recursionExportsValues(value));
}
}
return Array.from(new Set(files));
}
const DEFAULT_ENTRY = "index.js";
const IGNORE_KEYS = ["default", "types", "typings", "development", "browser"];
const JS_RE = /\.[m]?js$/;
async function resolvePackage(cachePath) {
const pkg = await readPackageJSON(cachePath);
if (pkg.__ESMD__ === true) {
return pkg;
}
const pkgExports = await resolveExports(pkg, cachePath);
const files = await resolveFiles(pkg, cachePath, pkgExports);
pkg.exports = pkgExports;
pkg.files = files;
Object.assign(pkg, await resolveImports(pkg));
pkg.__ESMD__ = true;
return pkg;
}
async function resolveImports(pkg) {
const { browser } = pkg;
if (!browser || !_.isObject(browser)) {
return {};
}
const pkgBrowser = browser;
const resultImport = pkgBrowser?.import ?? {};
for (const [key, value] of Object.entries(pkgBrowser)) {
const importKey = `#${key.replace(/^((\.+)?\/?)/, "")}`;
if (resultImport[importKey]) {
continue;
}
Object.assign(resultImport, {
[importKey]: {
browser: normalizeExport(value),
default: normalizeExport(key)
}
});
}
return { imports: resultImport };
}
async function resolveExports(pkg, root) {
let {
exports: pkgExports,
module: pkgModule,
main: pkgMain,
browser: pkgBrowser,
files: pkgFiles = []
} = pkg;
const cjsMainFiles = [];
const unStandard = !pkgExports && !pkgMain && !pkgModule;
if (pkgExports !== void 0 && pkgExports !== null) {
if (_.isObject(pkgExports)) {
if (pkgExports["./*"] === "./*") {
const result3 = await addCjsFiledToExports({
root,
pkgExports,
cjsMainFiles
});
return await developmentifyExports(result3, root);
}
pkgExports["./package.json"] = "./package.json.js";
}
if (_.isString(pkgExports)) {
pkgExports = { ".": pkgExports };
}
for (const [key, pattern] of Object.entries(pkgExports)) {
if (key.includes("*") && _.isString(pattern) && pattern.includes("*") || key.endsWith("/") && _.isString(pattern) && pattern.endsWith("/")) {
await addMatchFileToExports(pattern, pkgExports, root);
continue;
}
if (_.isObject(pattern)) {
await handleObjectPattern({
root,
pkgExports,
key,
pattern
});
}
}
const result2 = await addCjsFiledToExports({
root,
pkgExports,
cjsMainFiles
});
return await developmentifyExports(result2, root);
} else if (!pkgExports) {
const resultExports = {};
if (!pkgModule && !pkgMain) {
const normalizePkgMain = normalizeExport(guessEntryFile(root, pkgFiles));
const addonCjsMainFiles = await createCjsMainFiles(root, normalizePkgMain);
cjsMainFiles.push(...addonCjsMainFiles);
Object.assign(resultExports, {
".": normalizePkgMain
});
} else if (pkgModule && pkgMain) {
const normalizePkgMain = normalizeExport(pkgMain);
const normalizepkgModule = normalizeExport(pkgModule);
const addonCjsMainFiles = await createCjsMainFiles(root, normalizePkgMain);
cjsMainFiles.push(...addonCjsMainFiles);
Object.assign(resultExports, {
".": await resolveMainAndModule(root, normalizePkgMain, normalizepkgModule, pkgBrowser)
});
if (!pkgBrowser) {
Object.assign(resultExports, await joinFilesToExports(root, pkgFiles));
}
resultExports["./package.json"] = "./package.json.js";
Object.assign(resultExports, {
[normalizePkgMain]: await resolveMain(root, normalizePkgMain),
[normalizepkgModule]: normalizepkgModule
});
} else if (!pkgModule && pkgMain) {
const normalizePkgMain = normalizeExport(pkgMain);
const addonCjsMainFiles = await createCjsMainFiles(root, normalizePkgMain);
cjsMainFiles.push(...addonCjsMainFiles);
Object.assign(resultExports, {
".": await resolveMain(root, normalizePkgMain),
[normalizePkgMain]: await resolveMain(root, normalizePkgMain)
});
resultExports["./package.json"] = "./package.json.js";
Object.assign(resultExports, await joinFilesToExports(root, pkgFiles));
}
pkgExports = resultExports;
}
if (unStandard) {
pkgExports["./package.json"] = "./package.json.js";
}
let result = await addCjsFiledToExports({ root, pkgExports, cjsMainFiles });
result = await handlerPkgBrowser(pkgBrowser, result);
return await developmentifyExports(result, root);
}
async function resolveFiles(pkg, root, pkgExports) {
let { files = [] } = pkg;
files = [];
files.push(...["", ".js"].map((item) => `package.json${item}`));
const values = recursionExportsValues(pkgExports);
files.push(...values.map((item) => {
return item.replace(/^\.?\//, "");
}));
files.forEach((item) => {
if (/\.[m|c]?js$/.test(item) && !item.includes("*")) {
files.push(`${item}.map`);
}
});
const matchFiles = await fg(["license", "readme.md", "changelog.md"], {
cwd: root,
caseSensitiveMatch: false
});
const matchTsFiles = await fg("./*.d.ts", {
cwd: root,
caseSensitiveMatch: false
});
files.push(...matchFiles, ...matchTsFiles);
files = files.filter((item) => !["*", ".", "./", "./*"].includes(item));
return Array.from(new Set(files)).sort();
}
async function developmentifyExports(pkgExports, root) {
for (const [key, value] of Object.entries(pkgExports)) {
const ext = path.extname(key);
if (!ext || key.endsWith(".prod.cjs") || ![".js", ".cjs"].includes(ext) || !_.isString(value) || key === "./index.js") {
continue;
}
const filepath = path.join(root, key);
if (!fs$1.existsSync(filepath)) {
continue;
}
const { isEsm } = await getFileType(root, key);
if (isEsm) {
continue;
}
const content = fileReader(filepath);
const dynamicEntry = await isDynamicEntry(content);
if (dynamicEntry) {
const devKeys = await resolveDevFilename(key);
const itemExports = {
default: key,
development: devKeys
};
pkgExports[key] = itemExports;
const unExtKey = key.substring(0, key.length - ext.length);
if (pkgExports[unExtKey]) {
pkgExports[unExtKey] = itemExports;
}
}
}
return pkgExports;
}
async function joinFilesToExports(root, pkgFiles) {
const resultExports = {};
const getFiles = await findPkgFiles(root, pkgFiles);
getFiles.forEach((file) => {
const fileKey = normalizeExport(file);
if (!fileKey.endsWith(".cjs.js")) {
resultExports[fileKey] = fileKey;
if (JS_RE.test(fileKey)) {
resultExports[removeFileExt(fileKey)] = fileKey;
}
}
});
return resultExports;
}
async function handlerPkgBrowser(pkgBrowser, pkgExports) {
if (!pkgBrowser || _.isString(pkgBrowser)) {
return pkgExports;
}
const resultExports = pkgExports;
for (const [key, value] of Object.entries(pkgBrowser)) {
if (!resultExports[key] || _.isString(resultExports[key])) {
resultExports[removeFileExt(key)] = resultExports[key] = {
default: normalizeExport(key),
browser: normalizeExport(value)
};
}
}
return resultExports;
}
async function createCjsMainFiles(root, pkgMain) {
const { isCjs } = await getFileType(root, pkgMain);
const cjsMainFiles = [];
if (isCjs) {
cjsMainFiles.push(...[pkgMain]);
}
return cjsMainFiles;
}
async function findPkgFiles(root, pkgFiles = []) {
const pattern = pkgFiles.length === 0 ? "**/**" : pkgFiles.map((item) => {
if (item.includes("*") || path.extname(item)) {
return item;
} else {
const filepath = path.join(root, item);
if (fs$1.existsSync(filepath) && fs$1.statSync(filepath).isFile()) {
return item;
}
return `${item}${item.endsWith("/") ? "" : "/"}**/**.js`;
}
});
const files = await fg(pattern, { cwd: root, ignore: FILES_IGNORE });
const pkg = await readPackageJSON(root);
return files.filter((item) => {
const ext = path.extname(item);
if (!ext || ext === ".ts" || excludeFiles(pkg, item)) {
return false;
}
return FILE_EXTENSIONS.includes(ext);
});
}
function excludeFiles(pkg, file) {
return FILE_EXCLUDES.some((item) => file.includes(item)) || file.endsWith(".min.js") || file.endsWith(".prod.js") || file.endsWith(".development.js") || file.endsWith(".dev.js") || file.endsWith(".global.js");
}
async function handleObjectPattern({
root,
pkgExports,
key,
pattern
}) {
for (const [pkey, pval] of Object.entries(pattern)) {
if (IGNORE_KEYS.includes(pkey)) {
continue;
}
if (_.isString(pval)) {
if (pattern.import && pattern.require && _.isString(pattern.import) && _.isString(pattern.require) && pattern.require !== pattern.import) {
continue;
}
pkgExports[key][pkey] = await resolveMain(root, pval);
} else if (_.isObject(pval)) {
for (const [ik, iv] of Object.entries(pval)) {
if (IGNORE_KEYS.includes(ik)) {
continue;
}
if (_.isString(iv)) {
pkgExports[key][pkey][ik] = await resolveMain(root, iv);
}
}
}
}
}
async function addMatchFileToExports(pattern, pkgExports, cwd) {
const files = fg.sync(pattern.endsWith("/") ? `${pattern}*` : pattern, {
cwd
});
for (const key of files) {
pkgExports[key] = normalizeExport(key);
}
}
async function addCjsFiledToExports({
root,
pkgExports,
cjsMainFiles
}) {
for (const [key, value] of Object.entries(pkgExports)) {
if (_.isObject(value)) {
const requireFile = value.require;
if (requireFile) {
if (_.isString(requireFile)) {
pkgExports[`${requireFile}!cjs`] = requireFile;
} else if (_.isObject(requireFile)) {
for (const rval of Object.values(requireFile)) {
pkgExports[`${rval}!cjs`] = rval;
}
}
}
} else {
try {
if (!key.includes("*") && !key.startsWith(".ts")) {
if (JS_RE.test(key)) {
const { isCjs } = await getFileType(root, key);
if (isCjs) {
pkgExports[`${key}!cjs`] = key;
}
} else if (key.endsWith("package.json")) {
pkgExports[`${value}!cjs`] = value;
}
}
} catch (error) {
}
}
}
for (const cjsMainFile of cjsMainFiles) {
pkgExports[`${cjsMainFile}!cjs`] = cjsMainFile;
}
return pkgExports;
}
function guessEntryFile(root, pkgFiles) {
let indexFile = pkgFiles.find((file) => path.basename(file) === "index");
if (indexFile) {
indexFile = path.basename(indexFile);
} else {
indexFile = "index";
}
const entryFile = fileResolveByExtension(path.join(root || "", indexFile));
if (entryFile) {
return path.relative(root, entryFile);
}
return DEFAULT_ENTRY;
}
async function resolveMainAndModule(root, pkgMain, pkgModule, pkgBrowser) {
const result = {
module: normalizeExport(pkgModule),
default: await resolveMain(root, pkgMain)
};
if (_.isString(pkgBrowser)) {
Object.assign(result, {
browser: normalizeExport(pkgBrowser)
});
}
return result;
}
async function resolveMain(root, pkgMain) {
const normalizeMain = normalizeExport(pkgMain);
const isDynamicEntry2 = await getIsDynamic(root, pkgMain);
const { isUmd } = await getFileType(root, pkgMain);
if (isUmd || pkgMain.endsWith(".mjs") || !isDynamicEntry2) {
return normalizeMain;
}
return {
development: !isDynamicEntry2 ? normalizeMain : await resolveDevFilename(normalizeMain),
default: normalizeMain
};
}
async function resolveDevFilename(filename) {
const basename = path.basename(filename);
const newBaseName = basename.replace(/^(\.?\/?)*/, (m, $1) => `${$1 || ""}dev.`);
return filename.replace(basename, newBaseName);
}
async function getIsDynamic(root, filepath) {
const mainContent = fileReader(path.join(root, filepath));
let isDynamic = false;
if (JS_RE.test(filepath)) {
isDynamic = await isDynamicEntry(mainContent);
}
return isDynamic;
}
async function isDynamicEntry(source) {
try {
return source.replace(/\s*/g, "").includes(`process.env.NODE_ENV==`) || source.replace(/\s*/g, "").includes(`process.env.NODE_ENV!=`);
} catch (error) {
return false;
}
}
async function getFileType(root, filepath) {
if (!JS_RE.test(filepath)) {
return { isCjs: false, isEsm: false, isUmd: false };
}
const pkg = await readPackageJSON(root);
await init;
const source = fileReader(path.join(root, filepath));
const [importer, exporter] = parse$1(source);
const { reexports } = parse$2(filepath, source, "production");
const isCjs = pkg.type !== "module" && importer.length === 0 && exporter.length === 0 && !filepath.endsWith(".mjs");
if (isCjs) {
const isUmd = !exporter.length && !importer.length && reexports.length === 0;
return {
isCjs: true,
isEsm: false,
isUmd
};
}
const isEsm = importer.length !== 0 || exporter.length !== 0 || pkg.type === "module" || filepath.endsWith(".mjs");
return {
isCjs,
isEsm,
isUmd: isCjs && exporter.length === 0
};
}
function normalizeExport(str) {
if (str?.startsWith("./")) {
return str;
}
if (str?.startsWith("/")) {
return `.${str}`;
}
return `./${str}`;
}
function removeFileExt(file) {
const lastIndex = file.lastIndexOf(path.extname(file));
return file.substring(0, lastIndex);
}
process.setMaxListeners(0);
async function build({
buildFiles,
outputPath,
sourcePath,
sourcemap = true
}) {
const inputMap = {};
const pkg = await readPackageJSON(sourcePath);
const devBuildFiles = [];
await Promise.all(buildFiles.map(async (file) => {
const dynamicEntry = await isDynamicEntry(fs$1.readFileSync(file, { encoding: "utf8" }));
if (dynamicEntry) {
devBuildFiles.push(file);
}
}));
for (const file of buildFiles) {
let n = file.split("/").pop();
if (!n) {
continue;
}
const extIndex = n.lastIndexOf(".");
if (extIndex !== -1)
n = n.slice(0, extIndex);
if (inputMap[n]) {
const _n = n;
let i = 1;
while (inputMap[n])
n = _n + ++i;
}
inputMap[n] = file;
}
await Promise.all([
doBuildMultipleEntry({
input: inputMap,
outputPath,
sourcePath,
env: "production",
name: pkg.name,
sourcemap
}),
Promise.all(devBuildFiles.map((input) => doBuildSingleEntry({
input,
outputPath,
sourcePath,
env: "development",
name: pkg.name,
sourcemap
})))
]);
}
async function doBuildMultipleEntry({
input,
sourcePath,
outputPath,
env,
name,
sourcemap
}) {
const inputKeys = Object.keys(input);
const bundle = await rollup({
input,
treeshake: { moduleSideEffects: true },
onwarn: onWarning,
external: (id) => !inputKeys.includes(path$1.join(sourcePath, id)) && !needExternal(id),
plugins: createRollupPlugins(name, env)
});
fs$1.ensureDirSync(outputPath);
const { output } = await bundle.generate({
dir: outputPath,
format: "esm",
exports: "named",
sourcemap,
entryFileNames: (chunk) => {
let id = chunk.facadeModuleId;
if (id?.startsWith(`${APP_NAME}:`)) {
id = id.replace(`${APP_NAME}:`, "");
}
id = id?.replace(sourcePath, "") ?? "";
id = id.replace(/^\//, "");
if (id.endsWith(".js") || id.endsWith(".mjs")) {
return id;
}
return `${id}.js`;
},
chunkFileNames: "[hash].js"
});
await Promise.all(output.map((chunk) => {
if (chunk.type === "chunk") {
const map = chunk.map?.toString();
const encoding = {
encoding: "utf8"
};
const filename = chunk.fileName;
return Promise.all([
fs$1.outputFile(path$1.join(outputPath, filename), chunk.code, encoding),
map && fs$1.outputFile(path$1.join(outputPath, `${filename}.map`), map, encoding)
]);
}
return () => {
};
}));
}
async function doBuildSingleEntry({
input,
sourcePath,
outputPath,
env,
name,
sourcemap,
devPrefix = "dev."
}) {
try {
const bundle = await rollup({
input,
treeshake: { moduleSideEffects: true },
onwarn: onWarning,
external: (id) => path$1.join(id) !== path$1.join(input) && !needExternal(id),
plugins: createRollupPlugins(name, env)
});
fs$1.ensureDirSync(outputPath);
let file = path$1.join(outputPath, path$1.relative(sourcePath, input));
const basename = path$1.basename(input);
if (basename === "package.json") {
file = path$1.join(outputPath, "package.json.js");
}
if (env === "development") {
file = file.replace(basename, `${devPrefix}${basename}`);
}
await bundle.write({
file,
exports: "named",
sourcemap
});
} catch (error) {
throw new Error(error);
}
}
function createRollupPlugins(name, env) {
return [
peerDepsExternal(),
resolve$1({
preferBuiltins: false,
browser: true,
extensions: [".mjs", ".cjs", ".js", ".json"]
}),
rollupJSONPlugin({
preferConst: true,
indent: " ",
compact: false,
namedExports: true
}),
commonjs({
extensions: [".js", ".cjs"],
esmExternals: true,
requireReturnsDefault: "auto"
}),
rollupPluginWrapTargets(false, name),
esbuild({
minify: true,
define: {
"process.env.NODE_ENV": JSON.stringify(env),
"process.env.VUE_ENV": JSON.stringify("browser")
}
}),
rollupPluginNodeProcessPolyfill({
NODE_ENV: env
}),
nodePolyfills()
].filter(Boolean);
}
function needExternal(id) {
return id.startsWith(`${APP_NAME}:`) || id.startsWith(`node:`) || id[0] === "." || path$1.isAbsolute(id) || ["process", "Buffer", "module"].includes(id) || path$1.basename(id) === "package.json";
}
function onWarning(warning, handler) {
if (["THIS_IS_UNDEFINED", "UNRESOLVED_IMPORT", "SOURCEMAP_ERROR"].includes(warning.code)) {
return;
}
handler(warning);
}
export { build, doBuildMultipleEntry, doBuildSingleEntry, isDynamicEntry, normalizeExport, removeFileExt, resolveDevFilename, resolveExports, resolveFiles, resolveImports, resolvePackage };