Primeiro commit do projeto Angular
This commit is contained in:
+1
@@ -0,0 +1 @@
|
||||
export { };
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { n as __toESM, t as require_binding } from "./shared/binding-DzKFaUu2.mjs";
|
||||
|
||||
//#region src/cli/setup-index.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
let isWatchMode = false;
|
||||
for (let i = 0; i < process.argv.length; i++) {
|
||||
const arg = process.argv[i];
|
||||
if (arg === "--watch" || arg === "-w") {
|
||||
isWatchMode = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isWatchMode) (0, import_binding.createTokioRuntime)(32);
|
||||
else (0, import_binding.createTokioRuntime)(4);
|
||||
|
||||
//#endregion
|
||||
export { };
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { };
|
||||
+609
@@ -0,0 +1,609 @@
|
||||
import "./shared/binding-DzKFaUu2.mjs";
|
||||
import { n as onExit, t as watch } from "./shared/watch-CgVvtyIH.mjs";
|
||||
import "./shared/normalize-string-or-regex-0P4NpnRa.mjs";
|
||||
import { S as version, x as description } from "./shared/bindingify-input-options-phmnMdxa.mjs";
|
||||
import { t as arraify } from "./shared/misc-CCZIsXVO.mjs";
|
||||
import { a as getInputCliKeys, i as getCliSchemaInfo, l as styleText$1, o as getOutputCliKeys, r as logger, s as validateCliOptions } from "./shared/rolldown-build-CjERPB8v.mjs";
|
||||
import "./shared/error-DC8XkJKP.mjs";
|
||||
import "./shared/parse-DIfx5aEh.mjs";
|
||||
import { t as rolldown } from "./shared/rolldown-6S97x4m9.mjs";
|
||||
import { t as loadConfig } from "./shared/load-config-ae-aexjN.mjs";
|
||||
import path from "node:path";
|
||||
import { parseArgs } from "node:util";
|
||||
import process$1 from "node:process";
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
//#region src/cli/arguments/alias.ts
|
||||
const alias = {
|
||||
config: {
|
||||
abbreviation: "c",
|
||||
hint: "filename"
|
||||
},
|
||||
help: { abbreviation: "h" },
|
||||
version: { abbreviation: "v" },
|
||||
watch: { abbreviation: "w" },
|
||||
dir: { abbreviation: "d" },
|
||||
file: { abbreviation: "o" },
|
||||
external: { abbreviation: "e" },
|
||||
format: { abbreviation: "f" },
|
||||
name: { abbreviation: "n" },
|
||||
globals: { abbreviation: "g" },
|
||||
sourcemap: {
|
||||
abbreviation: "s",
|
||||
default: true
|
||||
},
|
||||
minify: { abbreviation: "m" },
|
||||
platform: { abbreviation: "p" },
|
||||
assetFileNames: { hint: "name" },
|
||||
chunkFileNames: { hint: "name" },
|
||||
entryFileNames: { hint: "name" },
|
||||
externalLiveBindings: {
|
||||
default: true,
|
||||
reverse: true
|
||||
},
|
||||
treeshake: {
|
||||
default: true,
|
||||
reverse: true
|
||||
},
|
||||
preserveEntrySignatures: {
|
||||
default: "strict",
|
||||
reverse: true
|
||||
},
|
||||
moduleTypes: { hint: "types" }
|
||||
};
|
||||
|
||||
//#endregion
|
||||
//#region src/cli/arguments/utils.ts
|
||||
function setNestedProperty(obj, path, value) {
|
||||
const keys = path.split(".");
|
||||
let current = obj;
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
if (!current[keys[i]]) current[keys[i]] = {};
|
||||
current = current[keys[i]];
|
||||
}
|
||||
const finalKey = keys[keys.length - 1];
|
||||
Object.defineProperty(current, finalKey, {
|
||||
value,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
function camelCaseToKebabCase(str) {
|
||||
return str.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
|
||||
}
|
||||
function kebabCaseToCamelCase(str) {
|
||||
return str.replace(/-./g, (match) => match[1].toUpperCase());
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/cli/arguments/normalize.ts
|
||||
function normalizeCliOptions(cliOptions, positionals) {
|
||||
const prototypePollutionKeys = [
|
||||
"__proto__",
|
||||
"constructor",
|
||||
"prototype"
|
||||
];
|
||||
const unflattenedCliOptions = {};
|
||||
for (let [key, value] of Object.entries(cliOptions)) if (prototypePollutionKeys.includes(key)) {} else if (key.includes(".")) {
|
||||
const [parentKey] = key.split(".");
|
||||
unflattenedCliOptions[parentKey] ??= {};
|
||||
setNestedProperty(unflattenedCliOptions, key, value);
|
||||
} else unflattenedCliOptions[key] = value;
|
||||
const [data, errors] = validateCliOptions(unflattenedCliOptions);
|
||||
if (errors?.length) {
|
||||
errors.forEach((error) => {
|
||||
logger.error(`${error}. You can use \`rolldown -h\` to see the help.`);
|
||||
});
|
||||
process.exit(1);
|
||||
}
|
||||
const options = data ?? {};
|
||||
const result = {
|
||||
input: {},
|
||||
output: {},
|
||||
help: options.help ?? false,
|
||||
version: options.version ?? false,
|
||||
watch: options.watch ?? false
|
||||
};
|
||||
if (typeof options.config === "string") result.config = options.config;
|
||||
if (options.environment !== void 0) result.environment = options.environment;
|
||||
const keysOfInput = getInputCliKeys();
|
||||
const keysOfOutput = getOutputCliKeys();
|
||||
const reservedKeys = [
|
||||
"help",
|
||||
"version",
|
||||
"config",
|
||||
"watch",
|
||||
"environment"
|
||||
];
|
||||
for (let [key, value] of Object.entries(options)) {
|
||||
const [primary] = key.split(".");
|
||||
if (keysOfInput.includes(primary)) setNestedProperty(result.input, key, value);
|
||||
else if (keysOfOutput.includes(primary)) setNestedProperty(result.output, key, value);
|
||||
else if (!reservedKeys.includes(key)) {
|
||||
logger.error(`Unknown option: ${key}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
if (!result.config && positionals.length > 0) if (Array.isArray(result.input.input)) result.input.input.push(...positionals);
|
||||
else result.input.input = positionals;
|
||||
return result;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/cli/arguments/index.ts
|
||||
const schemaInfo = getCliSchemaInfo();
|
||||
const options = Object.fromEntries(Object.entries(schemaInfo).filter(([_key, info]) => info.type !== "never").map(([key, info]) => {
|
||||
const config = Object.getOwnPropertyDescriptor(alias, key)?.value;
|
||||
const result = {
|
||||
type: info.type === "boolean" ? "boolean" : "string",
|
||||
description: info?.description ?? config?.description ?? "",
|
||||
hint: config?.hint
|
||||
};
|
||||
if (config && config?.abbreviation) result.short = config?.abbreviation;
|
||||
if (config && config.reverse) {
|
||||
if (result.description.startsWith("enable")) result.description = result.description.replace("enable", "disable");
|
||||
else if (!result.description.startsWith("Avoid")) result.description = `disable ${result.description}`;
|
||||
}
|
||||
key = camelCaseToKebabCase(key);
|
||||
return [config?.reverse ? `no-${key}` : key, result];
|
||||
}));
|
||||
function parseCliArguments() {
|
||||
const { values, tokens, positionals } = parseArgs({
|
||||
options,
|
||||
tokens: true,
|
||||
allowPositionals: true,
|
||||
strict: false
|
||||
});
|
||||
let invalid_options = tokens.filter((token) => token.kind === "option").map((option) => {
|
||||
let negative = false;
|
||||
if (option.name.startsWith("no-")) {
|
||||
const name = kebabCaseToCamelCase(option.name.substring(3));
|
||||
if (name in schemaInfo) {
|
||||
delete values[option.name];
|
||||
option.name = name;
|
||||
negative = true;
|
||||
}
|
||||
}
|
||||
delete values[option.name];
|
||||
option.name = kebabCaseToCamelCase(option.name);
|
||||
let originalInfo = schemaInfo[option.name];
|
||||
if (!originalInfo) return {
|
||||
name: option.name,
|
||||
value: option.value
|
||||
};
|
||||
let type = originalInfo.type;
|
||||
if (type === "string" && typeof option.value !== "string") {
|
||||
let opt = option;
|
||||
let defaultValue = Object.getOwnPropertyDescriptor(alias, opt.name)?.value;
|
||||
Object.defineProperty(values, opt.name, {
|
||||
value: defaultValue.default ?? "",
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
} else if (type === "object" && typeof option.value === "string") {
|
||||
const pairs = option.value.split(",").map((x) => x.split("="));
|
||||
if (!values[option.name]) Object.defineProperty(values, option.name, {
|
||||
value: {},
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
for (const [key, value] of pairs) if (key && value) Object.defineProperty(values[option.name], key, {
|
||||
value,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
} else if (type === "array" && typeof option.value === "string") {
|
||||
if (!values[option.name]) Object.defineProperty(values, option.name, {
|
||||
value: [],
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
values[option.name].push(option.value);
|
||||
} else if (type === "boolean") Object.defineProperty(values, option.name, {
|
||||
value: !negative,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
else if (type === "union") {
|
||||
let defaultValue = Object.getOwnPropertyDescriptor(alias, option.name)?.value;
|
||||
Object.defineProperty(values, option.name, {
|
||||
value: option.value ?? defaultValue?.default ?? "",
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
} else Object.defineProperty(values, option.name, {
|
||||
value: option.value ?? "",
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
}).filter((item) => {
|
||||
return item !== void 0;
|
||||
});
|
||||
invalid_options.sort((a, b) => {
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
if (invalid_options.length !== 0) {
|
||||
let single = invalid_options.length === 1;
|
||||
logger.warn(`Option \`${invalid_options.map((item) => item.name).join(",")}\` ${single ? "is" : "are"} unrecognized. We will ignore ${single ? "this" : "those"} option${single ? "" : "s"}.`);
|
||||
}
|
||||
let rawArgs = {
|
||||
...values,
|
||||
...invalid_options.reduce((acc, cur) => {
|
||||
acc[cur.name] = cur.value;
|
||||
return acc;
|
||||
}, Object.create(null))
|
||||
};
|
||||
return {
|
||||
...normalizeCliOptions(values, positionals),
|
||||
rawArgs
|
||||
};
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/utils/clear-screen.ts
|
||||
const CLEAR_SCREEN = "\x1Bc";
|
||||
function getClearScreenFunction(options) {
|
||||
const isTTY = process.stdout.isTTY;
|
||||
const isAnyOptionNotAllowingClearScreen = arraify(options).some(({ watch }) => watch === false || watch?.clearScreen === false);
|
||||
if (isTTY && !isAnyOptionNotAllowingClearScreen) return () => {
|
||||
process.stdout.write(CLEAR_SCREEN);
|
||||
};
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region \0@oxc-project+runtime@0.113.0/helpers/usingCtx.js
|
||||
function _usingCtx() {
|
||||
var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
|
||||
var n = Error();
|
||||
return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
|
||||
}, e = {}, n = [];
|
||||
function using(r, e) {
|
||||
if (null != e) {
|
||||
if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
|
||||
if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
|
||||
if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
|
||||
if ("function" != typeof o) throw new TypeError("Object is not disposable.");
|
||||
t && (o = function o() {
|
||||
try {
|
||||
t.call(e);
|
||||
} catch (r) {
|
||||
return Promise.reject(r);
|
||||
}
|
||||
}), n.push({
|
||||
v: e,
|
||||
d: o,
|
||||
a: r
|
||||
});
|
||||
} else r && n.push({
|
||||
d: e,
|
||||
a: r
|
||||
});
|
||||
return e;
|
||||
}
|
||||
return {
|
||||
e,
|
||||
u: using.bind(null, !1),
|
||||
a: using.bind(null, !0),
|
||||
d: function d() {
|
||||
var o, t = this.e, s = 0;
|
||||
function next() {
|
||||
for (; o = n.pop();) try {
|
||||
if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
|
||||
if (o.d) {
|
||||
var r = o.d.call(o.v);
|
||||
if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
|
||||
} else s |= 1;
|
||||
} catch (r) {
|
||||
return err(r);
|
||||
}
|
||||
if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
|
||||
if (t !== e) throw t;
|
||||
}
|
||||
function err(n) {
|
||||
return t = t !== e ? new r(n, t) : n, next();
|
||||
}
|
||||
return next();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/cli/commands/bundle.ts
|
||||
async function bundleWithConfig(configPath, cliOptions, rawArgs = {}) {
|
||||
if (cliOptions.watch) {
|
||||
process.env.ROLLUP_WATCH = "true";
|
||||
process.env.ROLLDOWN_WATCH = "true";
|
||||
}
|
||||
const config = await loadConfig(configPath);
|
||||
const resolvedConfig = typeof config === "function" ? await config(rawArgs) : config;
|
||||
if (typeof resolvedConfig !== "object" || resolvedConfig === null) {
|
||||
logger.error(`Invalid configuration from ${configPath}: expected object or array, got ${resolvedConfig}`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (cliOptions.watch) await watchInner(resolvedConfig, cliOptions);
|
||||
else await bundleInner(resolvedConfig, cliOptions);
|
||||
}
|
||||
async function bundleWithCliOptions(cliOptions) {
|
||||
try {
|
||||
var _usingCtx$1 = _usingCtx();
|
||||
if (cliOptions.output.dir || cliOptions.output.file) {
|
||||
await (cliOptions.watch ? watchInner : bundleInner)({}, cliOptions);
|
||||
return;
|
||||
}
|
||||
if (cliOptions.watch) {
|
||||
logger.error("You must specify `output.dir` to use watch mode");
|
||||
process.exit(1);
|
||||
}
|
||||
const { output: outputs } = await _usingCtx$1.a(await rolldown(cliOptions.input)).generate(cliOptions.output);
|
||||
if (outputs.length === 0) {
|
||||
logger.error("No output generated");
|
||||
process.exit(1);
|
||||
}
|
||||
for (const file of outputs) {
|
||||
if (outputs.length > 1) logger.log(`\n${styleText$1(["cyan", "bold"], `|→ ${file.fileName}:`)}\n`);
|
||||
console.log(file.type === "asset" ? file.source : file.code);
|
||||
}
|
||||
} catch (_) {
|
||||
_usingCtx$1.e = _;
|
||||
} finally {
|
||||
await _usingCtx$1.d();
|
||||
}
|
||||
}
|
||||
async function watchInner(config, cliOptions) {
|
||||
let normalizedConfig = arraify(config).map((option) => {
|
||||
return {
|
||||
...option,
|
||||
...cliOptions.input,
|
||||
output: arraify(option.output || {}).map((output) => {
|
||||
return {
|
||||
...output,
|
||||
...cliOptions.output
|
||||
};
|
||||
})
|
||||
};
|
||||
});
|
||||
const watcher = watch(normalizedConfig);
|
||||
onExit((code) => {
|
||||
Promise.resolve(watcher.close()).finally(() => {
|
||||
process.exit(typeof code === "number" ? code : 0);
|
||||
});
|
||||
return true;
|
||||
});
|
||||
const changedFile = [];
|
||||
watcher.on("change", (id, event) => {
|
||||
if (event.event === "update") changedFile.push(id);
|
||||
});
|
||||
const clearScreen = getClearScreenFunction(normalizedConfig);
|
||||
watcher.on("event", async (event) => {
|
||||
switch (event.code) {
|
||||
case "START":
|
||||
clearScreen?.();
|
||||
break;
|
||||
case "BUNDLE_START":
|
||||
if (changedFile.length > 0) logger.log(`Found ${styleText$1("bold", changedFile.map(relativeId).join(", "))} changed, rebuilding...`);
|
||||
changedFile.length = 0;
|
||||
break;
|
||||
case "BUNDLE_END":
|
||||
await event.result.close();
|
||||
logger.success(`Rebuilt ${styleText$1("bold", relativeId(event.output[0]))} in ${styleText$1("green", ms(event.duration))}.`);
|
||||
break;
|
||||
case "ERROR":
|
||||
await event.result.close();
|
||||
logger.error(event.error);
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
});
|
||||
logger.log(`Waiting for changes...`);
|
||||
}
|
||||
async function bundleInner(config, cliOptions) {
|
||||
const startTime = performance.now();
|
||||
const result = [];
|
||||
const configList = arraify(config);
|
||||
for (const config of configList) {
|
||||
const outputList = arraify(config.output || {});
|
||||
const build = await rolldown({
|
||||
...config,
|
||||
...cliOptions.input
|
||||
});
|
||||
try {
|
||||
for (const output of outputList) result.push(await build.write({
|
||||
...output,
|
||||
...cliOptions.output
|
||||
}));
|
||||
} finally {
|
||||
await build.close();
|
||||
}
|
||||
}
|
||||
result.forEach(printBundleOutputPretty);
|
||||
logger.log(``);
|
||||
const duration = performance.now() - startTime;
|
||||
logger.success(`rolldown v${version} Finished in ${styleText$1("green", ms(duration))}`);
|
||||
}
|
||||
function printBundleOutputPretty(output) {
|
||||
const outputEntries = collectOutputEntries(output.output);
|
||||
printOutputEntries(outputEntries, collectOutputLayoutAdjustmentSizes(outputEntries), "<DIR>");
|
||||
}
|
||||
function collectOutputEntries(output) {
|
||||
return output.map((chunk) => ({
|
||||
type: chunk.type,
|
||||
fileName: chunk.fileName,
|
||||
size: chunk.type === "chunk" ? Buffer.byteLength(chunk.code) : Buffer.byteLength(chunk.source)
|
||||
}));
|
||||
}
|
||||
function collectOutputLayoutAdjustmentSizes(entries) {
|
||||
let longest = 0;
|
||||
let biggestSize = 0;
|
||||
for (const entry of entries) {
|
||||
if (entry.fileName.length > longest) longest = entry.fileName.length;
|
||||
if (entry.size > biggestSize) biggestSize = entry.size;
|
||||
}
|
||||
const sizePad = displaySize(biggestSize).length;
|
||||
return {
|
||||
longest,
|
||||
biggestSize,
|
||||
sizePad
|
||||
};
|
||||
}
|
||||
const numberFormatter = new Intl.NumberFormat("en", {
|
||||
maximumFractionDigits: 2,
|
||||
minimumFractionDigits: 2
|
||||
});
|
||||
function displaySize(bytes) {
|
||||
return `${numberFormatter.format(bytes / 1e3)} kB`;
|
||||
}
|
||||
const CHUNK_GROUPS = [{
|
||||
type: "asset",
|
||||
color: "green"
|
||||
}, {
|
||||
type: "chunk",
|
||||
color: "cyan"
|
||||
}];
|
||||
function printOutputEntries(entries, sizeAdjustment, distPath) {
|
||||
for (const group of CHUNK_GROUPS) {
|
||||
const filtered = entries.filter((e) => e.type === group.type);
|
||||
if (!filtered.length) continue;
|
||||
for (const entry of filtered.sort((a, z) => a.size - z.size)) {
|
||||
let log = styleText$1("dim", withTrailingSlash(distPath));
|
||||
log += styleText$1(group.color, entry.fileName.padEnd(sizeAdjustment.longest + 2));
|
||||
log += styleText$1("dim", entry.type);
|
||||
log += styleText$1("dim", ` │ size: ${displaySize(entry.size).padStart(sizeAdjustment.sizePad)}`);
|
||||
logger.log(log);
|
||||
}
|
||||
}
|
||||
}
|
||||
function withTrailingSlash(path) {
|
||||
if (path[path.length - 1] !== "/") return `${path}/`;
|
||||
return path;
|
||||
}
|
||||
function ms(duration) {
|
||||
return duration < 1e3 ? `${duration.toFixed(2)} ms` : `${(duration / 1e3).toFixed(2)} s`;
|
||||
}
|
||||
function relativeId(id) {
|
||||
if (!path.isAbsolute(id)) return id;
|
||||
return path.relative(path.resolve(), id);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/cli/commands/help.ts
|
||||
const examples = [
|
||||
{
|
||||
title: "Bundle with a config file `rolldown.config.mjs`",
|
||||
command: "rolldown -c rolldown.config.mjs"
|
||||
},
|
||||
{
|
||||
title: "Bundle the `src/main.ts` to `dist` with `cjs` format",
|
||||
command: "rolldown src/main.ts -d dist -f cjs"
|
||||
},
|
||||
{
|
||||
title: "Bundle the `src/main.ts` and handle the `.png` assets to Data URL",
|
||||
command: "rolldown src/main.ts -d dist --moduleTypes .png=dataurl"
|
||||
},
|
||||
{
|
||||
title: "Bundle the `src/main.tsx` and minify the output with sourcemap",
|
||||
command: "rolldown src/main.tsx -d dist -m -s"
|
||||
},
|
||||
{
|
||||
title: "Create self-executing IIFE using external jQuery as `$` and `_`",
|
||||
command: "rolldown src/main.ts -d dist -n bundle -f iife -e jQuery,window._ -g jQuery=$"
|
||||
}
|
||||
];
|
||||
const notes = [
|
||||
"Due to the API limitation, you need to pass `-s` for `.map` sourcemap file as the last argument.",
|
||||
"If you are using the configuration, please pass the `-c` as the last argument if you ignore the default configuration file.",
|
||||
"CLI options will override the configuration file.",
|
||||
"For more information, please visit https://rolldown.rs/."
|
||||
];
|
||||
/**
|
||||
* Generates the CLI help text as a string.
|
||||
*/
|
||||
function generateHelpText() {
|
||||
const lines = [];
|
||||
lines.push(`${styleText$1("gray", `${description} (rolldown v${version})`)}`);
|
||||
lines.push("");
|
||||
lines.push(`${styleText$1(["bold", "underline"], "USAGE")} ${styleText$1("cyan", "rolldown -c <config>")} or ${styleText$1("cyan", "rolldown <input> <options>")}`);
|
||||
lines.push("");
|
||||
lines.push(`${styleText$1(["bold", "underline"], "OPTIONS")}`);
|
||||
lines.push("");
|
||||
lines.push(Object.entries(options).sort(([a], [b]) => {
|
||||
if (options[a].short && !options[b].short) return -1;
|
||||
if (!options[a].short && options[b].short) return 1;
|
||||
if (options[a].short && options[b].short) return options[a].short.localeCompare(options[b].short);
|
||||
return a.localeCompare(b);
|
||||
}).map(([option, { type, short, hint, description }]) => {
|
||||
let optionStr = ` --${option} `;
|
||||
option = camelCaseToKebabCase(option);
|
||||
if (short) optionStr += `-${short}, `;
|
||||
if (type === "string") optionStr += `<${hint ?? option}>`;
|
||||
if (description && description.length > 0) description = description[0].toUpperCase() + description.slice(1);
|
||||
return styleText$1("cyan", optionStr.padEnd(30)) + description + (description && description?.endsWith(".") ? "" : ".");
|
||||
}).join("\n"));
|
||||
lines.push("");
|
||||
lines.push(`${styleText$1(["bold", "underline"], "EXAMPLES")}`);
|
||||
lines.push("");
|
||||
examples.forEach(({ title, command }, ord) => {
|
||||
lines.push(` ${ord + 1}. ${title}:`);
|
||||
lines.push(` ${styleText$1("cyan", command)}`);
|
||||
lines.push("");
|
||||
});
|
||||
lines.push(`${styleText$1(["bold", "underline"], "NOTES")}`);
|
||||
lines.push("");
|
||||
notes.forEach((note) => {
|
||||
lines.push(` * ${styleText$1("gray", note)}`);
|
||||
});
|
||||
return lines.join("\n");
|
||||
}
|
||||
function showHelp() {
|
||||
logger.log(generateHelpText());
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/cli/version-check.ts
|
||||
function checkNodeVersion(nodeVersion) {
|
||||
const currentVersion = nodeVersion.split(".");
|
||||
const major = parseInt(currentVersion[0], 10);
|
||||
const minor = parseInt(currentVersion[1], 10);
|
||||
return major === 20 && minor >= 19 || major === 22 && minor >= 12 || major > 22;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/cli/index.ts
|
||||
if (!checkNodeVersion(process$1.versions.node)) logger.warn(`You are using Node.js ${process$1.versions.node}. Rolldown requires Node.js version 20.19+ or 22.12+. Please upgrade your Node.js version.`);
|
||||
async function main() {
|
||||
const { rawArgs, ...cliOptions } = parseCliArguments();
|
||||
if (cliOptions.environment) {
|
||||
const environment = Array.isArray(cliOptions.environment) ? cliOptions.environment : [cliOptions.environment];
|
||||
for (const argument of environment) for (const pair of argument.split(",")) {
|
||||
const [key, ...value] = pair.split(":");
|
||||
process$1.env[key] = value.length === 0 ? String(true) : value.join(":");
|
||||
}
|
||||
}
|
||||
if (cliOptions.config || cliOptions.config === "") {
|
||||
await bundleWithConfig(cliOptions.config, cliOptions, rawArgs);
|
||||
return;
|
||||
}
|
||||
if ("input" in cliOptions.input) {
|
||||
await bundleWithCliOptions(cliOptions);
|
||||
return;
|
||||
}
|
||||
if (cliOptions.version) {
|
||||
logger.log(`rolldown v${version}`);
|
||||
return;
|
||||
}
|
||||
showHelp();
|
||||
}
|
||||
main().catch((err) => {
|
||||
logger.error(err);
|
||||
process$1.exit(1);
|
||||
});
|
||||
|
||||
//#endregion
|
||||
export { };
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import "./shared/binding-BLUhc7Nl.mjs";
|
||||
import { P as VERSION, r as defineConfig, t as ConfigExport } from "./shared/define-config-Cj8yDgkV.mjs";
|
||||
|
||||
//#region src/utils/load-config.d.ts
|
||||
declare function loadConfig(configPath: string): Promise<ConfigExport>;
|
||||
//#endregion
|
||||
export { VERSION, defineConfig, loadConfig };
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import "./shared/binding-DzKFaUu2.mjs";
|
||||
import "./shared/normalize-string-or-regex-0P4NpnRa.mjs";
|
||||
import { b as VERSION } from "./shared/bindingify-input-options-phmnMdxa.mjs";
|
||||
import "./shared/rolldown-build-CjERPB8v.mjs";
|
||||
import "./shared/error-DC8XkJKP.mjs";
|
||||
import "./shared/parse-DIfx5aEh.mjs";
|
||||
import "./shared/rolldown-6S97x4m9.mjs";
|
||||
import { t as defineConfig } from "./shared/define-config-B-Hn45NS.mjs";
|
||||
import { t as loadConfig } from "./shared/load-config-ae-aexjN.mjs";
|
||||
|
||||
export { VERSION, defineConfig, loadConfig };
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
import { A as IsolatedDeclarationsOptions, B as ResolverFactory, D as BindingViteTransformPluginConfig, F as NapiResolveOptions, G as isolatedDeclaration, I as ParseResult$1, J as resolveTsconfig, K as isolatedDeclarationSync, L as ParserOptions$1, P as MinifyResult$1, S as BindingViteManifestPluginConfig, U as TsconfigCache$1, W as createTokioRuntime, _ as BindingTsconfigRawOptions, a as BindingEnhancedTransformOptions, f as BindingRebuildStrategy, g as BindingTsconfigCompilerOptions, i as BindingClientHmrUpdate, j as IsolatedDeclarationsResult, n as BindingBundleAnalyzerPluginConfig, q as moduleRunnerTransform, r as BindingBundleState, z as ResolveResult } from "./shared/binding-BLUhc7Nl.mjs";
|
||||
import { Gt as freeExternalMemory, J as defineParallelPlugin, M as BuiltinPlugin, Pt as OutputOptions, Ut as RolldownOutput, at as NormalizedOutputOptions, c as InputOptions } from "./shared/define-config-Cj8yDgkV.mjs";
|
||||
import { a as viteImportGlobPlugin, c as viteModulePreloadPolyfillPlugin, d as viteResolvePlugin, f as viteWasmFallbackPlugin, i as viteDynamicImportVarsPlugin, l as viteReactRefreshWrapperPlugin, n as isolatedDeclarationPlugin, o as viteJsonPlugin, p as viteWebWorkerPostPlugin, r as viteBuildImportAnalysisPlugin, s as viteLoadFallbackPlugin, u as viteReporterPlugin } from "./shared/constructors-DIU14v_Z.mjs";
|
||||
import { a as minify$1, c as parseSync$1, i as MinifyOptions$1, n as transform$1, o as minifySync$1, r as transformSync$1, s as parse$1, t as TransformResult$1 } from "./shared/transform-CfCvdTIT.mjs";
|
||||
|
||||
//#region src/api/dev/dev-options.d.ts
|
||||
type DevOnHmrUpdates = (result: Error | {
|
||||
updates: BindingClientHmrUpdate[];
|
||||
changedFiles: string[];
|
||||
}) => void | Promise<void>;
|
||||
type DevOnOutput = (result: Error | RolldownOutput) => void | Promise<void>;
|
||||
interface DevWatchOptions {
|
||||
/**
|
||||
* If `true`, files are not written to disk.
|
||||
* @default false
|
||||
*/
|
||||
skipWrite?: boolean;
|
||||
/**
|
||||
* If `true`, use polling instead of native file system events for watching.
|
||||
* @default false
|
||||
*/
|
||||
usePolling?: boolean;
|
||||
/**
|
||||
* Poll interval in milliseconds (only used when usePolling is true).
|
||||
* @default 100
|
||||
*/
|
||||
pollInterval?: number;
|
||||
/**
|
||||
* If `true`, use debounced watcher. If `false`, use non-debounced watcher for immediate responses.
|
||||
* @default true
|
||||
*/
|
||||
useDebounce?: boolean;
|
||||
/**
|
||||
* Debounce duration in milliseconds (only used when useDebounce is true).
|
||||
* @default 10
|
||||
*/
|
||||
debounceDuration?: number;
|
||||
/**
|
||||
* Whether to compare file contents for poll-based watchers (only used when usePolling is true).
|
||||
* When enabled, poll watchers will check file contents to determine if they actually changed.
|
||||
* @default false
|
||||
*/
|
||||
compareContentsForPolling?: boolean;
|
||||
/**
|
||||
* Tick rate in milliseconds for debounced watchers (only used when useDebounce is true).
|
||||
* Controls how frequently the debouncer checks for events to process.
|
||||
* When not specified, the debouncer will auto-select an appropriate tick rate (1/4 of the debounce duration).
|
||||
* @default undefined (auto-select)
|
||||
*/
|
||||
debounceTickRate?: number;
|
||||
}
|
||||
interface DevOptions {
|
||||
onHmrUpdates?: DevOnHmrUpdates;
|
||||
onOutput?: DevOnOutput;
|
||||
/**
|
||||
* Strategy for triggering rebuilds after HMR updates.
|
||||
* - `'always'`: Always trigger a rebuild after HMR updates
|
||||
* - `'auto'`: Trigger rebuild only if HMR updates contain full reload updates
|
||||
* - `'never'`: Never trigger rebuild after HMR updates (default)
|
||||
* @default 'auto'
|
||||
*/
|
||||
rebuildStrategy?: "always" | "auto" | "never";
|
||||
watch?: DevWatchOptions;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/api/dev/dev-engine.d.ts
|
||||
declare class DevEngine {
|
||||
#private;
|
||||
static create(inputOptions: InputOptions, outputOptions?: OutputOptions, devOptions?: DevOptions): Promise<DevEngine>;
|
||||
private constructor();
|
||||
run(): Promise<void>;
|
||||
ensureCurrentBuildFinish(): Promise<void>;
|
||||
getBundleState(): Promise<BindingBundleState>;
|
||||
ensureLatestBuildOutput(): Promise<void>;
|
||||
invalidate(file: string, firstInvalidatedBy?: string): Promise<BindingClientHmrUpdate[]>;
|
||||
registerModules(clientId: string, modules: string[]): Promise<void>;
|
||||
removeClient(clientId: string): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
/**
|
||||
* Compile a lazy entry module and return HMR-style patch code.
|
||||
*
|
||||
* This is called when a dynamically imported module is first requested at runtime.
|
||||
* The module was previously stubbed with a proxy, and now we need to compile the
|
||||
* actual module and its dependencies.
|
||||
*
|
||||
* @param moduleId - The absolute file path of the module to compile
|
||||
* @param clientId - The client ID requesting this compilation
|
||||
* @returns The compiled JavaScript code as a string (HMR patch format)
|
||||
*/
|
||||
compileEntry(moduleId: string, clientId: string): Promise<string>;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/api/dev/index.d.ts
|
||||
declare const dev: typeof DevEngine.create;
|
||||
//#endregion
|
||||
//#region src/api/experimental.d.ts
|
||||
/**
|
||||
* This is an experimental API. Its behavior may change in the future.
|
||||
*
|
||||
* - Calling this API will only execute the `scan/build` stage of rolldown.
|
||||
* - `scan` will clean up all resources automatically, but if you want to ensure timely cleanup, you need to wait for the returned promise to resolve.
|
||||
*
|
||||
* @example To ensure cleanup of resources, use the returned promise to wait for the scan to complete.
|
||||
* ```ts
|
||||
* import { scan } from 'rolldown/api/experimental';
|
||||
*
|
||||
* const cleanupPromise = await scan(...);
|
||||
* await cleanupPromise;
|
||||
* // Now all resources have been cleaned up.
|
||||
* ```
|
||||
*/
|
||||
declare const scan: (rawInputOptions: InputOptions, rawOutputOptions?: {}) => Promise<Promise<void>>;
|
||||
//#endregion
|
||||
//#region src/builtin-plugin/alias-plugin.d.ts
|
||||
type ViteAliasPluginConfig = {
|
||||
entries: {
|
||||
find: string | RegExp;
|
||||
replacement: string;
|
||||
}[];
|
||||
};
|
||||
declare function viteAliasPlugin(config: ViteAliasPluginConfig): BuiltinPlugin;
|
||||
//#endregion
|
||||
//#region src/builtin-plugin/bundle-analyzer-plugin.d.ts
|
||||
/**
|
||||
* A plugin that analyzes bundle composition and generates detailed reports.
|
||||
*
|
||||
* The plugin outputs a JSON file containing detailed information about:
|
||||
* - All chunks and their relationships
|
||||
* - Modules bundled in each chunk
|
||||
* - Import dependencies between chunks
|
||||
* - Reachable modules from each entry point
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
|
||||
*
|
||||
* export default {
|
||||
* plugins: [
|
||||
* bundleAnalyzerPlugin()
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* **Custom filename**
|
||||
* ```js
|
||||
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
|
||||
*
|
||||
* export default {
|
||||
* plugins: [
|
||||
* bundleAnalyzerPlugin({
|
||||
* fileName: 'bundle-analysis.json'
|
||||
* })
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
declare function bundleAnalyzerPlugin(config?: BindingBundleAnalyzerPluginConfig): BuiltinPlugin;
|
||||
//#endregion
|
||||
//#region src/builtin-plugin/transform-plugin.d.ts
|
||||
type TransformPattern = string | RegExp | readonly (RegExp | string)[];
|
||||
type TransformPluginConfig = Omit<BindingViteTransformPluginConfig, "include" | "exclude" | "jsxRefreshInclude" | "jsxRefreshExclude" | "yarnPnp"> & {
|
||||
include?: TransformPattern;
|
||||
exclude?: TransformPattern;
|
||||
jsxRefreshInclude?: TransformPattern;
|
||||
jsxRefreshExclude?: TransformPattern;
|
||||
};
|
||||
declare function viteTransformPlugin(config: TransformPluginConfig): BuiltinPlugin;
|
||||
//#endregion
|
||||
//#region src/builtin-plugin/vite-manifest-plugin.d.ts
|
||||
type ViteManifestPluginConfig = Omit<BindingViteManifestPluginConfig, "isLegacy"> & {
|
||||
isOutputOptionsForLegacyChunks?: (outputOptions: NormalizedOutputOptions) => boolean;
|
||||
};
|
||||
declare function viteManifestPlugin(config: ViteManifestPluginConfig): BuiltinPlugin;
|
||||
//#endregion
|
||||
//#region src/experimental-index.d.ts
|
||||
/**
|
||||
* In-memory file system for browser builds.
|
||||
*
|
||||
* This is a re-export of the {@link https://github.com/streamich/memfs | memfs} package used by the WASI runtime.
|
||||
* It allows you to read and write files to a virtual filesystem when using rolldown in browser environments.
|
||||
*
|
||||
* - `fs`: A Node.js-compatible filesystem API (`IFs` from memfs)
|
||||
* - `volume`: The underlying `Volume` instance that stores the filesystem state
|
||||
*
|
||||
* Returns `undefined` in Node.js builds (only available in browser builds via `@rolldown/browser`).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { memfs } from 'rolldown/experimental';
|
||||
*
|
||||
* // Write files to virtual filesystem before bundling
|
||||
* memfs?.volume.fromJSON({
|
||||
* '/src/index.js': 'export const foo = 42;',
|
||||
* '/package.json': '{"name": "my-app"}'
|
||||
* });
|
||||
*
|
||||
* // Read files from the virtual filesystem
|
||||
* const content = memfs?.fs.readFileSync('/src/index.js', 'utf8');
|
||||
* ```
|
||||
*
|
||||
* @see {@link https://github.com/streamich/memfs} for more information on the memfs API.
|
||||
*/
|
||||
declare const memfs: {
|
||||
fs: any;
|
||||
volume: any;
|
||||
} | undefined;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
declare const parse: typeof parse$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
declare const parseSync: typeof parseSync$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
type ParseResult = ParseResult$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
type ParserOptions = ParserOptions$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
declare const minify: typeof minify$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
declare const minifySync: typeof minifySync$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
type MinifyOptions = MinifyOptions$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
type MinifyResult = MinifyResult$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
declare const transform: typeof transform$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
declare const transformSync: typeof transformSync$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
type TransformOptions = BindingEnhancedTransformOptions;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
type TransformResult = TransformResult$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
declare const TsconfigCache: typeof TsconfigCache$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
type TsconfigRawOptions = BindingTsconfigRawOptions;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
type TsconfigCompilerOptions = BindingTsconfigCompilerOptions;
|
||||
//#endregion
|
||||
export { type BindingClientHmrUpdate, BindingRebuildStrategy, DevEngine, type DevOptions, type DevWatchOptions, type IsolatedDeclarationsOptions, type IsolatedDeclarationsResult, MinifyOptions, MinifyResult, ParseResult, ParserOptions, type NapiResolveOptions as ResolveOptions, type ResolveResult, ResolverFactory, TransformOptions, TransformResult, TsconfigCache, TsconfigCompilerOptions, TsconfigRawOptions, bundleAnalyzerPlugin, createTokioRuntime, defineParallelPlugin, dev, viteDynamicImportVarsPlugin as dynamicImportVarsPlugin, viteDynamicImportVarsPlugin, freeExternalMemory, viteImportGlobPlugin as importGlobPlugin, viteImportGlobPlugin, isolatedDeclaration, isolatedDeclarationPlugin, isolatedDeclarationSync, memfs, minify, minifySync, moduleRunnerTransform, parse, parseSync, resolveTsconfig, scan, transform, transformSync, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReactRefreshWrapperPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWasmFallbackPlugin, viteWebWorkerPostPlugin };
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
import { n as __toESM, t as require_binding } from "./shared/binding-DzKFaUu2.mjs";
|
||||
import { n as BuiltinPlugin, t as normalizedStringOrRegex } from "./shared/normalize-string-or-regex-0P4NpnRa.mjs";
|
||||
import { a as transformToRollupOutput } from "./shared/bindingify-input-options-phmnMdxa.mjs";
|
||||
import { c as validateOption, n as createBundlerOptions, t as RolldownBuild, u as PluginDriver } from "./shared/rolldown-build-CjERPB8v.mjs";
|
||||
import { i as unwrapBindingResult, r as normalizeBindingResult } from "./shared/error-DC8XkJKP.mjs";
|
||||
import { n as parseSync$1, t as parse$1 } from "./shared/parse-DIfx5aEh.mjs";
|
||||
import { a as viteImportGlobPlugin, c as viteModulePreloadPolyfillPlugin, d as viteResolvePlugin, f as viteWasmFallbackPlugin, i as viteDynamicImportVarsPlugin, l as viteReactRefreshWrapperPlugin, n as isolatedDeclarationPlugin, o as viteJsonPlugin, p as viteWebWorkerPostPlugin, r as viteBuildImportAnalysisPlugin, s as viteLoadFallbackPlugin, u as viteReporterPlugin } from "./shared/constructors-CfBLTWqY.mjs";
|
||||
import { a as minifySync$1, i as minify$1, n as transform$1, r as transformSync$1, t as import_binding$1 } from "./shared/transform-BRmOyKcA.mjs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
//#region src/api/dev/dev-engine.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
var DevEngine = class DevEngine {
|
||||
#inner;
|
||||
#cachedBuildFinishPromise = null;
|
||||
static async create(inputOptions, outputOptions = {}, devOptions = {}) {
|
||||
inputOptions = await PluginDriver.callOptionsHook(inputOptions);
|
||||
const options = await createBundlerOptions(inputOptions, outputOptions, false);
|
||||
const userOnHmrUpdates = devOptions.onHmrUpdates;
|
||||
const bindingOnHmrUpdates = userOnHmrUpdates ? function(rawResult) {
|
||||
const result = normalizeBindingResult(rawResult);
|
||||
if (result instanceof Error) {
|
||||
userOnHmrUpdates(result);
|
||||
return;
|
||||
}
|
||||
const [updates, changedFiles] = result;
|
||||
userOnHmrUpdates({
|
||||
updates,
|
||||
changedFiles
|
||||
});
|
||||
} : void 0;
|
||||
const userOnOutput = devOptions.onOutput;
|
||||
const bindingDevOptions = {
|
||||
onHmrUpdates: bindingOnHmrUpdates,
|
||||
onOutput: userOnOutput ? function(rawResult) {
|
||||
const result = normalizeBindingResult(rawResult);
|
||||
if (result instanceof Error) {
|
||||
userOnOutput(result);
|
||||
return;
|
||||
}
|
||||
userOnOutput(transformToRollupOutput(result));
|
||||
} : void 0,
|
||||
rebuildStrategy: devOptions.rebuildStrategy ? devOptions.rebuildStrategy === "always" ? import_binding.BindingRebuildStrategy.Always : devOptions.rebuildStrategy === "auto" ? import_binding.BindingRebuildStrategy.Auto : import_binding.BindingRebuildStrategy.Never : void 0,
|
||||
watch: devOptions.watch && {
|
||||
skipWrite: devOptions.watch.skipWrite,
|
||||
usePolling: devOptions.watch.usePolling,
|
||||
pollInterval: devOptions.watch.pollInterval,
|
||||
useDebounce: devOptions.watch.useDebounce,
|
||||
debounceDuration: devOptions.watch.debounceDuration,
|
||||
compareContentsForPolling: devOptions.watch.compareContentsForPolling,
|
||||
debounceTickRate: devOptions.watch.debounceTickRate
|
||||
}
|
||||
};
|
||||
return new DevEngine(new import_binding.BindingDevEngine(options.bundlerOptions, bindingDevOptions));
|
||||
}
|
||||
constructor(inner) {
|
||||
this.#inner = inner;
|
||||
}
|
||||
async run() {
|
||||
await this.#inner.run();
|
||||
}
|
||||
async ensureCurrentBuildFinish() {
|
||||
if (this.#cachedBuildFinishPromise) return this.#cachedBuildFinishPromise;
|
||||
const promise = this.#inner.ensureCurrentBuildFinish().then(() => {
|
||||
this.#cachedBuildFinishPromise = null;
|
||||
});
|
||||
this.#cachedBuildFinishPromise = promise;
|
||||
return promise;
|
||||
}
|
||||
async getBundleState() {
|
||||
return this.#inner.getBundleState();
|
||||
}
|
||||
async ensureLatestBuildOutput() {
|
||||
await this.#inner.ensureLatestBuildOutput();
|
||||
}
|
||||
async invalidate(file, firstInvalidatedBy) {
|
||||
return this.#inner.invalidate(file, firstInvalidatedBy);
|
||||
}
|
||||
async registerModules(clientId, modules) {
|
||||
await this.#inner.registerModules(clientId, modules);
|
||||
}
|
||||
async removeClient(clientId) {
|
||||
await this.#inner.removeClient(clientId);
|
||||
}
|
||||
async close() {
|
||||
await this.#inner.close();
|
||||
}
|
||||
/**
|
||||
* Compile a lazy entry module and return HMR-style patch code.
|
||||
*
|
||||
* This is called when a dynamically imported module is first requested at runtime.
|
||||
* The module was previously stubbed with a proxy, and now we need to compile the
|
||||
* actual module and its dependencies.
|
||||
*
|
||||
* @param moduleId - The absolute file path of the module to compile
|
||||
* @param clientId - The client ID requesting this compilation
|
||||
* @returns The compiled JavaScript code as a string (HMR patch format)
|
||||
*/
|
||||
async compileEntry(moduleId, clientId) {
|
||||
return this.#inner.compileEntry(moduleId, clientId);
|
||||
}
|
||||
};
|
||||
|
||||
//#endregion
|
||||
//#region src/api/dev/index.ts
|
||||
const dev = (...args) => DevEngine.create(...args);
|
||||
|
||||
//#endregion
|
||||
//#region src/types/external-memory-handle.ts
|
||||
const symbolForExternalMemoryHandle = "__rolldown_external_memory_handle__";
|
||||
/**
|
||||
* Frees the external memory held by the given handle.
|
||||
*
|
||||
* This is useful when you want to manually release memory held by Rust objects
|
||||
* (like `OutputChunk` or `OutputAsset`) before they are garbage collected.
|
||||
*
|
||||
* @param handle - The object with external memory to free
|
||||
* @param keepDataAlive - If true, evaluates all lazy fields before freeing memory (default: false).
|
||||
* This will take time to copy data from Rust to JavaScript, but prevents errors
|
||||
* when accessing properties after the memory is freed.
|
||||
* @returns Status object with `freed` boolean and optional `reason` string.
|
||||
* - `{ freed: true }` if memory was successfully freed
|
||||
* - `{ freed: false, reason: "..." }` if memory couldn't be freed (e.g., already freed or other references exist)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { freeExternalMemory } from 'rolldown/experimental';
|
||||
*
|
||||
* const output = await bundle.generate();
|
||||
* const chunk = output.output[0];
|
||||
*
|
||||
* // Use the chunk...
|
||||
*
|
||||
* // Manually free the memory (fast, but accessing properties after will throw)
|
||||
* const status = freeExternalMemory(chunk); // { freed: true }
|
||||
* const statusAgain = freeExternalMemory(chunk); // { freed: false, reason: "Memory has already been freed" }
|
||||
*
|
||||
* // Keep data alive before freeing (slower, but data remains accessible)
|
||||
* freeExternalMemory(chunk, true); // Evaluates all lazy fields first
|
||||
* console.log(chunk.code); // OK - data was copied to JavaScript before freeing
|
||||
*
|
||||
* // Without keepDataAlive, accessing chunk properties after freeing will throw an error
|
||||
* ```
|
||||
*/
|
||||
function freeExternalMemory(handle, keepDataAlive = false) {
|
||||
return handle[symbolForExternalMemoryHandle](keepDataAlive);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/api/experimental.ts
|
||||
/**
|
||||
* This is an experimental API. Its behavior may change in the future.
|
||||
*
|
||||
* - Calling this API will only execute the `scan/build` stage of rolldown.
|
||||
* - `scan` will clean up all resources automatically, but if you want to ensure timely cleanup, you need to wait for the returned promise to resolve.
|
||||
*
|
||||
* @example To ensure cleanup of resources, use the returned promise to wait for the scan to complete.
|
||||
* ```ts
|
||||
* import { scan } from 'rolldown/api/experimental';
|
||||
*
|
||||
* const cleanupPromise = await scan(...);
|
||||
* await cleanupPromise;
|
||||
* // Now all resources have been cleaned up.
|
||||
* ```
|
||||
*/
|
||||
const scan = async (rawInputOptions, rawOutputOptions = {}) => {
|
||||
validateOption("input", rawInputOptions);
|
||||
validateOption("output", rawOutputOptions);
|
||||
const ret = await createBundlerOptions(await PluginDriver.callOptionsHook(rawInputOptions), rawOutputOptions, false);
|
||||
const bundler = new import_binding.BindingBundler();
|
||||
if (RolldownBuild.asyncRuntimeShutdown) (0, import_binding.startAsyncRuntime)();
|
||||
async function cleanup() {
|
||||
await bundler.close();
|
||||
await ret.stopWorkers?.();
|
||||
(0, import_binding.shutdownAsyncRuntime)();
|
||||
RolldownBuild.asyncRuntimeShutdown = true;
|
||||
}
|
||||
let cleanupPromise = Promise.resolve();
|
||||
try {
|
||||
unwrapBindingResult(await bundler.scan(ret.bundlerOptions));
|
||||
} catch (err) {
|
||||
await cleanup();
|
||||
throw err;
|
||||
} finally {
|
||||
cleanupPromise = cleanup();
|
||||
}
|
||||
return cleanupPromise;
|
||||
};
|
||||
|
||||
//#endregion
|
||||
//#region src/plugin/parallel-plugin.ts
|
||||
function defineParallelPlugin(pluginPath) {
|
||||
return (options) => {
|
||||
return { _parallel: {
|
||||
fileUrl: pathToFileURL(pluginPath).href,
|
||||
options
|
||||
} };
|
||||
};
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/builtin-plugin/alias-plugin.ts
|
||||
function viteAliasPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-alias", config);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/builtin-plugin/bundle-analyzer-plugin.ts
|
||||
/**
|
||||
* A plugin that analyzes bundle composition and generates detailed reports.
|
||||
*
|
||||
* The plugin outputs a JSON file containing detailed information about:
|
||||
* - All chunks and their relationships
|
||||
* - Modules bundled in each chunk
|
||||
* - Import dependencies between chunks
|
||||
* - Reachable modules from each entry point
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
|
||||
*
|
||||
* export default {
|
||||
* plugins: [
|
||||
* bundleAnalyzerPlugin()
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* **Custom filename**
|
||||
* ```js
|
||||
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
|
||||
*
|
||||
* export default {
|
||||
* plugins: [
|
||||
* bundleAnalyzerPlugin({
|
||||
* fileName: 'bundle-analysis.json'
|
||||
* })
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
function bundleAnalyzerPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:bundle-analyzer", config);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/builtin-plugin/transform-plugin.ts
|
||||
function viteTransformPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-transform", {
|
||||
...config,
|
||||
include: normalizedStringOrRegex(config.include),
|
||||
exclude: normalizedStringOrRegex(config.exclude),
|
||||
jsxRefreshInclude: normalizedStringOrRegex(config.jsxRefreshInclude),
|
||||
jsxRefreshExclude: normalizedStringOrRegex(config.jsxRefreshExclude),
|
||||
yarnPnp: typeof process === "object" && !!process.versions?.pnp
|
||||
});
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/builtin-plugin/vite-manifest-plugin.ts
|
||||
function viteManifestPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-manifest", config);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/experimental-index.ts
|
||||
/**
|
||||
* In-memory file system for browser builds.
|
||||
*
|
||||
* This is a re-export of the {@link https://github.com/streamich/memfs | memfs} package used by the WASI runtime.
|
||||
* It allows you to read and write files to a virtual filesystem when using rolldown in browser environments.
|
||||
*
|
||||
* - `fs`: A Node.js-compatible filesystem API (`IFs` from memfs)
|
||||
* - `volume`: The underlying `Volume` instance that stores the filesystem state
|
||||
*
|
||||
* Returns `undefined` in Node.js builds (only available in browser builds via `@rolldown/browser`).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { memfs } from 'rolldown/experimental';
|
||||
*
|
||||
* // Write files to virtual filesystem before bundling
|
||||
* memfs?.volume.fromJSON({
|
||||
* '/src/index.js': 'export const foo = 42;',
|
||||
* '/package.json': '{"name": "my-app"}'
|
||||
* });
|
||||
*
|
||||
* // Read files from the virtual filesystem
|
||||
* const content = memfs?.fs.readFileSync('/src/index.js', 'utf8');
|
||||
* ```
|
||||
*
|
||||
* @see {@link https://github.com/streamich/memfs} for more information on the memfs API.
|
||||
*/
|
||||
const memfs = void 0;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
const parse = parse$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
const parseSync = parseSync$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
const minify = minify$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
const minifySync = minifySync$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
const transform = transform$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
const transformSync = transformSync$1;
|
||||
/** @deprecated Use from `rolldown/utils` instead. */
|
||||
const TsconfigCache = import_binding$1.TsconfigCache;
|
||||
|
||||
//#endregion
|
||||
var BindingRebuildStrategy = import_binding.BindingRebuildStrategy;
|
||||
var ResolverFactory = import_binding.ResolverFactory;
|
||||
var createTokioRuntime = import_binding.createTokioRuntime;
|
||||
var isolatedDeclaration = import_binding.isolatedDeclaration;
|
||||
var isolatedDeclarationSync = import_binding.isolatedDeclarationSync;
|
||||
var moduleRunnerTransform = import_binding.moduleRunnerTransform;
|
||||
var resolveTsconfig = import_binding.resolveTsconfig;
|
||||
export { BindingRebuildStrategy, DevEngine, ResolverFactory, TsconfigCache, bundleAnalyzerPlugin, createTokioRuntime, defineParallelPlugin, dev, viteDynamicImportVarsPlugin as dynamicImportVarsPlugin, viteDynamicImportVarsPlugin, freeExternalMemory, viteImportGlobPlugin as importGlobPlugin, viteImportGlobPlugin, isolatedDeclaration, isolatedDeclarationPlugin, isolatedDeclarationSync, memfs, minify, minifySync, moduleRunnerTransform, parse, parseSync, resolveTsconfig, scan, transform, transformSync, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReactRefreshWrapperPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWasmFallbackPlugin, viteWebWorkerPostPlugin };
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* @typedef {{ type: 'hmr:module-registered', modules: string[] }} DevRuntimeMessage
|
||||
* @typedef {{ send(message: DevRuntimeMessage): void }} Messenger
|
||||
*/
|
||||
export class DevRuntime {
|
||||
/**
|
||||
* @param {Messenger} messenger
|
||||
* @param {string} clientId
|
||||
*/
|
||||
constructor(messenger: Messenger, clientId: string);
|
||||
/**
|
||||
* Client ID generated at runtime initialization, used for lazy compilation requests.
|
||||
* @type {string}
|
||||
*/
|
||||
clientId: string;
|
||||
messenger: Messenger;
|
||||
/**
|
||||
* @type {Record<string, Module>}
|
||||
*/
|
||||
modules: Record<string, Module>;
|
||||
/**
|
||||
* @param {string} _moduleId
|
||||
*/
|
||||
createModuleHotContext(_moduleId: string): void;
|
||||
/**
|
||||
* @param {[string, string][]} _boundaries
|
||||
*/
|
||||
applyUpdates(_boundaries: [string, string][]): void;
|
||||
/**
|
||||
* @param {string} id
|
||||
* @param {{ exports: any }} exportsHolder
|
||||
*/
|
||||
registerModule(id: string, exportsHolder: {
|
||||
exports: any;
|
||||
}): void;
|
||||
/**
|
||||
* @param {string} id
|
||||
*/
|
||||
loadExports(id: string): any;
|
||||
/**
|
||||
* __esmMin
|
||||
*
|
||||
* @type {<T>(fn: any, res: T) => () => T}
|
||||
* @internal
|
||||
*/
|
||||
createEsmInitializer: <T>(fn: any, res: T) => () => T;
|
||||
/**
|
||||
* __commonJSMin
|
||||
*
|
||||
* @type {<T extends { exports: any }>(cb: any, mod: { exports: any }) => () => T}
|
||||
* @internal
|
||||
*/
|
||||
createCjsInitializer: <T extends {
|
||||
exports: any;
|
||||
}>(cb: any, mod: {
|
||||
exports: any;
|
||||
}) => () => T;
|
||||
/** @internal */
|
||||
__toESM: any;
|
||||
/** @internal */
|
||||
__toCommonJS: any;
|
||||
/** @internal */
|
||||
__exportAll: any;
|
||||
/**
|
||||
* @param {boolean} [isNodeMode]
|
||||
* @returns {(mod: any) => any}
|
||||
* @internal
|
||||
*/
|
||||
__toDynamicImportESM: (isNodeMode?: boolean) => (mod: any) => any;
|
||||
/** @internal */
|
||||
__reExport: any;
|
||||
sendModuleRegisteredMessage: (module: string) => void;
|
||||
}
|
||||
export type DevRuntimeMessage = {
|
||||
type: "hmr:module-registered";
|
||||
modules: string[];
|
||||
};
|
||||
export type Messenger = {
|
||||
send(message: DevRuntimeMessage): void;
|
||||
};
|
||||
declare class Module {
|
||||
/**
|
||||
* @param {string} id
|
||||
*/
|
||||
constructor(id: string);
|
||||
/**
|
||||
* @type {{ exports: any }}
|
||||
*/
|
||||
exportsHolder: {
|
||||
exports: any;
|
||||
};
|
||||
/**
|
||||
* @type {string}
|
||||
*/
|
||||
id: string;
|
||||
get exports(): any;
|
||||
}
|
||||
export {};
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
import "./shared/binding-BLUhc7Nl.mjs";
|
||||
import { j as withFilter } from "./shared/define-config-Cj8yDgkV.mjs";
|
||||
|
||||
//#region ../pluginutils/dist/filter/composable-filters.d.ts
|
||||
type StringOrRegExp = string | RegExp;
|
||||
type PluginModuleType = 'js' | 'jsx' | 'ts' | 'tsx' | 'json' | 'text' | 'base64' | 'dataurl' | 'binary' | 'empty' | (string & {});
|
||||
type FilterExpressionKind = FilterExpression['kind'];
|
||||
type FilterExpression = And | Or | Not | Id | ImporterId | ModuleType | Code | Query;
|
||||
type TopLevelFilterExpression = Include | Exclude;
|
||||
declare class And {
|
||||
kind: 'and';
|
||||
args: FilterExpression[];
|
||||
constructor(...args: FilterExpression[]);
|
||||
}
|
||||
declare class Or {
|
||||
kind: 'or';
|
||||
args: FilterExpression[];
|
||||
constructor(...args: FilterExpression[]);
|
||||
}
|
||||
declare class Not {
|
||||
kind: 'not';
|
||||
expr: FilterExpression;
|
||||
constructor(expr: FilterExpression);
|
||||
}
|
||||
interface QueryFilterObject {
|
||||
[key: string]: StringOrRegExp | boolean;
|
||||
}
|
||||
interface IdParams {
|
||||
cleanUrl?: boolean;
|
||||
}
|
||||
declare class Id {
|
||||
kind: 'id';
|
||||
pattern: StringOrRegExp;
|
||||
params: IdParams;
|
||||
constructor(pattern: StringOrRegExp, params?: IdParams);
|
||||
}
|
||||
declare class ImporterId {
|
||||
kind: 'importerId';
|
||||
pattern: StringOrRegExp;
|
||||
params: IdParams;
|
||||
constructor(pattern: StringOrRegExp, params?: IdParams);
|
||||
}
|
||||
declare class ModuleType {
|
||||
kind: 'moduleType';
|
||||
pattern: PluginModuleType;
|
||||
constructor(pattern: PluginModuleType);
|
||||
}
|
||||
declare class Code {
|
||||
kind: 'code';
|
||||
pattern: StringOrRegExp;
|
||||
constructor(expr: StringOrRegExp);
|
||||
}
|
||||
declare class Query {
|
||||
kind: 'query';
|
||||
key: string;
|
||||
pattern: StringOrRegExp | boolean;
|
||||
constructor(key: string, pattern: StringOrRegExp | boolean);
|
||||
}
|
||||
declare class Include {
|
||||
kind: 'include';
|
||||
expr: FilterExpression;
|
||||
constructor(expr: FilterExpression);
|
||||
}
|
||||
declare class Exclude {
|
||||
kind: 'exclude';
|
||||
expr: FilterExpression;
|
||||
constructor(expr: FilterExpression);
|
||||
}
|
||||
declare function and(...args: FilterExpression[]): And;
|
||||
declare function or(...args: FilterExpression[]): Or;
|
||||
declare function not(expr: FilterExpression): Not;
|
||||
declare function id(pattern: StringOrRegExp, params?: IdParams): Id;
|
||||
declare function importerId(pattern: StringOrRegExp, params?: IdParams): ImporterId;
|
||||
declare function moduleType(pattern: PluginModuleType): ModuleType;
|
||||
declare function code(pattern: StringOrRegExp): Code;
|
||||
declare function query(key: string, pattern: StringOrRegExp | boolean): Query;
|
||||
declare function include(expr: FilterExpression): Include;
|
||||
declare function exclude(expr: FilterExpression): Exclude;
|
||||
/**
|
||||
* convert a queryObject to FilterExpression like
|
||||
* ```js
|
||||
* and(query(k1, v1), query(k2, v2))
|
||||
* ```
|
||||
* @param queryFilterObject The query filter object needs to be matched.
|
||||
* @returns a `And` FilterExpression
|
||||
*/
|
||||
declare function queries(queryFilter: QueryFilterObject): And;
|
||||
declare function interpreter(exprs: TopLevelFilterExpression | TopLevelFilterExpression[], code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string): boolean;
|
||||
interface InterpreterCtx {
|
||||
urlSearchParamsCache?: URLSearchParams;
|
||||
}
|
||||
declare function interpreterImpl(expr: TopLevelFilterExpression[], code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string, ctx?: InterpreterCtx): boolean;
|
||||
declare function exprInterpreter(expr: FilterExpression, code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string, ctx?: InterpreterCtx): boolean;
|
||||
//#endregion
|
||||
//#region ../pluginutils/dist/filter/filter-vite-plugins.d.ts
|
||||
/**
|
||||
* Filters out Vite plugins that have `apply: 'serve'` set.
|
||||
*
|
||||
* Since Rolldown operates in build mode, plugins marked with `apply: 'serve'`
|
||||
* are intended only for Vite's dev server and should be excluded from the build process.
|
||||
*
|
||||
* @param plugins - Array of plugins (can include nested arrays)
|
||||
* @returns Filtered array with serve-only plugins removed
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { defineConfig } from 'rolldown';
|
||||
* import { filterVitePlugins } from '@rolldown/pluginutils';
|
||||
* import viteReact from '@vitejs/plugin-react';
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: filterVitePlugins([
|
||||
* viteReact(),
|
||||
* {
|
||||
* name: 'dev-only',
|
||||
* apply: 'serve', // This will be filtered out
|
||||
* // ...
|
||||
* }
|
||||
* ])
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
declare function filterVitePlugins<T = any>(plugins: T | T[] | null | undefined | false): T[];
|
||||
//#endregion
|
||||
//#region ../pluginutils/dist/filter/simple-filters.d.ts
|
||||
/**
|
||||
* Constructs a RegExp that matches the exact string specified.
|
||||
*
|
||||
* This is useful for plugin hook filters.
|
||||
*
|
||||
* @param str the string to match.
|
||||
* @param flags flags for the RegExp.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { exactRegex } from '@rolldown/pluginutils';
|
||||
* const plugin = {
|
||||
* name: 'plugin',
|
||||
* resolveId: {
|
||||
* filter: { id: exactRegex('foo') },
|
||||
* handler(id) {} // will only be called for `foo`
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
declare function exactRegex(str: string, flags?: string): RegExp;
|
||||
/**
|
||||
* Constructs a RegExp that matches a value that has the specified prefix.
|
||||
*
|
||||
* This is useful for plugin hook filters.
|
||||
*
|
||||
* @param str the string to match.
|
||||
* @param flags flags for the RegExp.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { prefixRegex } from '@rolldown/pluginutils';
|
||||
* const plugin = {
|
||||
* name: 'plugin',
|
||||
* resolveId: {
|
||||
* filter: { id: prefixRegex('foo') },
|
||||
* handler(id) {} // will only be called for IDs starting with `foo`
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
declare function prefixRegex(str: string, flags?: string): RegExp;
|
||||
type WidenString<T> = T extends string ? string : T;
|
||||
/**
|
||||
* Converts a id filter to match with an id with a query.
|
||||
*
|
||||
* @param input the id filters to convert.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { makeIdFiltersToMatchWithQuery } from '@rolldown/pluginutils';
|
||||
* const plugin = {
|
||||
* name: 'plugin',
|
||||
* transform: {
|
||||
* filter: { id: makeIdFiltersToMatchWithQuery(['**' + '/*.js', /\.ts$/]) },
|
||||
* // The handler will be called for IDs like:
|
||||
* // - foo.js
|
||||
* // - foo.js?foo
|
||||
* // - foo.txt?foo.js
|
||||
* // - foo.ts
|
||||
* // - foo.ts?foo
|
||||
* // - foo.txt?foo.ts
|
||||
* handler(code, id) {}
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
declare function makeIdFiltersToMatchWithQuery<T extends string | RegExp>(input: T): WidenString<T>;
|
||||
declare function makeIdFiltersToMatchWithQuery<T extends string | RegExp>(input: readonly T[]): WidenString<T>[];
|
||||
declare function makeIdFiltersToMatchWithQuery(input: string | RegExp | readonly (string | RegExp)[]): string | RegExp | (string | RegExp)[];
|
||||
//#endregion
|
||||
export { FilterExpression, FilterExpressionKind, QueryFilterObject, TopLevelFilterExpression, and, code, exactRegex, exclude, exprInterpreter, filterVitePlugins, id, importerId, include, interpreter, interpreterImpl, makeIdFiltersToMatchWithQuery, moduleType, not, or, prefixRegex, queries, query, withFilter };
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
import { n as isPromiseLike, t as arraify } from "./shared/misc-CCZIsXVO.mjs";
|
||||
|
||||
//#region ../pluginutils/dist/utils.js
|
||||
const postfixRE = /[?#].*$/;
|
||||
function cleanUrl(url) {
|
||||
return url.replace(postfixRE, "");
|
||||
}
|
||||
function extractQueryWithoutFragment(url) {
|
||||
const questionMarkIndex = url.indexOf("?");
|
||||
if (questionMarkIndex === -1) return "";
|
||||
const fragmentIndex = url.indexOf("#", questionMarkIndex);
|
||||
if (fragmentIndex === -1) return url.substring(questionMarkIndex);
|
||||
else return url.substring(questionMarkIndex, fragmentIndex);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region ../pluginutils/dist/filter/composable-filters.js
|
||||
var And = class {
|
||||
kind;
|
||||
args;
|
||||
constructor(...args) {
|
||||
if (args.length === 0) throw new Error("`And` expects at least one operand");
|
||||
this.args = args;
|
||||
this.kind = "and";
|
||||
}
|
||||
};
|
||||
var Or = class {
|
||||
kind;
|
||||
args;
|
||||
constructor(...args) {
|
||||
if (args.length === 0) throw new Error("`Or` expects at least one operand");
|
||||
this.args = args;
|
||||
this.kind = "or";
|
||||
}
|
||||
};
|
||||
var Not = class {
|
||||
kind;
|
||||
expr;
|
||||
constructor(expr) {
|
||||
this.expr = expr;
|
||||
this.kind = "not";
|
||||
}
|
||||
};
|
||||
var Id = class {
|
||||
kind;
|
||||
pattern;
|
||||
params;
|
||||
constructor(pattern, params) {
|
||||
this.pattern = pattern;
|
||||
this.kind = "id";
|
||||
this.params = params ?? { cleanUrl: false };
|
||||
}
|
||||
};
|
||||
var ImporterId = class {
|
||||
kind;
|
||||
pattern;
|
||||
params;
|
||||
constructor(pattern, params) {
|
||||
this.pattern = pattern;
|
||||
this.kind = "importerId";
|
||||
this.params = params ?? { cleanUrl: false };
|
||||
}
|
||||
};
|
||||
var ModuleType = class {
|
||||
kind;
|
||||
pattern;
|
||||
constructor(pattern) {
|
||||
this.pattern = pattern;
|
||||
this.kind = "moduleType";
|
||||
}
|
||||
};
|
||||
var Code = class {
|
||||
kind;
|
||||
pattern;
|
||||
constructor(expr) {
|
||||
this.pattern = expr;
|
||||
this.kind = "code";
|
||||
}
|
||||
};
|
||||
var Query = class {
|
||||
kind;
|
||||
key;
|
||||
pattern;
|
||||
constructor(key, pattern) {
|
||||
this.pattern = pattern;
|
||||
this.key = key;
|
||||
this.kind = "query";
|
||||
}
|
||||
};
|
||||
var Include = class {
|
||||
kind;
|
||||
expr;
|
||||
constructor(expr) {
|
||||
this.expr = expr;
|
||||
this.kind = "include";
|
||||
}
|
||||
};
|
||||
var Exclude = class {
|
||||
kind;
|
||||
expr;
|
||||
constructor(expr) {
|
||||
this.expr = expr;
|
||||
this.kind = "exclude";
|
||||
}
|
||||
};
|
||||
function and(...args) {
|
||||
return new And(...args);
|
||||
}
|
||||
function or(...args) {
|
||||
return new Or(...args);
|
||||
}
|
||||
function not(expr) {
|
||||
return new Not(expr);
|
||||
}
|
||||
function id(pattern, params) {
|
||||
return new Id(pattern, params);
|
||||
}
|
||||
function importerId(pattern, params) {
|
||||
return new ImporterId(pattern, params);
|
||||
}
|
||||
function moduleType(pattern) {
|
||||
return new ModuleType(pattern);
|
||||
}
|
||||
function code(pattern) {
|
||||
return new Code(pattern);
|
||||
}
|
||||
function query(key, pattern) {
|
||||
return new Query(key, pattern);
|
||||
}
|
||||
function include(expr) {
|
||||
return new Include(expr);
|
||||
}
|
||||
function exclude(expr) {
|
||||
return new Exclude(expr);
|
||||
}
|
||||
/**
|
||||
* convert a queryObject to FilterExpression like
|
||||
* ```js
|
||||
* and(query(k1, v1), query(k2, v2))
|
||||
* ```
|
||||
* @param queryFilterObject The query filter object needs to be matched.
|
||||
* @returns a `And` FilterExpression
|
||||
*/
|
||||
function queries(queryFilter) {
|
||||
return and(...Object.entries(queryFilter).map(([key, value]) => {
|
||||
return new Query(key, value);
|
||||
}));
|
||||
}
|
||||
function interpreter(exprs, code, id, moduleType, importerId) {
|
||||
let arr = [];
|
||||
if (Array.isArray(exprs)) arr = exprs;
|
||||
else arr = [exprs];
|
||||
return interpreterImpl(arr, code, id, moduleType, importerId);
|
||||
}
|
||||
function interpreterImpl(expr, code, id, moduleType, importerId, ctx = {}) {
|
||||
let hasInclude = false;
|
||||
for (const e of expr) switch (e.kind) {
|
||||
case "include":
|
||||
hasInclude = true;
|
||||
if (exprInterpreter(e.expr, code, id, moduleType, importerId, ctx)) return true;
|
||||
break;
|
||||
case "exclude":
|
||||
if (exprInterpreter(e.expr, code, id, moduleType, importerId, ctx)) return false;
|
||||
break;
|
||||
}
|
||||
return !hasInclude;
|
||||
}
|
||||
function exprInterpreter(expr, code, id, moduleType, importerId, ctx = {}) {
|
||||
switch (expr.kind) {
|
||||
case "and": return expr.args.every((e) => exprInterpreter(e, code, id, moduleType, importerId, ctx));
|
||||
case "or": return expr.args.some((e) => exprInterpreter(e, code, id, moduleType, importerId, ctx));
|
||||
case "not": return !exprInterpreter(expr.expr, code, id, moduleType, importerId, ctx);
|
||||
case "id": {
|
||||
if (id === void 0) throw new Error("`id` is required for `id` expression");
|
||||
let idToMatch = id;
|
||||
if (expr.params.cleanUrl) idToMatch = cleanUrl(idToMatch);
|
||||
return typeof expr.pattern === "string" ? idToMatch === expr.pattern : expr.pattern.test(idToMatch);
|
||||
}
|
||||
case "importerId": {
|
||||
if (importerId === void 0) return false;
|
||||
let importerIdToMatch = importerId;
|
||||
if (expr.params.cleanUrl) importerIdToMatch = cleanUrl(importerIdToMatch);
|
||||
return typeof expr.pattern === "string" ? importerIdToMatch === expr.pattern : expr.pattern.test(importerIdToMatch);
|
||||
}
|
||||
case "moduleType":
|
||||
if (moduleType === void 0) throw new Error("`moduleType` is required for `moduleType` expression");
|
||||
return moduleType === expr.pattern;
|
||||
case "code":
|
||||
if (code === void 0) throw new Error("`code` is required for `code` expression");
|
||||
return typeof expr.pattern === "string" ? code.includes(expr.pattern) : expr.pattern.test(code);
|
||||
case "query": {
|
||||
if (id === void 0) throw new Error("`id` is required for `Query` expression");
|
||||
if (!ctx.urlSearchParamsCache) {
|
||||
let queryString = extractQueryWithoutFragment(id);
|
||||
ctx.urlSearchParamsCache = new URLSearchParams(queryString);
|
||||
}
|
||||
let urlParams = ctx.urlSearchParamsCache;
|
||||
if (typeof expr.pattern === "boolean") if (expr.pattern) return urlParams.has(expr.key);
|
||||
else return !urlParams.has(expr.key);
|
||||
else if (typeof expr.pattern === "string") return urlParams.get(expr.key) === expr.pattern;
|
||||
else return expr.pattern.test(urlParams.get(expr.key) ?? "");
|
||||
}
|
||||
default: throw new Error(`Expression ${JSON.stringify(expr)} is not expected.`);
|
||||
}
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region ../pluginutils/dist/filter/filter-vite-plugins.js
|
||||
/**
|
||||
* Filters out Vite plugins that have `apply: 'serve'` set.
|
||||
*
|
||||
* Since Rolldown operates in build mode, plugins marked with `apply: 'serve'`
|
||||
* are intended only for Vite's dev server and should be excluded from the build process.
|
||||
*
|
||||
* @param plugins - Array of plugins (can include nested arrays)
|
||||
* @returns Filtered array with serve-only plugins removed
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { defineConfig } from 'rolldown';
|
||||
* import { filterVitePlugins } from '@rolldown/pluginutils';
|
||||
* import viteReact from '@vitejs/plugin-react';
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: filterVitePlugins([
|
||||
* viteReact(),
|
||||
* {
|
||||
* name: 'dev-only',
|
||||
* apply: 'serve', // This will be filtered out
|
||||
* // ...
|
||||
* }
|
||||
* ])
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
function filterVitePlugins(plugins) {
|
||||
if (!plugins) return [];
|
||||
const pluginArray = Array.isArray(plugins) ? plugins : [plugins];
|
||||
const result = [];
|
||||
for (const plugin of pluginArray) {
|
||||
if (!plugin) continue;
|
||||
if (Array.isArray(plugin)) {
|
||||
result.push(...filterVitePlugins(plugin));
|
||||
continue;
|
||||
}
|
||||
const pluginWithApply = plugin;
|
||||
if ("apply" in pluginWithApply) {
|
||||
const applyValue = pluginWithApply.apply;
|
||||
if (typeof applyValue === "function") try {
|
||||
if (applyValue({}, {
|
||||
command: "build",
|
||||
mode: "production"
|
||||
})) result.push(plugin);
|
||||
} catch {
|
||||
result.push(plugin);
|
||||
}
|
||||
else if (applyValue === "serve") continue;
|
||||
else result.push(plugin);
|
||||
} else result.push(plugin);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region ../pluginutils/dist/filter/simple-filters.js
|
||||
/**
|
||||
* Constructs a RegExp that matches the exact string specified.
|
||||
*
|
||||
* This is useful for plugin hook filters.
|
||||
*
|
||||
* @param str the string to match.
|
||||
* @param flags flags for the RegExp.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { exactRegex } from '@rolldown/pluginutils';
|
||||
* const plugin = {
|
||||
* name: 'plugin',
|
||||
* resolveId: {
|
||||
* filter: { id: exactRegex('foo') },
|
||||
* handler(id) {} // will only be called for `foo`
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
function exactRegex(str, flags) {
|
||||
return new RegExp(`^${escapeRegex(str)}$`, flags);
|
||||
}
|
||||
/**
|
||||
* Constructs a RegExp that matches a value that has the specified prefix.
|
||||
*
|
||||
* This is useful for plugin hook filters.
|
||||
*
|
||||
* @param str the string to match.
|
||||
* @param flags flags for the RegExp.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { prefixRegex } from '@rolldown/pluginutils';
|
||||
* const plugin = {
|
||||
* name: 'plugin',
|
||||
* resolveId: {
|
||||
* filter: { id: prefixRegex('foo') },
|
||||
* handler(id) {} // will only be called for IDs starting with `foo`
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
function prefixRegex(str, flags) {
|
||||
return new RegExp(`^${escapeRegex(str)}`, flags);
|
||||
}
|
||||
const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
|
||||
function escapeRegex(str) {
|
||||
return str.replace(escapeRegexRE, "\\$&");
|
||||
}
|
||||
function makeIdFiltersToMatchWithQuery(input) {
|
||||
if (!Array.isArray(input)) return makeIdFilterToMatchWithQuery(input);
|
||||
return input.map((i) => makeIdFilterToMatchWithQuery(i));
|
||||
}
|
||||
function makeIdFilterToMatchWithQuery(input) {
|
||||
if (typeof input === "string") return `${input}{?*,}`;
|
||||
return makeRegexIdFilterToMatchWithQuery(input);
|
||||
}
|
||||
function makeRegexIdFilterToMatchWithQuery(input) {
|
||||
return new RegExp(input.source.replace(/(?<!\\)\$/g, "(?:\\?.*)?$"), input.flags);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/plugin/with-filter.ts
|
||||
function withFilterImpl(pluginOption, filterObjectList) {
|
||||
if (isPromiseLike(pluginOption)) return pluginOption.then((p) => withFilter(p, filterObjectList));
|
||||
if (pluginOption == false || pluginOption == null) return pluginOption;
|
||||
if (Array.isArray(pluginOption)) return pluginOption.map((p) => withFilter(p, filterObjectList));
|
||||
let plugin = pluginOption;
|
||||
let filterObjectIndex = findMatchedFilterObject(plugin.name, filterObjectList);
|
||||
if (filterObjectIndex === -1) return plugin;
|
||||
let filterObject = filterObjectList[filterObjectIndex];
|
||||
Object.keys(plugin).forEach((key) => {
|
||||
switch (key) {
|
||||
case "transform":
|
||||
case "resolveId":
|
||||
case "load":
|
||||
if (!plugin[key]) return;
|
||||
if (typeof plugin[key] === "object") plugin[key].filter = filterObject[key] ?? plugin[key].filter;
|
||||
else plugin[key] = {
|
||||
handler: plugin[key],
|
||||
filter: filterObject[key]
|
||||
};
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
});
|
||||
return plugin;
|
||||
}
|
||||
function withFilter(pluginOption, filterObject) {
|
||||
return withFilterImpl(pluginOption, arraify(filterObject));
|
||||
}
|
||||
function findMatchedFilterObject(pluginName, overrideFilterObjectList) {
|
||||
if (overrideFilterObjectList.length === 1 && overrideFilterObjectList[0].pluginNamePattern === void 0) return 0;
|
||||
for (let i = 0; i < overrideFilterObjectList.length; i++) for (let j = 0; j < (overrideFilterObjectList[i].pluginNamePattern ?? []).length; j++) {
|
||||
let pattern = overrideFilterObjectList[i].pluginNamePattern[j];
|
||||
if (typeof pattern === "string" && pattern === pluginName) return i;
|
||||
else if (pattern instanceof RegExp && pattern.test(pluginName)) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { and, code, exactRegex, exclude, exprInterpreter, filterVitePlugins, id, importerId, include, interpreter, interpreterImpl, makeIdFiltersToMatchWithQuery, moduleType, not, or, prefixRegex, queries, query, withFilter };
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { a as RolldownLog } from "./shared/logging-CKYae7lu.mjs";
|
||||
|
||||
//#region src/get-log-filter.d.ts
|
||||
type GetLogFilter = (filters: string[]) => (log: RolldownLog) => boolean;
|
||||
declare const getLogFilter: GetLogFilter;
|
||||
//#endregion
|
||||
export { GetLogFilter, type RolldownLog, type RolldownLog as RollupLog, getLogFilter as default };
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
//#region src/get-log-filter.ts
|
||||
const getLogFilter = (filters) => {
|
||||
if (filters.length === 0) return () => true;
|
||||
const normalizedFilters = filters.map((filter) => filter.split("&").map((subFilter) => {
|
||||
const inverted = subFilter.startsWith("!");
|
||||
if (inverted) subFilter = subFilter.slice(1);
|
||||
const [key, ...value] = subFilter.split(":");
|
||||
return {
|
||||
inverted,
|
||||
key: key.split("."),
|
||||
parts: value.join(":").split("*")
|
||||
};
|
||||
}));
|
||||
return (log) => {
|
||||
nextIntersectedFilter: for (const intersectedFilters of normalizedFilters) {
|
||||
for (const { inverted, key, parts } of intersectedFilters) {
|
||||
const isFilterSatisfied = testFilter(log, key, parts);
|
||||
if (inverted ? isFilterSatisfied : !isFilterSatisfied) continue nextIntersectedFilter;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
};
|
||||
const testFilter = (log, key, parts) => {
|
||||
let rawValue = log;
|
||||
for (let index = 0; index < key.length; index++) {
|
||||
if (!rawValue) return false;
|
||||
const part = key[index];
|
||||
if (!(part in rawValue)) return false;
|
||||
rawValue = rawValue[part];
|
||||
}
|
||||
let value = typeof rawValue === "object" ? JSON.stringify(rawValue) : String(rawValue);
|
||||
if (parts.length === 1) return value === parts[0];
|
||||
if (!value.startsWith(parts[0])) return false;
|
||||
const lastPartIndex = parts.length - 1;
|
||||
for (let index = 1; index < lastPartIndex; index++) {
|
||||
const part = parts[index];
|
||||
const position = value.indexOf(part);
|
||||
if (position === -1) return false;
|
||||
value = value.slice(position + part.length);
|
||||
}
|
||||
return value.endsWith(parts[lastPartIndex]);
|
||||
};
|
||||
|
||||
//#endregion
|
||||
export { getLogFilter as default };
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { a as RolldownLog, i as RolldownError, n as LogLevelOption, o as RolldownLogWithString, r as LogOrStringHandler, t as LogLevel } from "./shared/logging-CKYae7lu.mjs";
|
||||
import { R as PreRenderedChunk, u as BindingMagicString } from "./shared/binding-BLUhc7Nl.mjs";
|
||||
import { $ as ModuleTypeFilter, A as TransformResult, At as GeneratedCodePreset, B as EmittedAsset, Bt as OutputChunk, C as Plugin, Ct as ChunkFileNamesFunction, D as RolldownPlugin, Dt as CodeSplittingOptions, E as ResolvedId, Et as CodeSplittingNameFunction, F as ExistingRawSourceMap, Ft as PreRenderedAsset, G as PluginContext, H as EmittedFile, Ht as RenderedModule, I as SourceMapInput, K as PluginContextResolveOptions, Kt as ModuleInfo, L as OutputBundle, Lt as PartialNull, Mt as MinifyOptions, N as RUNTIME_MODULE_ID, Nt as ModuleFormat, O as RolldownPluginOption, Ot as CommentsOptions, P as VERSION, Pt as OutputOptions, Q as HookFilter, R as TreeshakingOptions, S as PartialResolvedId, St as AdvancedChunksOptions, T as ResolveIdResult, Tt as CodeSplittingGroup, U as EmittedPrebuiltChunk, Ut as RolldownOutput, V as EmittedChunk, Vt as RenderedChunk, W as GetModuleInfo, Wt as SourceMap, X as PluginContextMeta, Y as MinimalPluginContext, Z as GeneralHookFilter, _ as LoadResult, _t as RolldownBuild, a as ExternalOption, at as NormalizedOutputOptions, b as ObjectHook, bt as AddonFunction, c as InputOptions, ct as ChecksOptions, d as WatcherOptions, dt as watch, et as BufferEncoding, f as AsyncPluginHooks, ft as RolldownWatcher, g as ImportKind, gt as rolldown, h as HookFilterExtension, ht as WatchOptions, i as RolldownOptions, it as InternalModuleFormat, jt as GlobalsFunction, k as SourceDescription, kt as GeneratedCodeOptions, l as ModuleTypes, lt as LoggingFunction, m as FunctionPluginHooks, mt as RolldownWatcherWatcherEventMap, n as RolldownOptionsFunction, nt as RolldownFileStats, o as ExternalOptionFunction, ot as NormalizedInputOptions, p as CustomPluginOptions, pt as RolldownWatcherEvent, q as DefineParallelPluginResult, qt as SourcemapIgnoreListOption, r as defineConfig, rt as RolldownFsModule, s as InputOption, st as TransformOptions, t as ConfigExport, tt as RolldownDirectoryEntry, u as OptimizationOptions, ut as WarningHandlerWithDefault, v as ModuleOptions, vt as BuildOptions, w as ResolveIdExtraOptions, wt as ChunkingContext, x as ParallelPluginHooks, xt as AdvancedChunksGroup, y as ModuleType, yt as build, z as TransformPluginContext, zt as OutputAsset } from "./shared/define-config-Cj8yDgkV.mjs";
|
||||
export { type AddonFunction, type AdvancedChunksGroup, type AdvancedChunksOptions, type AsyncPluginHooks, BindingMagicString, type BufferEncoding, type BuildOptions, type ChecksOptions, type ChunkFileNamesFunction, type ChunkingContext, type CodeSplittingGroup, type CodeSplittingNameFunction, type CodeSplittingOptions, type CommentsOptions, type ConfigExport, type CustomPluginOptions, type DefineParallelPluginResult, type EmittedAsset, type EmittedChunk, type EmittedFile, type EmittedPrebuiltChunk, type ExistingRawSourceMap, type ExternalOption, type ExternalOptionFunction, type FunctionPluginHooks, type GeneralHookFilter, type GeneratedCodeOptions, type GeneratedCodePreset, type GetModuleInfo, type GlobalsFunction, type HookFilter, type HookFilterExtension, type ImportKind, type InputOption, type InputOptions, type InternalModuleFormat, type LoadResult, type LogLevel, type LogLevelOption, type LogOrStringHandler, type LoggingFunction, type MinifyOptions, type MinimalPluginContext, type ModuleFormat, type ModuleInfo, type ModuleOptions, type ModuleType, type ModuleTypeFilter, type ModuleTypes, type NormalizedInputOptions, type NormalizedOutputOptions, type ObjectHook, type OptimizationOptions, type OutputAsset, type OutputBundle, type OutputChunk, type OutputOptions, type ParallelPluginHooks, type PartialNull, type PartialResolvedId, type Plugin, type PluginContext, type PluginContextMeta, type PluginContextResolveOptions, type PreRenderedAsset, type PreRenderedChunk, RUNTIME_MODULE_ID, type RenderedChunk, type RenderedModule, type ResolveIdExtraOptions, type ResolveIdResult, type ResolvedId, type RolldownBuild, type RolldownDirectoryEntry, type RolldownError, type RolldownError as RollupError, type RolldownFileStats, type RolldownFsModule, type RolldownLog, type RolldownLog as RollupLog, type RolldownLogWithString, type RolldownLogWithString as RollupLogWithString, type RolldownOptions, type RolldownOptionsFunction, type RolldownOutput, type RolldownPlugin, type RolldownPluginOption, type RolldownWatcher, type RolldownWatcherEvent, type RolldownWatcherWatcherEventMap, type SourceDescription, type SourceMap, type SourceMapInput, type SourcemapIgnoreListOption, type TransformOptions, type TransformPluginContext, type TransformResult, type TreeshakingOptions, VERSION, type WarningHandlerWithDefault, type WatchOptions, type WatcherOptions, build, defineConfig, rolldown, watch };
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { n as __toESM, t as require_binding } from "./shared/binding-DzKFaUu2.mjs";
|
||||
import { n as onExit, t as watch } from "./shared/watch-CgVvtyIH.mjs";
|
||||
import "./shared/normalize-string-or-regex-0P4NpnRa.mjs";
|
||||
import { b as VERSION, y as RUNTIME_MODULE_ID } from "./shared/bindingify-input-options-phmnMdxa.mjs";
|
||||
import "./shared/rolldown-build-CjERPB8v.mjs";
|
||||
import "./shared/error-DC8XkJKP.mjs";
|
||||
import "./shared/parse-DIfx5aEh.mjs";
|
||||
import { t as rolldown } from "./shared/rolldown-6S97x4m9.mjs";
|
||||
import { t as defineConfig } from "./shared/define-config-B-Hn45NS.mjs";
|
||||
import { isMainThread } from "node:worker_threads";
|
||||
|
||||
//#region src/setup.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
if (isMainThread) {
|
||||
const subscriberGuard = (0, import_binding.initTraceSubscriber)();
|
||||
onExit(() => {
|
||||
subscriberGuard?.close();
|
||||
});
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/api/build.ts
|
||||
/**
|
||||
* The API similar to esbuild's `build` function.
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { build } from 'rolldown';
|
||||
*
|
||||
* const result = await build({
|
||||
* input: 'src/main.js',
|
||||
* output: {
|
||||
* file: 'bundle.js',
|
||||
* },
|
||||
* });
|
||||
* console.log(result);
|
||||
* ```
|
||||
*
|
||||
* @experimental
|
||||
* @category Programmatic APIs
|
||||
*/
|
||||
async function build(options) {
|
||||
if (Array.isArray(options)) return Promise.all(options.map((opts) => build(opts)));
|
||||
else {
|
||||
const { output, write = true, ...inputOptions } = options;
|
||||
const build = await rolldown(inputOptions);
|
||||
try {
|
||||
if (write) return await build.write(output);
|
||||
else return await build.generate(output);
|
||||
} finally {
|
||||
await build.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//#endregion
|
||||
var BindingMagicString = import_binding.BindingMagicString;
|
||||
export { BindingMagicString, RUNTIME_MODULE_ID, VERSION, build, defineConfig, rolldown, watch };
|
||||
+1
@@ -0,0 +1 @@
|
||||
export { };
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { n as __toESM, t as require_binding } from "./shared/binding-DzKFaUu2.mjs";
|
||||
import "./shared/normalize-string-or-regex-0P4NpnRa.mjs";
|
||||
import { n as PluginContextData, r as bindingifyPlugin } from "./shared/bindingify-input-options-phmnMdxa.mjs";
|
||||
import "./shared/error-DC8XkJKP.mjs";
|
||||
import "./shared/parse-DIfx5aEh.mjs";
|
||||
import { parentPort, workerData } from "node:worker_threads";
|
||||
|
||||
//#region src/parallel-plugin-worker.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
const { registryId, pluginInfos, threadNumber } = workerData;
|
||||
(async () => {
|
||||
try {
|
||||
(0, import_binding.registerPlugins)(registryId, await Promise.all(pluginInfos.map(async (pluginInfo) => {
|
||||
const definePluginImpl = (await import(pluginInfo.fileUrl)).default;
|
||||
const plugin = await definePluginImpl(pluginInfo.options, { threadNumber });
|
||||
return {
|
||||
index: pluginInfo.index,
|
||||
plugin: bindingifyPlugin(plugin, {}, {}, new PluginContextData(() => {}, {}, []), [], () => {}, "info", false)
|
||||
};
|
||||
})));
|
||||
parentPort.postMessage({ type: "success" });
|
||||
} catch (error) {
|
||||
parentPort.postMessage({
|
||||
type: "error",
|
||||
error
|
||||
});
|
||||
} finally {
|
||||
parentPort.unref();
|
||||
}
|
||||
})();
|
||||
|
||||
//#endregion
|
||||
export { };
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import "./shared/binding-BLUhc7Nl.mjs";
|
||||
import { C as Plugin, It as MaybePromise } from "./shared/define-config-Cj8yDgkV.mjs";
|
||||
|
||||
//#region src/plugin/parallel-plugin-implementation.d.ts
|
||||
type ParallelPluginImplementation = Plugin;
|
||||
type Context = {
|
||||
/**
|
||||
* Thread number
|
||||
*/
|
||||
threadNumber: number;
|
||||
};
|
||||
declare function defineParallelPluginImplementation<Options>(plugin: (Options: Options, context: Context) => MaybePromise<ParallelPluginImplementation>): (Options: Options, context: Context) => MaybePromise<ParallelPluginImplementation>;
|
||||
//#endregion
|
||||
export { type Context, type ParallelPluginImplementation, defineParallelPluginImplementation };
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
//#region src/plugin/parallel-plugin-implementation.ts
|
||||
function defineParallelPluginImplementation(plugin) {
|
||||
return plugin;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { defineParallelPluginImplementation };
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { I as ParseResult, L as ParserOptions } from "./shared/binding-BLUhc7Nl.mjs";
|
||||
import { Program } from "@oxc-project/types";
|
||||
|
||||
//#region src/parse-ast-index.d.ts
|
||||
declare function parseAst(sourceText: string, options?: ParserOptions | null, filename?: string): Program;
|
||||
declare function parseAstAsync(sourceText: string, options?: ParserOptions | null, filename?: string): Promise<Program>;
|
||||
//#endregion
|
||||
export { type ParseResult, type ParserOptions, parseAst, parseAstAsync };
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import "./shared/binding-DzKFaUu2.mjs";
|
||||
import { l as locate, n as error, s as logParseError, t as augmentCodeLocation, u as getCodeFrame } from "./shared/logs-COHDsWqD.mjs";
|
||||
import { n as parseSync, t as parse } from "./shared/parse-DIfx5aEh.mjs";
|
||||
|
||||
//#region src/parse-ast-index.ts
|
||||
function wrap(result, filename, sourceText) {
|
||||
if (result.errors.length > 0) return normalizeParseError(filename, sourceText, result.errors);
|
||||
return result.program;
|
||||
}
|
||||
function normalizeParseError(filename, sourceText, errors) {
|
||||
let message = `Parse failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
|
||||
const pos = errors[0]?.labels?.[0]?.start;
|
||||
for (let i = 0; i < errors.length; i++) {
|
||||
if (i >= 5) {
|
||||
message += "\n...";
|
||||
break;
|
||||
}
|
||||
const e = errors[i];
|
||||
message += e.message + "\n" + e.labels.map((label) => {
|
||||
const location = locate(sourceText, label.start, { offsetLine: 1 });
|
||||
if (!location) return;
|
||||
return getCodeFrame(sourceText, location.line, location.column);
|
||||
}).filter(Boolean).join("\n");
|
||||
}
|
||||
const log = logParseError(message, filename, pos);
|
||||
if (pos !== void 0 && filename) augmentCodeLocation(log, pos, sourceText, filename);
|
||||
return error(log);
|
||||
}
|
||||
const defaultParserOptions = {
|
||||
lang: "js",
|
||||
preserveParens: false
|
||||
};
|
||||
function parseAst(sourceText, options, filename) {
|
||||
return wrap(parseSync(filename ?? "file.js", sourceText, {
|
||||
...defaultParserOptions,
|
||||
...options
|
||||
}), filename, sourceText);
|
||||
}
|
||||
async function parseAstAsync(sourceText, options, filename) {
|
||||
return wrap(await parse(filename ?? "file.js", sourceText, {
|
||||
...defaultParserOptions,
|
||||
...options
|
||||
}), filename, sourceText);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { parseAst, parseAstAsync };
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { m as BindingReplacePluginConfig } from "./shared/binding-BLUhc7Nl.mjs";
|
||||
import { M as BuiltinPlugin } from "./shared/define-config-Cj8yDgkV.mjs";
|
||||
import { t as esmExternalRequirePlugin } from "./shared/constructors-DIU14v_Z.mjs";
|
||||
|
||||
//#region src/builtin-plugin/replace-plugin.d.ts
|
||||
/**
|
||||
* Replaces targeted strings in files while bundling.
|
||||
*
|
||||
* @example
|
||||
* // Basic usage
|
||||
* ```js
|
||||
* replacePlugin({
|
||||
* 'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
* __buildVersion: 15
|
||||
* })
|
||||
* ```
|
||||
* @example
|
||||
* // With options
|
||||
* ```js
|
||||
* replacePlugin({
|
||||
* 'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
* __buildVersion: 15
|
||||
* }, {
|
||||
* preventAssignment: false,
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
declare function replacePlugin(values?: BindingReplacePluginConfig["values"], options?: Omit<BindingReplacePluginConfig, "values">): BuiltinPlugin;
|
||||
//#endregion
|
||||
export { esmExternalRequirePlugin, replacePlugin };
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import "./shared/binding-DzKFaUu2.mjs";
|
||||
import { a as makeBuiltinPluginCallable, n as BuiltinPlugin } from "./shared/normalize-string-or-regex-0P4NpnRa.mjs";
|
||||
import { t as esmExternalRequirePlugin } from "./shared/constructors-CfBLTWqY.mjs";
|
||||
|
||||
//#region src/builtin-plugin/replace-plugin.ts
|
||||
/**
|
||||
* Replaces targeted strings in files while bundling.
|
||||
*
|
||||
* @example
|
||||
* // Basic usage
|
||||
* ```js
|
||||
* replacePlugin({
|
||||
* 'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
* __buildVersion: 15
|
||||
* })
|
||||
* ```
|
||||
* @example
|
||||
* // With options
|
||||
* ```js
|
||||
* replacePlugin({
|
||||
* 'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
* __buildVersion: 15
|
||||
* }, {
|
||||
* preventAssignment: false,
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
function replacePlugin(values = {}, options = {}) {
|
||||
Object.keys(values).forEach((key) => {
|
||||
const value = values[key];
|
||||
if (typeof value !== "string") values[key] = String(value);
|
||||
});
|
||||
return makeBuiltinPluginCallable(new BuiltinPlugin("builtin:replace", {
|
||||
...options,
|
||||
values
|
||||
}));
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { esmExternalRequirePlugin, replacePlugin };
|
||||
+1817
File diff suppressed because it is too large
Load Diff
+591
@@ -0,0 +1,591 @@
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
//#region \0rolldown/runtime.js
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
||||
key = keys[i];
|
||||
if (!__hasOwnProp.call(to, key) && key !== except) {
|
||||
__defProp(to, key, {
|
||||
get: ((k) => from[k]).bind(null, key),
|
||||
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
||||
value: mod,
|
||||
enumerable: true
|
||||
}) : target, mod));
|
||||
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
||||
|
||||
//#endregion
|
||||
//#region src/webcontainer-fallback.cjs
|
||||
var require_webcontainer_fallback = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
||||
const fs = __require("node:fs");
|
||||
const childProcess = __require("node:child_process");
|
||||
const version = JSON.parse(fs.readFileSync(__require.resolve("rolldown/package.json"), "utf-8")).version;
|
||||
const baseDir = `/tmp/rolldown-${version}`;
|
||||
const bindingEntry = `${baseDir}/node_modules/@rolldown/binding-wasm32-wasi/rolldown-binding.wasi.cjs`;
|
||||
if (!fs.existsSync(bindingEntry)) {
|
||||
const bindingPkg = `@rolldown/binding-wasm32-wasi@${version}`;
|
||||
fs.rmSync(baseDir, {
|
||||
recursive: true,
|
||||
force: true
|
||||
});
|
||||
fs.mkdirSync(baseDir, { recursive: true });
|
||||
console.log(`[rolldown] Downloading ${bindingPkg} on WebContainer...`);
|
||||
childProcess.execFileSync("pnpm", ["i", bindingPkg], {
|
||||
cwd: baseDir,
|
||||
stdio: "inherit"
|
||||
});
|
||||
}
|
||||
module.exports = __require(bindingEntry);
|
||||
}));
|
||||
|
||||
//#endregion
|
||||
//#region src/binding.cjs
|
||||
var require_binding = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
||||
const { readFileSync } = __require("node:fs");
|
||||
let nativeBinding = null;
|
||||
const loadErrors = [];
|
||||
const isMusl = () => {
|
||||
let musl = false;
|
||||
if (process.platform === "linux") {
|
||||
musl = isMuslFromFilesystem();
|
||||
if (musl === null) musl = isMuslFromReport();
|
||||
if (musl === null) musl = isMuslFromChildProcess();
|
||||
}
|
||||
return musl;
|
||||
};
|
||||
const isFileMusl = (f) => f.includes("libc.musl-") || f.includes("ld-musl-");
|
||||
const isMuslFromFilesystem = () => {
|
||||
try {
|
||||
return readFileSync("/usr/bin/ldd", "utf-8").includes("musl");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const isMuslFromReport = () => {
|
||||
let report = null;
|
||||
if (typeof process.report?.getReport === "function") {
|
||||
process.report.excludeNetwork = true;
|
||||
report = process.report.getReport();
|
||||
}
|
||||
if (!report) return null;
|
||||
if (report.header && report.header.glibcVersionRuntime) return false;
|
||||
if (Array.isArray(report.sharedObjects)) {
|
||||
if (report.sharedObjects.some(isFileMusl)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const isMuslFromChildProcess = () => {
|
||||
try {
|
||||
return __require("child_process").execSync("ldd --version", { encoding: "utf8" }).includes("musl");
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
function requireNative() {
|
||||
if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) try {
|
||||
return __require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH);
|
||||
} catch (err) {
|
||||
loadErrors.push(err);
|
||||
}
|
||||
else if (process.platform === "android") if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.android-arm64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-android-arm64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-android-arm64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm") {
|
||||
try {
|
||||
return __require("./rolldown-binding.android-arm-eabi.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-android-arm-eabi");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-android-arm-eabi/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Android ${process.arch}`));
|
||||
else if (process.platform === "win32") if (process.arch === "x64") if (process.config?.variables?.shlib_suffix === "dll.a" || process.config?.variables?.node_target_type === "shared_library") {
|
||||
try {
|
||||
return __require("./rolldown-binding.win32-x64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-win32-x64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-win32-x64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.win32-x64-msvc.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-win32-x64-msvc");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-win32-x64-msvc/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
else if (process.arch === "ia32") {
|
||||
try {
|
||||
return __require("./rolldown-binding.win32-ia32-msvc.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-win32-ia32-msvc");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-win32-ia32-msvc/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.win32-arm64-msvc.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-win32-arm64-msvc");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-win32-arm64-msvc/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Windows: ${process.arch}`));
|
||||
else if (process.platform === "darwin") {
|
||||
try {
|
||||
return __require("./rolldown-binding.darwin-universal.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-darwin-universal");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-darwin-universal/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
if (process.arch === "x64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.darwin-x64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-darwin-x64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-darwin-x64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.darwin-arm64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-darwin-arm64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-darwin-arm64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on macOS: ${process.arch}`));
|
||||
} else if (process.platform === "freebsd") if (process.arch === "x64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.freebsd-x64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-freebsd-x64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-freebsd-x64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.freebsd-arm64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-freebsd-arm64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-freebsd-arm64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on FreeBSD: ${process.arch}`));
|
||||
else if (process.platform === "linux") if (process.arch === "x64") if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-x64-musl.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-x64-musl");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-x64-musl/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("../rolldown-binding.linux-x64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-x64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-x64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
else if (process.arch === "arm64") if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-arm64-musl.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-arm64-musl");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-arm64-musl/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-arm64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-arm64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-arm64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
else if (process.arch === "arm") if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-arm-musleabihf.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-arm-musleabihf");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-arm-musleabihf/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-arm-gnueabihf.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-arm-gnueabihf");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-arm-gnueabihf/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
else if (process.arch === "loong64") if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-loong64-musl.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-loong64-musl");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-loong64-musl/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-loong64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-loong64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-loong64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
else if (process.arch === "riscv64") if (isMusl()) {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-riscv64-musl.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-riscv64-musl");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-riscv64-musl/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-riscv64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-riscv64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-riscv64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
}
|
||||
else if (process.arch === "ppc64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-ppc64-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-ppc64-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-ppc64-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "s390x") {
|
||||
try {
|
||||
return __require("./rolldown-binding.linux-s390x-gnu.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-linux-s390x-gnu");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-linux-s390x-gnu/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on Linux: ${process.arch}`));
|
||||
else if (process.platform === "openharmony") if (process.arch === "arm64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.openharmony-arm64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-openharmony-arm64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-openharmony-arm64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "x64") {
|
||||
try {
|
||||
return __require("./rolldown-binding.openharmony-x64.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-openharmony-x64");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-openharmony-x64/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else if (process.arch === "arm") {
|
||||
try {
|
||||
return __require("./rolldown-binding.openharmony-arm.node");
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
try {
|
||||
const binding = __require("@rolldown/binding-openharmony-arm");
|
||||
const bindingPackageVersion = __require("@rolldown/binding-openharmony-arm/package.json").version;
|
||||
if (bindingPackageVersion !== "1.0.0-rc.4" && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== "0") throw new Error(`Native binding package version mismatch, expected 1.0.0-rc.4 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`);
|
||||
return binding;
|
||||
} catch (e) {
|
||||
loadErrors.push(e);
|
||||
}
|
||||
} else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`));
|
||||
else loadErrors.push(/* @__PURE__ */ new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`));
|
||||
}
|
||||
nativeBinding = requireNative();
|
||||
if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) {
|
||||
let wasiBinding = null;
|
||||
let wasiBindingError = null;
|
||||
try {
|
||||
wasiBinding = __require("../rolldown-binding.wasi.cjs");
|
||||
nativeBinding = wasiBinding;
|
||||
} catch (err) {
|
||||
if (process.env.NAPI_RS_FORCE_WASI) wasiBindingError = err;
|
||||
}
|
||||
if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) try {
|
||||
wasiBinding = __require("@rolldown/binding-wasm32-wasi");
|
||||
nativeBinding = wasiBinding;
|
||||
} catch (err) {
|
||||
if (process.env.NAPI_RS_FORCE_WASI) {
|
||||
if (!wasiBindingError) wasiBindingError = err;
|
||||
else wasiBindingError.cause = err;
|
||||
loadErrors.push(err);
|
||||
}
|
||||
}
|
||||
if (process.env.NAPI_RS_FORCE_WASI === "error" && !wasiBinding) {
|
||||
const error = /* @__PURE__ */ new Error("WASI binding not found and NAPI_RS_FORCE_WASI is set to error");
|
||||
error.cause = wasiBindingError;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (!nativeBinding && globalThis.process?.versions?.["webcontainer"]) try {
|
||||
nativeBinding = require_webcontainer_fallback();
|
||||
} catch (err) {
|
||||
loadErrors.push(err);
|
||||
}
|
||||
if (!nativeBinding) {
|
||||
if (loadErrors.length > 0) throw new Error("Cannot find native binding. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). Please try `npm i` again after removing both package-lock.json and node_modules directory.", { cause: loadErrors.reduce((err, cur) => {
|
||||
cur.cause = err;
|
||||
return cur;
|
||||
}) });
|
||||
throw new Error(`Failed to load native binding`);
|
||||
}
|
||||
module.exports = nativeBinding;
|
||||
module.exports.minify = nativeBinding.minify;
|
||||
module.exports.minifySync = nativeBinding.minifySync;
|
||||
module.exports.Severity = nativeBinding.Severity;
|
||||
module.exports.ParseResult = nativeBinding.ParseResult;
|
||||
module.exports.ExportExportNameKind = nativeBinding.ExportExportNameKind;
|
||||
module.exports.ExportImportNameKind = nativeBinding.ExportImportNameKind;
|
||||
module.exports.ExportLocalNameKind = nativeBinding.ExportLocalNameKind;
|
||||
module.exports.ImportNameKind = nativeBinding.ImportNameKind;
|
||||
module.exports.parse = nativeBinding.parse;
|
||||
module.exports.parseSync = nativeBinding.parseSync;
|
||||
module.exports.rawTransferSupported = nativeBinding.rawTransferSupported;
|
||||
module.exports.ResolverFactory = nativeBinding.ResolverFactory;
|
||||
module.exports.EnforceExtension = nativeBinding.EnforceExtension;
|
||||
module.exports.ModuleType = nativeBinding.ModuleType;
|
||||
module.exports.sync = nativeBinding.sync;
|
||||
module.exports.HelperMode = nativeBinding.HelperMode;
|
||||
module.exports.isolatedDeclaration = nativeBinding.isolatedDeclaration;
|
||||
module.exports.isolatedDeclarationSync = nativeBinding.isolatedDeclarationSync;
|
||||
module.exports.moduleRunnerTransform = nativeBinding.moduleRunnerTransform;
|
||||
module.exports.moduleRunnerTransformSync = nativeBinding.moduleRunnerTransformSync;
|
||||
module.exports.transform = nativeBinding.transform;
|
||||
module.exports.transformSync = nativeBinding.transformSync;
|
||||
module.exports.BindingBundleEndEventData = nativeBinding.BindingBundleEndEventData;
|
||||
module.exports.BindingBundleErrorEventData = nativeBinding.BindingBundleErrorEventData;
|
||||
module.exports.BindingBundler = nativeBinding.BindingBundler;
|
||||
module.exports.BindingCallableBuiltinPlugin = nativeBinding.BindingCallableBuiltinPlugin;
|
||||
module.exports.BindingChunkingContext = nativeBinding.BindingChunkingContext;
|
||||
module.exports.BindingDecodedMap = nativeBinding.BindingDecodedMap;
|
||||
module.exports.BindingDevEngine = nativeBinding.BindingDevEngine;
|
||||
module.exports.BindingLoadPluginContext = nativeBinding.BindingLoadPluginContext;
|
||||
module.exports.BindingMagicString = nativeBinding.BindingMagicString;
|
||||
module.exports.BindingModuleInfo = nativeBinding.BindingModuleInfo;
|
||||
module.exports.BindingNormalizedOptions = nativeBinding.BindingNormalizedOptions;
|
||||
module.exports.BindingOutputAsset = nativeBinding.BindingOutputAsset;
|
||||
module.exports.BindingOutputChunk = nativeBinding.BindingOutputChunk;
|
||||
module.exports.BindingPluginContext = nativeBinding.BindingPluginContext;
|
||||
module.exports.BindingRenderedChunk = nativeBinding.BindingRenderedChunk;
|
||||
module.exports.BindingRenderedChunkMeta = nativeBinding.BindingRenderedChunkMeta;
|
||||
module.exports.BindingRenderedModule = nativeBinding.BindingRenderedModule;
|
||||
module.exports.BindingSourceMap = nativeBinding.BindingSourceMap;
|
||||
module.exports.BindingTransformPluginContext = nativeBinding.BindingTransformPluginContext;
|
||||
module.exports.BindingWatcher = nativeBinding.BindingWatcher;
|
||||
module.exports.BindingWatcherBundler = nativeBinding.BindingWatcherBundler;
|
||||
module.exports.BindingWatcherChangeData = nativeBinding.BindingWatcherChangeData;
|
||||
module.exports.BindingWatcherEvent = nativeBinding.BindingWatcherEvent;
|
||||
module.exports.ParallelJsPluginRegistry = nativeBinding.ParallelJsPluginRegistry;
|
||||
module.exports.ScheduledBuild = nativeBinding.ScheduledBuild;
|
||||
module.exports.TraceSubscriberGuard = nativeBinding.TraceSubscriberGuard;
|
||||
module.exports.TsconfigCache = nativeBinding.TsconfigCache;
|
||||
module.exports.BindingAttachDebugInfo = nativeBinding.BindingAttachDebugInfo;
|
||||
module.exports.BindingBuiltinPluginName = nativeBinding.BindingBuiltinPluginName;
|
||||
module.exports.BindingChunkModuleOrderBy = nativeBinding.BindingChunkModuleOrderBy;
|
||||
module.exports.BindingLogLevel = nativeBinding.BindingLogLevel;
|
||||
module.exports.BindingPluginOrder = nativeBinding.BindingPluginOrder;
|
||||
module.exports.BindingPropertyReadSideEffects = nativeBinding.BindingPropertyReadSideEffects;
|
||||
module.exports.BindingPropertyWriteSideEffects = nativeBinding.BindingPropertyWriteSideEffects;
|
||||
module.exports.BindingRebuildStrategy = nativeBinding.BindingRebuildStrategy;
|
||||
module.exports.collapseSourcemaps = nativeBinding.collapseSourcemaps;
|
||||
module.exports.createTokioRuntime = nativeBinding.createTokioRuntime;
|
||||
module.exports.enhancedTransform = nativeBinding.enhancedTransform;
|
||||
module.exports.enhancedTransformSync = nativeBinding.enhancedTransformSync;
|
||||
module.exports.FilterTokenKind = nativeBinding.FilterTokenKind;
|
||||
module.exports.initTraceSubscriber = nativeBinding.initTraceSubscriber;
|
||||
module.exports.registerPlugins = nativeBinding.registerPlugins;
|
||||
module.exports.resolveTsconfig = nativeBinding.resolveTsconfig;
|
||||
module.exports.shutdownAsyncRuntime = nativeBinding.shutdownAsyncRuntime;
|
||||
module.exports.startAsyncRuntime = nativeBinding.startAsyncRuntime;
|
||||
}));
|
||||
|
||||
//#endregion
|
||||
export { __toESM as n, require_binding as t };
|
||||
+2181
File diff suppressed because it is too large
Load Diff
+58
@@ -0,0 +1,58 @@
|
||||
import { a as makeBuiltinPluginCallable, n as BuiltinPlugin, t as normalizedStringOrRegex } from "./normalize-string-or-regex-0P4NpnRa.mjs";
|
||||
|
||||
//#region src/builtin-plugin/constructors.ts
|
||||
function viteModulePreloadPolyfillPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-module-preload-polyfill", config);
|
||||
}
|
||||
function viteDynamicImportVarsPlugin(config) {
|
||||
if (config) {
|
||||
config.include = normalizedStringOrRegex(config.include);
|
||||
config.exclude = normalizedStringOrRegex(config.exclude);
|
||||
}
|
||||
return new BuiltinPlugin("builtin:vite-dynamic-import-vars", config);
|
||||
}
|
||||
function viteImportGlobPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-import-glob", config);
|
||||
}
|
||||
function viteReporterPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-reporter", config);
|
||||
}
|
||||
function viteWasmFallbackPlugin() {
|
||||
return makeBuiltinPluginCallable(new BuiltinPlugin("builtin:vite-wasm-fallback"));
|
||||
}
|
||||
function viteLoadFallbackPlugin() {
|
||||
return new BuiltinPlugin("builtin:vite-load-fallback");
|
||||
}
|
||||
function viteJsonPlugin(config) {
|
||||
return makeBuiltinPluginCallable(new BuiltinPlugin("builtin:vite-json", config));
|
||||
}
|
||||
function viteBuildImportAnalysisPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-build-import-analysis", config);
|
||||
}
|
||||
function viteResolvePlugin(config) {
|
||||
return makeBuiltinPluginCallable(new BuiltinPlugin("builtin:vite-resolve", {
|
||||
...config,
|
||||
yarnPnp: typeof process === "object" && !!process.versions?.pnp
|
||||
}));
|
||||
}
|
||||
function isolatedDeclarationPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:isolated-declaration", config);
|
||||
}
|
||||
function viteWebWorkerPostPlugin() {
|
||||
return new BuiltinPlugin("builtin:vite-web-worker-post");
|
||||
}
|
||||
function esmExternalRequirePlugin(config) {
|
||||
const plugin = new BuiltinPlugin("builtin:esm-external-require", config);
|
||||
plugin.enforce = "pre";
|
||||
return plugin;
|
||||
}
|
||||
function viteReactRefreshWrapperPlugin(config) {
|
||||
if (config) {
|
||||
config.include = normalizedStringOrRegex(config.include);
|
||||
config.exclude = normalizedStringOrRegex(config.exclude);
|
||||
}
|
||||
return makeBuiltinPluginCallable(new BuiltinPlugin("builtin:vite-react-refresh-wrapper", config));
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { viteImportGlobPlugin as a, viteModulePreloadPolyfillPlugin as c, viteResolvePlugin as d, viteWasmFallbackPlugin as f, viteDynamicImportVarsPlugin as i, viteReactRefreshWrapperPlugin as l, isolatedDeclarationPlugin as n, viteJsonPlugin as o, viteWebWorkerPostPlugin as p, viteBuildImportAnalysisPlugin as r, viteLoadFallbackPlugin as s, esmExternalRequirePlugin as t, viteReporterPlugin as u };
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import { C as BindingViteModulePreloadPolyfillPluginConfig, E as BindingViteResolvePluginConfig, T as BindingViteReporterPluginConfig, b as BindingViteImportGlobPluginConfig, l as BindingIsolatedDeclarationPluginConfig, s as BindingEsmExternalRequirePluginConfig, v as BindingViteBuildImportAnalysisPluginConfig, w as BindingViteReactRefreshWrapperPluginConfig, x as BindingViteJsonPluginConfig, y as BindingViteDynamicImportVarsPluginConfig } from "./binding-BLUhc7Nl.mjs";
|
||||
import { M as BuiltinPlugin, Rt as StringOrRegExp } from "./define-config-Cj8yDgkV.mjs";
|
||||
|
||||
//#region src/builtin-plugin/constructors.d.ts
|
||||
declare function viteModulePreloadPolyfillPlugin(config?: BindingViteModulePreloadPolyfillPluginConfig): BuiltinPlugin;
|
||||
type DynamicImportVarsPluginConfig = Omit<BindingViteDynamicImportVarsPluginConfig, "include" | "exclude"> & {
|
||||
include?: StringOrRegExp | StringOrRegExp[];
|
||||
exclude?: StringOrRegExp | StringOrRegExp[];
|
||||
};
|
||||
declare function viteDynamicImportVarsPlugin(config?: DynamicImportVarsPluginConfig): BuiltinPlugin;
|
||||
declare function viteImportGlobPlugin(config?: BindingViteImportGlobPluginConfig): BuiltinPlugin;
|
||||
declare function viteReporterPlugin(config: BindingViteReporterPluginConfig): BuiltinPlugin;
|
||||
declare function viteWasmFallbackPlugin(): BuiltinPlugin;
|
||||
declare function viteLoadFallbackPlugin(): BuiltinPlugin;
|
||||
declare function viteJsonPlugin(config: BindingViteJsonPluginConfig): BuiltinPlugin;
|
||||
declare function viteBuildImportAnalysisPlugin(config: BindingViteBuildImportAnalysisPluginConfig): BuiltinPlugin;
|
||||
declare function viteResolvePlugin(config: Omit<BindingViteResolvePluginConfig, "yarnPnp">): BuiltinPlugin;
|
||||
declare function isolatedDeclarationPlugin(config?: BindingIsolatedDeclarationPluginConfig): BuiltinPlugin;
|
||||
declare function viteWebWorkerPostPlugin(): BuiltinPlugin;
|
||||
declare function esmExternalRequirePlugin(config?: BindingEsmExternalRequirePluginConfig): BuiltinPlugin;
|
||||
type ViteReactRefreshWrapperPluginConfig = Omit<BindingViteReactRefreshWrapperPluginConfig, "include" | "exclude"> & {
|
||||
include?: StringOrRegExp | StringOrRegExp[];
|
||||
exclude?: StringOrRegExp | StringOrRegExp[];
|
||||
};
|
||||
declare function viteReactRefreshWrapperPlugin(config: ViteReactRefreshWrapperPluginConfig): BuiltinPlugin;
|
||||
//#endregion
|
||||
export { viteImportGlobPlugin as a, viteModulePreloadPolyfillPlugin as c, viteResolvePlugin as d, viteWasmFallbackPlugin as f, viteDynamicImportVarsPlugin as i, viteReactRefreshWrapperPlugin as l, isolatedDeclarationPlugin as n, viteJsonPlugin as o, viteWebWorkerPostPlugin as p, viteBuildImportAnalysisPlugin as r, viteLoadFallbackPlugin as s, esmExternalRequirePlugin as t, viteReporterPlugin as u };
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
//#region src/utils/define-config.ts
|
||||
function defineConfig(config) {
|
||||
return config;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { defineConfig as t };
|
||||
+3643
File diff suppressed because it is too large
Load Diff
+90
@@ -0,0 +1,90 @@
|
||||
import { n as __toESM, t as require_binding } from "./binding-DzKFaUu2.mjs";
|
||||
|
||||
//#region src/types/sourcemap.ts
|
||||
function bindingifySourcemap(map) {
|
||||
if (map == null) return;
|
||||
return { inner: typeof map === "string" ? map : {
|
||||
file: map.file ?? void 0,
|
||||
mappings: map.mappings,
|
||||
sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
|
||||
sources: map.sources?.map((s) => s ?? void 0),
|
||||
sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
|
||||
names: map.names,
|
||||
x_google_ignoreList: map.x_google_ignoreList,
|
||||
debugId: "debugId" in map ? map.debugId : void 0
|
||||
} };
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/utils/error.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
function unwrapBindingResult(container) {
|
||||
if (typeof container === "object" && container !== null && "isBindingErrors" in container && container.isBindingErrors) throw aggregateBindingErrorsIntoJsError(container.errors);
|
||||
return container;
|
||||
}
|
||||
function normalizeBindingResult(container) {
|
||||
if (typeof container === "object" && container !== null && "isBindingErrors" in container && container.isBindingErrors) return aggregateBindingErrorsIntoJsError(container.errors);
|
||||
return container;
|
||||
}
|
||||
function normalizeBindingError(e) {
|
||||
return e.type === "JsError" ? e.field0 : Object.assign(/* @__PURE__ */ new Error(), {
|
||||
code: e.field0.kind,
|
||||
kind: e.field0.kind,
|
||||
message: e.field0.message,
|
||||
id: e.field0.id,
|
||||
exporter: e.field0.exporter,
|
||||
loc: e.field0.loc,
|
||||
pos: e.field0.pos,
|
||||
stack: void 0
|
||||
});
|
||||
}
|
||||
function aggregateBindingErrorsIntoJsError(rawErrors) {
|
||||
const errors = rawErrors.map(normalizeBindingError);
|
||||
let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
|
||||
for (let i = 0; i < errors.length; i++) {
|
||||
summary += "\n";
|
||||
if (i >= 5) {
|
||||
summary += "...";
|
||||
break;
|
||||
}
|
||||
summary += getErrorMessage(errors[i]);
|
||||
}
|
||||
const wrapper = new Error(summary);
|
||||
Object.defineProperty(wrapper, "errors", {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: () => errors,
|
||||
set: (value) => Object.defineProperty(wrapper, "errors", {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
value
|
||||
})
|
||||
});
|
||||
return wrapper;
|
||||
}
|
||||
function getErrorMessage(e) {
|
||||
if (Object.hasOwn(e, "kind")) return e.message;
|
||||
let s = "";
|
||||
if (e.plugin) s += `[plugin ${e.plugin}]`;
|
||||
const id = e.id ?? e.loc?.file;
|
||||
if (id) {
|
||||
s += " " + id;
|
||||
if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
|
||||
}
|
||||
if (s) s += "\n";
|
||||
const message = `${e.name ?? "Error"}: ${e.message}`;
|
||||
s += message;
|
||||
if (e.frame) s = joinNewLine(s, e.frame);
|
||||
if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
|
||||
if (e.cause) {
|
||||
s = joinNewLine(s, "Caused by:");
|
||||
s = joinNewLine(s, getErrorMessage(e.cause).split("\n").map((line) => " " + line).join("\n"));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
function joinNewLine(s1, s2) {
|
||||
return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { bindingifySourcemap as a, unwrapBindingResult as i, normalizeBindingError as n, normalizeBindingResult as r, aggregateBindingErrorsIntoJsError as t };
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import { t as rolldown } from "./rolldown-6S97x4m9.mjs";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { readdir } from "node:fs/promises";
|
||||
import { cwd } from "node:process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
//#region src/utils/load-config.ts
|
||||
async function bundleTsConfig(configFile, isEsm) {
|
||||
const dirnameVarName = "injected_original_dirname";
|
||||
const filenameVarName = "injected_original_filename";
|
||||
const importMetaUrlVarName = "injected_original_import_meta_url";
|
||||
const bundle = await rolldown({
|
||||
input: configFile,
|
||||
platform: "node",
|
||||
resolve: { mainFields: ["main"] },
|
||||
transform: { define: {
|
||||
__dirname: dirnameVarName,
|
||||
__filename: filenameVarName,
|
||||
"import.meta.url": importMetaUrlVarName,
|
||||
"import.meta.dirname": dirnameVarName,
|
||||
"import.meta.filename": filenameVarName
|
||||
} },
|
||||
treeshake: false,
|
||||
external: [/^[\w@][^:]/],
|
||||
plugins: [{
|
||||
name: "inject-file-scope-variables",
|
||||
transform: {
|
||||
filter: { id: /\.[cm]?[jt]s$/ },
|
||||
async handler(code, id) {
|
||||
return {
|
||||
code: `const ${dirnameVarName} = ${JSON.stringify(path.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(id).href)};` + code,
|
||||
map: null
|
||||
};
|
||||
}
|
||||
}
|
||||
}]
|
||||
});
|
||||
const outputDir = path.dirname(configFile);
|
||||
const fileName = (await bundle.write({
|
||||
dir: outputDir,
|
||||
format: isEsm ? "esm" : "cjs",
|
||||
sourcemap: "inline",
|
||||
entryFileNames: `rolldown.config.[hash]${path.extname(configFile).replace("ts", "js")}`
|
||||
})).output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName;
|
||||
return path.join(outputDir, fileName);
|
||||
}
|
||||
const SUPPORTED_JS_CONFIG_FORMATS = [
|
||||
".js",
|
||||
".mjs",
|
||||
".cjs"
|
||||
];
|
||||
const SUPPORTED_TS_CONFIG_FORMATS = [
|
||||
".ts",
|
||||
".mts",
|
||||
".cts"
|
||||
];
|
||||
const SUPPORTED_CONFIG_FORMATS = [...SUPPORTED_JS_CONFIG_FORMATS, ...SUPPORTED_TS_CONFIG_FORMATS];
|
||||
const DEFAULT_CONFIG_BASE = "rolldown.config";
|
||||
async function findConfigFileNameInCwd() {
|
||||
const filesInWorkingDirectory = new Set(await readdir(cwd()));
|
||||
for (const extension of SUPPORTED_CONFIG_FORMATS) {
|
||||
const fileName = `${DEFAULT_CONFIG_BASE}${extension}`;
|
||||
if (filesInWorkingDirectory.has(fileName)) return fileName;
|
||||
}
|
||||
throw new Error("No `rolldown.config` configuration file found.");
|
||||
}
|
||||
async function loadTsConfig(configFile) {
|
||||
const file = await bundleTsConfig(configFile, isFilePathESM(configFile));
|
||||
try {
|
||||
return (await import(pathToFileURL(file).href)).default;
|
||||
} finally {
|
||||
fs.unlink(file, () => {});
|
||||
}
|
||||
}
|
||||
function isFilePathESM(filePath) {
|
||||
if (/\.m[jt]s$/.test(filePath)) return true;
|
||||
else if (/\.c[jt]s$/.test(filePath)) return false;
|
||||
else {
|
||||
const pkg = findNearestPackageData(path.dirname(filePath));
|
||||
if (pkg) return pkg.type === "module";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function findNearestPackageData(basedir) {
|
||||
while (basedir) {
|
||||
const pkgPath = path.join(basedir, "package.json");
|
||||
if (tryStatSync(pkgPath)?.isFile()) try {
|
||||
return JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
||||
} catch {}
|
||||
const nextBasedir = path.dirname(basedir);
|
||||
if (nextBasedir === basedir) break;
|
||||
basedir = nextBasedir;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function tryStatSync(file) {
|
||||
try {
|
||||
return fs.statSync(file, { throwIfNoEntry: false });
|
||||
} catch {}
|
||||
}
|
||||
async function loadConfig(configPath) {
|
||||
const ext = path.extname(configPath = configPath || await findConfigFileNameInCwd());
|
||||
try {
|
||||
if (SUPPORTED_JS_CONFIG_FORMATS.includes(ext) || process.env.NODE_OPTIONS?.includes("--import=tsx") && SUPPORTED_TS_CONFIG_FORMATS.includes(ext)) return (await import(pathToFileURL(configPath).href)).default;
|
||||
else if (SUPPORTED_TS_CONFIG_FORMATS.includes(ext)) return await loadTsConfig(path.resolve(configPath));
|
||||
else throw new Error(`Unsupported config format. Expected: \`${SUPPORTED_CONFIG_FORMATS.join(",")}\` but got \`${ext}\``);
|
||||
} catch (err) {
|
||||
throw new Error("Error happened while loading config.", { cause: err });
|
||||
}
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { loadConfig as t };
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
//#region src/log/logging.d.ts
|
||||
/** @inline */
|
||||
type LogLevel = "info" | "debug" | "warn";
|
||||
/** @inline */
|
||||
type LogLevelOption = LogLevel | "silent";
|
||||
/** @inline */
|
||||
type LogLevelWithError = LogLevel | "error";
|
||||
interface RolldownLog {
|
||||
binding?: string;
|
||||
cause?: unknown;
|
||||
/**
|
||||
* The log code for this log object.
|
||||
* @example 'PLUGIN_ERROR'
|
||||
*/
|
||||
code?: string;
|
||||
exporter?: string;
|
||||
frame?: string;
|
||||
hook?: string;
|
||||
id?: string;
|
||||
ids?: string[];
|
||||
loc?: {
|
||||
column: number;
|
||||
file?: string;
|
||||
line: number;
|
||||
};
|
||||
/**
|
||||
* The message for this log object.
|
||||
* @example 'The "transform" hook used by the output plugin "rolldown-plugin-foo" is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.'
|
||||
*/
|
||||
message: string;
|
||||
meta?: any;
|
||||
names?: string[];
|
||||
plugin?: string;
|
||||
pluginCode?: unknown;
|
||||
pos?: number;
|
||||
reexporter?: string;
|
||||
stack?: string;
|
||||
url?: string;
|
||||
}
|
||||
/** @inline */
|
||||
type RolldownLogWithString = RolldownLog | string;
|
||||
/** @category Plugin APIs */
|
||||
interface RolldownError extends RolldownLog {
|
||||
name?: string;
|
||||
stack?: string;
|
||||
watchFiles?: string[];
|
||||
}
|
||||
type LogOrStringHandler = (level: LogLevelWithError, log: RolldownLogWithString) => void;
|
||||
//#endregion
|
||||
export { RolldownLog as a, RolldownError as i, LogLevelOption as n, RolldownLogWithString as o, LogOrStringHandler as r, LogLevel as t };
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
//#region src/utils/code-frame.ts
|
||||
function spaces(index) {
|
||||
let result = "";
|
||||
while (index--) result += " ";
|
||||
return result;
|
||||
}
|
||||
function tabsToSpaces(value) {
|
||||
return value.replace(/^\t+/, (match) => match.split(" ").join(" "));
|
||||
}
|
||||
const LINE_TRUNCATE_LENGTH = 120;
|
||||
const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10;
|
||||
const ELLIPSIS = "...";
|
||||
function getCodeFrame(source, line, column) {
|
||||
let lines = source.split("\n");
|
||||
if (line > lines.length) return "";
|
||||
const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length + MIN_CHARACTERS_SHOWN_AFTER_LOCATION + 3, LINE_TRUNCATE_LENGTH);
|
||||
const frameStart = Math.max(0, line - 3);
|
||||
let frameEnd = Math.min(line + 2, lines.length);
|
||||
lines = lines.slice(frameStart, frameEnd);
|
||||
while (!/\S/.test(lines[lines.length - 1])) {
|
||||
lines.pop();
|
||||
frameEnd -= 1;
|
||||
}
|
||||
const digits = String(frameEnd).length;
|
||||
return lines.map((sourceLine, index) => {
|
||||
const isErrorLine = frameStart + index + 1 === line;
|
||||
let lineNumber = String(index + frameStart + 1);
|
||||
while (lineNumber.length < digits) lineNumber = ` ${lineNumber}`;
|
||||
let displayedLine = tabsToSpaces(sourceLine);
|
||||
if (displayedLine.length > maxLineLength) displayedLine = `${displayedLine.slice(0, maxLineLength - 3)}${ELLIPSIS}`;
|
||||
if (isErrorLine) {
|
||||
const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + "^";
|
||||
return `${lineNumber}: ${displayedLine}\n${indicator}`;
|
||||
}
|
||||
return `${lineNumber}: ${displayedLine}`;
|
||||
}).join("\n");
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/log/locate-character/index.js
|
||||
/** @typedef {import('./types').Location} Location */
|
||||
/**
|
||||
* @param {import('./types').Range} range
|
||||
* @param {number} index
|
||||
*/
|
||||
function rangeContains(range, index) {
|
||||
return range.start <= index && index < range.end;
|
||||
}
|
||||
/**
|
||||
* @param {string} source
|
||||
* @param {import('./types').Options} [options]
|
||||
*/
|
||||
function getLocator(source, options = {}) {
|
||||
const { offsetLine = 0, offsetColumn = 0 } = options;
|
||||
let start = 0;
|
||||
const ranges = source.split("\n").map((line, i) => {
|
||||
const end = start + line.length + 1;
|
||||
/** @type {import('./types').Range} */
|
||||
const range = {
|
||||
start,
|
||||
end,
|
||||
line: i
|
||||
};
|
||||
start = end;
|
||||
return range;
|
||||
});
|
||||
let i = 0;
|
||||
/**
|
||||
* @param {string | number} search
|
||||
* @param {number} [index]
|
||||
* @returns {Location | undefined}
|
||||
*/
|
||||
function locator(search, index) {
|
||||
if (typeof search === "string") search = source.indexOf(search, index ?? 0);
|
||||
if (search === -1) return void 0;
|
||||
let range = ranges[i];
|
||||
const d = search >= range.end ? 1 : -1;
|
||||
while (range) {
|
||||
if (rangeContains(range, search)) return {
|
||||
line: offsetLine + range.line,
|
||||
column: offsetColumn + search - range.start,
|
||||
character: search
|
||||
};
|
||||
i += d;
|
||||
range = ranges[i];
|
||||
}
|
||||
}
|
||||
return locator;
|
||||
}
|
||||
/**
|
||||
* @param {string} source
|
||||
* @param {string | number} search
|
||||
* @param {import('./types').Options} [options]
|
||||
* @returns {Location | undefined}
|
||||
*/
|
||||
function locate(source, search, options) {
|
||||
return getLocator(source, options)(search, options && options.startIndex);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/log/logs.ts
|
||||
const INVALID_LOG_POSITION = "INVALID_LOG_POSITION", PLUGIN_ERROR = "PLUGIN_ERROR", INPUT_HOOK_IN_OUTPUT_PLUGIN = "INPUT_HOOK_IN_OUTPUT_PLUGIN", CYCLE_LOADING = "CYCLE_LOADING", MULTIPLY_NOTIFY_OPTION = "MULTIPLY_NOTIFY_OPTION", PARSE_ERROR = "PARSE_ERROR", NO_FS_IN_BROWSER = "NO_FS_IN_BROWSER";
|
||||
function logParseError(message, id, pos) {
|
||||
return {
|
||||
code: PARSE_ERROR,
|
||||
id,
|
||||
message,
|
||||
pos
|
||||
};
|
||||
}
|
||||
function logInvalidLogPosition(pluginName) {
|
||||
return {
|
||||
code: INVALID_LOG_POSITION,
|
||||
message: `Plugin "${pluginName}" tried to add a file position to a log or warning. This is only supported in the "transform" hook at the moment and will be ignored.`
|
||||
};
|
||||
}
|
||||
function logInputHookInOutputPlugin(pluginName, hookName) {
|
||||
return {
|
||||
code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
|
||||
message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
|
||||
};
|
||||
}
|
||||
function logCycleLoading(pluginName, moduleId) {
|
||||
return {
|
||||
code: CYCLE_LOADING,
|
||||
message: `Found the module "${moduleId}" cycle loading at ${pluginName} plugin, it maybe blocking fetching modules.`
|
||||
};
|
||||
}
|
||||
function logMultiplyNotifyOption() {
|
||||
return {
|
||||
code: MULTIPLY_NOTIFY_OPTION,
|
||||
message: `Found multiply notify option at watch options, using first one to start notify watcher.`
|
||||
};
|
||||
}
|
||||
function logPluginError(error, plugin, { hook, id } = {}) {
|
||||
try {
|
||||
const code = error.code;
|
||||
if (!error.pluginCode && code != null && (typeof code !== "string" || !code.startsWith("PLUGIN_"))) error.pluginCode = code;
|
||||
error.code = PLUGIN_ERROR;
|
||||
error.plugin = plugin;
|
||||
if (hook) error.hook = hook;
|
||||
if (id) error.id = id;
|
||||
} catch (_) {} finally {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
function error(base) {
|
||||
if (!(base instanceof Error)) {
|
||||
base = Object.assign(new Error(base.message), base);
|
||||
Object.defineProperty(base, "name", {
|
||||
value: "RolldownError",
|
||||
writable: true
|
||||
});
|
||||
}
|
||||
throw base;
|
||||
}
|
||||
function augmentCodeLocation(properties, pos, source, id) {
|
||||
if (typeof pos === "object") {
|
||||
const { line, column } = pos;
|
||||
properties.loc = {
|
||||
column,
|
||||
file: id,
|
||||
line
|
||||
};
|
||||
} else {
|
||||
properties.pos = pos;
|
||||
const location = locate(source, pos, { offsetLine: 1 });
|
||||
if (!location) return;
|
||||
const { line, column } = location;
|
||||
properties.loc = {
|
||||
column,
|
||||
file: id,
|
||||
line
|
||||
};
|
||||
}
|
||||
if (properties.frame === void 0) {
|
||||
const { line, column } = properties.loc;
|
||||
properties.frame = getCodeFrame(source, line, column);
|
||||
}
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { logInvalidLogPosition as a, logPluginError as c, logInputHookInOutputPlugin as i, locate as l, error as n, logMultiplyNotifyOption as o, logCycleLoading as r, logParseError as s, augmentCodeLocation as t, getCodeFrame as u };
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
//#region src/utils/misc.ts
|
||||
function arraify(value) {
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
function isPromiseLike(value) {
|
||||
return value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
|
||||
}
|
||||
function unimplemented(info) {
|
||||
if (info) throw new Error(`unimplemented: ${info}`);
|
||||
throw new Error("unimplemented");
|
||||
}
|
||||
function unreachable(info) {
|
||||
if (info) throw new Error(`unreachable: ${info}`);
|
||||
throw new Error("unreachable");
|
||||
}
|
||||
function unsupported(info) {
|
||||
throw new Error(`UNSUPPORTED: ${info}`);
|
||||
}
|
||||
function noop(..._args) {}
|
||||
|
||||
//#endregion
|
||||
export { unreachable as a, unimplemented as i, isPromiseLike as n, unsupported as o, noop as r, arraify as t };
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { n as __toESM, t as require_binding } from "./binding-DzKFaUu2.mjs";
|
||||
import { c as logPluginError, n as error } from "./logs-COHDsWqD.mjs";
|
||||
|
||||
//#region src/builtin-plugin/utils.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
var BuiltinPlugin = class {
|
||||
/** Vite-specific option to control plugin ordering */
|
||||
enforce;
|
||||
constructor(name, _options) {
|
||||
this.name = name;
|
||||
this._options = _options;
|
||||
}
|
||||
};
|
||||
function makeBuiltinPluginCallable(plugin) {
|
||||
let callablePlugin = new import_binding.BindingCallableBuiltinPlugin(bindingifyBuiltInPlugin(plugin));
|
||||
const wrappedPlugin = plugin;
|
||||
for (const key in callablePlugin) wrappedPlugin[key] = async function(...args) {
|
||||
try {
|
||||
return await callablePlugin[key](...args);
|
||||
} catch (e) {
|
||||
if (e instanceof Error && !e.stack?.includes("at ")) Error.captureStackTrace(e, wrappedPlugin[key]);
|
||||
return error(logPluginError(e, plugin.name, {
|
||||
hook: key,
|
||||
id: key === "transform" ? args[2] : void 0
|
||||
}));
|
||||
}
|
||||
};
|
||||
return wrappedPlugin;
|
||||
}
|
||||
function bindingifyBuiltInPlugin(plugin) {
|
||||
return {
|
||||
__name: plugin.name,
|
||||
options: plugin._options
|
||||
};
|
||||
}
|
||||
function bindingifyManifestPlugin(plugin, pluginContextData) {
|
||||
const { isOutputOptionsForLegacyChunks, ...options } = plugin._options;
|
||||
return {
|
||||
__name: plugin.name,
|
||||
options: {
|
||||
...options,
|
||||
isLegacy: isOutputOptionsForLegacyChunks ? (opts) => {
|
||||
return isOutputOptionsForLegacyChunks(pluginContextData.getOutputOptions(opts));
|
||||
} : void 0
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/utils/normalize-string-or-regex.ts
|
||||
function normalizedStringOrRegex(pattern) {
|
||||
if (!pattern) return;
|
||||
if (!isReadonlyArray(pattern)) return [pattern];
|
||||
return pattern;
|
||||
}
|
||||
function isReadonlyArray(input) {
|
||||
return Array.isArray(input);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { makeBuiltinPluginCallable as a, bindingifyManifestPlugin as i, BuiltinPlugin as n, bindingifyBuiltInPlugin as r, normalizedStringOrRegex as t };
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { n as __toESM, t as require_binding } from "./binding-DzKFaUu2.mjs";
|
||||
|
||||
//#region ../../node_modules/.pnpm/oxc-parser@0.112.0/node_modules/oxc-parser/src-js/wrap.js
|
||||
function wrap(result) {
|
||||
let program, module, comments, errors;
|
||||
return {
|
||||
get program() {
|
||||
if (!program) program = jsonParseAst(result.program);
|
||||
return program;
|
||||
},
|
||||
get module() {
|
||||
if (!module) module = result.module;
|
||||
return module;
|
||||
},
|
||||
get comments() {
|
||||
if (!comments) comments = result.comments;
|
||||
return comments;
|
||||
},
|
||||
get errors() {
|
||||
if (!errors) errors = result.errors;
|
||||
return errors;
|
||||
}
|
||||
};
|
||||
}
|
||||
function jsonParseAst(programJson) {
|
||||
const { node: program, fixes } = JSON.parse(programJson);
|
||||
for (const fixPath of fixes) applyFix(program, fixPath);
|
||||
return program;
|
||||
}
|
||||
function applyFix(program, fixPath) {
|
||||
let node = program;
|
||||
for (const key of fixPath) node = node[key];
|
||||
if (node.bigint) node.value = BigInt(node.bigint);
|
||||
else try {
|
||||
node.value = RegExp(node.regex.pattern, node.regex.flags);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/utils/parse.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
/**
|
||||
* Parse JS/TS source asynchronously on a separate thread.
|
||||
*
|
||||
* Note that not all of the workload can happen on a separate thread.
|
||||
* Parsing on Rust side does happen in a separate thread, but deserialization of the AST to JS objects
|
||||
* has to happen on current thread. This synchronous deserialization work typically outweighs
|
||||
* the asynchronous parsing by a factor of between 3 and 20.
|
||||
*
|
||||
* i.e. the majority of the workload cannot be parallelized by using this method.
|
||||
*
|
||||
* Generally `parseSync` is preferable to use as it does not have the overhead of spawning a thread.
|
||||
* If you need to parallelize parsing multiple files, it is recommended to use worker threads.
|
||||
*/
|
||||
async function parse(filename, sourceText, options) {
|
||||
return wrap(await (0, import_binding.parse)(filename, sourceText, options));
|
||||
}
|
||||
/**
|
||||
* Parse JS/TS source synchronously on current thread.
|
||||
*
|
||||
* This is generally preferable over `parse` (async) as it does not have the overhead
|
||||
* of spawning a thread, and the majority of the workload cannot be parallelized anyway
|
||||
* (see `parse` documentation for details).
|
||||
*
|
||||
* If you need to parallelize parsing multiple files, it is recommended to use worker threads
|
||||
* with `parseSync` rather than using `parse`.
|
||||
*/
|
||||
function parseSync(filename, sourceText, options) {
|
||||
return wrap((0, import_binding.parseSync)(filename, sourceText, options));
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { parseSync as n, parse as t };
|
||||
+847
File diff suppressed because one or more lines are too long
+42
@@ -0,0 +1,42 @@
|
||||
import { c as validateOption, t as RolldownBuild, u as PluginDriver } from "./rolldown-build-CjERPB8v.mjs";
|
||||
|
||||
//#region src/api/rolldown/index.ts
|
||||
/**
|
||||
* The API compatible with Rollup's `rollup` function.
|
||||
*
|
||||
* Unlike Rollup, the module graph is not built until the methods of the bundle object are called.
|
||||
*
|
||||
* @param input The input options object.
|
||||
* @returns A Promise that resolves to a bundle object.
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { rolldown } from 'rolldown';
|
||||
*
|
||||
* let bundle, failed = false;
|
||||
* try {
|
||||
* bundle = await rolldown({
|
||||
* input: 'src/main.js',
|
||||
* });
|
||||
* await bundle.write({
|
||||
* format: 'esm',
|
||||
* });
|
||||
* } catch (e) {
|
||||
* console.error(e);
|
||||
* failed = true;
|
||||
* }
|
||||
* if (bundle) {
|
||||
* await bundle.close();
|
||||
* }
|
||||
* process.exitCode = failed ? 1 : 0;
|
||||
* ```
|
||||
*
|
||||
* @category Programmatic APIs
|
||||
*/
|
||||
const rolldown = async (input) => {
|
||||
validateOption("input", input);
|
||||
return new RolldownBuild(await PluginDriver.callOptionsHook(input));
|
||||
};
|
||||
|
||||
//#endregion
|
||||
export { rolldown as t };
|
||||
+3366
File diff suppressed because one or more lines are too long
+91
@@ -0,0 +1,91 @@
|
||||
import { n as __toESM, t as require_binding } from "./binding-DzKFaUu2.mjs";
|
||||
import { a as bindingifySourcemap, n as normalizeBindingError } from "./error-DC8XkJKP.mjs";
|
||||
|
||||
//#region src/utils/minify.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||||
/**
|
||||
* Minify asynchronously.
|
||||
*
|
||||
* Note: This function can be slower than `minifySync` due to the overhead of spawning a thread.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
async function minify(filename, sourceText, options) {
|
||||
const inputMap = bindingifySourcemap(options?.inputMap);
|
||||
const result = await (0, import_binding.minify)(filename, sourceText, options);
|
||||
if (result.map && inputMap) result.map = {
|
||||
version: 3,
|
||||
...(0, import_binding.collapseSourcemaps)([inputMap, bindingifySourcemap(result.map)])
|
||||
};
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Minify synchronously.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
function minifySync(filename, sourceText, options) {
|
||||
const inputMap = bindingifySourcemap(options?.inputMap);
|
||||
const result = (0, import_binding.minifySync)(filename, sourceText, options);
|
||||
if (result.map && inputMap) result.map = {
|
||||
version: 3,
|
||||
...(0, import_binding.collapseSourcemaps)([inputMap, bindingifySourcemap(result.map)])
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/utils/transform.ts
|
||||
/**
|
||||
* Transpile a JavaScript or TypeScript into a target ECMAScript version, asynchronously.
|
||||
*
|
||||
* Note: This function can be slower than `transformSync` due to the overhead of spawning a thread.
|
||||
*
|
||||
* @param filename The name of the file being transformed. If this is a
|
||||
* relative path, consider setting the {@link TransformOptions#cwd} option.
|
||||
* @param source_text The source code to transform.
|
||||
* @param options The transform options including tsconfig and inputMap. See {@link
|
||||
* BindingEnhancedTransformOptions} for more information.
|
||||
* @param cache Optional tsconfig cache for reusing resolved tsconfig across multiple transforms.
|
||||
* Only used when `options.tsconfig` is `true`.
|
||||
*
|
||||
* @returns a promise that resolves to an object containing the transformed code,
|
||||
* source maps, and any errors that occurred during parsing or transformation.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
async function transform(filename, sourceText, options, cache) {
|
||||
const result = await (0, import_binding.enhancedTransform)(filename, sourceText, options, cache);
|
||||
return {
|
||||
...result,
|
||||
errors: result.errors.map(normalizeBindingError),
|
||||
warnings: result.warnings.map((w) => w.field0)
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Transpile a JavaScript or TypeScript into a target ECMAScript version.
|
||||
*
|
||||
* @param filename The name of the file being transformed. If this is a
|
||||
* relative path, consider setting the {@link TransformOptions#cwd} option.
|
||||
* @param source_text The source code to transform.
|
||||
* @param options The transform options including tsconfig and inputMap. See {@link
|
||||
* BindingEnhancedTransformOptions} for more information.
|
||||
* @param cache Optional tsconfig cache for reusing resolved tsconfig across multiple transforms.
|
||||
* Only used when `options.tsconfig` is `true`.
|
||||
*
|
||||
* @returns an object containing the transformed code, source maps, and any errors
|
||||
* that occurred during parsing or transformation.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
function transformSync(filename, sourceText, options, cache) {
|
||||
const result = (0, import_binding.enhancedTransformSync)(filename, sourceText, options, cache);
|
||||
return {
|
||||
...result,
|
||||
errors: result.errors.map(normalizeBindingError),
|
||||
warnings: result.warnings.map((w) => w.field0)
|
||||
};
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { minifySync as a, minify as i, transform as n, transformSync as r, import_binding as t };
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
import { a as RolldownLog } from "./logging-CKYae7lu.mjs";
|
||||
import { I as ParseResult, L as ParserOptions, N as MinifyOptions$1, P as MinifyResult, U as TsconfigCache, V as SourceMap, a as BindingEnhancedTransformOptions, o as BindingEnhancedTransformResult } from "./binding-BLUhc7Nl.mjs";
|
||||
|
||||
//#region src/utils/parse.d.ts
|
||||
/**
|
||||
* Parse JS/TS source asynchronously on a separate thread.
|
||||
*
|
||||
* Note that not all of the workload can happen on a separate thread.
|
||||
* Parsing on Rust side does happen in a separate thread, but deserialization of the AST to JS objects
|
||||
* has to happen on current thread. This synchronous deserialization work typically outweighs
|
||||
* the asynchronous parsing by a factor of between 3 and 20.
|
||||
*
|
||||
* i.e. the majority of the workload cannot be parallelized by using this method.
|
||||
*
|
||||
* Generally `parseSync` is preferable to use as it does not have the overhead of spawning a thread.
|
||||
* If you need to parallelize parsing multiple files, it is recommended to use worker threads.
|
||||
*/
|
||||
declare function parse(filename: string, sourceText: string, options?: ParserOptions | null): Promise<ParseResult>;
|
||||
/**
|
||||
* Parse JS/TS source synchronously on current thread.
|
||||
*
|
||||
* This is generally preferable over `parse` (async) as it does not have the overhead
|
||||
* of spawning a thread, and the majority of the workload cannot be parallelized anyway
|
||||
* (see `parse` documentation for details).
|
||||
*
|
||||
* If you need to parallelize parsing multiple files, it is recommended to use worker threads
|
||||
* with `parseSync` rather than using `parse`.
|
||||
*/
|
||||
declare function parseSync(filename: string, sourceText: string, options?: ParserOptions | null): ParseResult;
|
||||
//#endregion
|
||||
//#region src/utils/minify.d.ts
|
||||
type MinifyOptions = MinifyOptions$1 & {
|
||||
inputMap?: SourceMap;
|
||||
};
|
||||
/**
|
||||
* Minify asynchronously.
|
||||
*
|
||||
* Note: This function can be slower than `minifySync` due to the overhead of spawning a thread.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare function minify(filename: string, sourceText: string, options?: MinifyOptions | null): Promise<MinifyResult>;
|
||||
/**
|
||||
* Minify synchronously.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare function minifySync(filename: string, sourceText: string, options?: MinifyOptions | null): MinifyResult;
|
||||
//#endregion
|
||||
//#region src/utils/transform.d.ts
|
||||
type TransformResult = Omit<BindingEnhancedTransformResult, "errors" | "warnings"> & {
|
||||
errors: Error[];
|
||||
warnings: RolldownLog[];
|
||||
};
|
||||
/**
|
||||
* Transpile a JavaScript or TypeScript into a target ECMAScript version, asynchronously.
|
||||
*
|
||||
* Note: This function can be slower than `transformSync` due to the overhead of spawning a thread.
|
||||
*
|
||||
* @param filename The name of the file being transformed. If this is a
|
||||
* relative path, consider setting the {@link TransformOptions#cwd} option.
|
||||
* @param source_text The source code to transform.
|
||||
* @param options The transform options including tsconfig and inputMap. See {@link
|
||||
* BindingEnhancedTransformOptions} for more information.
|
||||
* @param cache Optional tsconfig cache for reusing resolved tsconfig across multiple transforms.
|
||||
* Only used when `options.tsconfig` is `true`.
|
||||
*
|
||||
* @returns a promise that resolves to an object containing the transformed code,
|
||||
* source maps, and any errors that occurred during parsing or transformation.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare function transform(filename: string, sourceText: string, options?: BindingEnhancedTransformOptions | null, cache?: TsconfigCache | null): Promise<TransformResult>;
|
||||
/**
|
||||
* Transpile a JavaScript or TypeScript into a target ECMAScript version.
|
||||
*
|
||||
* @param filename The name of the file being transformed. If this is a
|
||||
* relative path, consider setting the {@link TransformOptions#cwd} option.
|
||||
* @param source_text The source code to transform.
|
||||
* @param options The transform options including tsconfig and inputMap. See {@link
|
||||
* BindingEnhancedTransformOptions} for more information.
|
||||
* @param cache Optional tsconfig cache for reusing resolved tsconfig across multiple transforms.
|
||||
* Only used when `options.tsconfig` is `true`.
|
||||
*
|
||||
* @returns an object containing the transformed code, source maps, and any errors
|
||||
* that occurred during parsing or transformation.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
declare function transformSync(filename: string, sourceText: string, options?: BindingEnhancedTransformOptions | null, cache?: TsconfigCache | null): TransformResult;
|
||||
//#endregion
|
||||
export { minify as a, parseSync as c, MinifyOptions as i, transform as n, minifySync as o, transformSync as r, parse as s, TransformResult as t };
|
||||
+380
@@ -0,0 +1,380 @@
|
||||
import { n as __toESM, t as require_binding } from "./binding-DzKFaUu2.mjs";
|
||||
import { o as logMultiplyNotifyOption } from "./logs-COHDsWqD.mjs";
|
||||
import { _ as LOG_LEVEL_WARN } from "./bindingify-input-options-phmnMdxa.mjs";
|
||||
import { t as arraify } from "./misc-CCZIsXVO.mjs";
|
||||
import { n as createBundlerOptions, u as PluginDriver } from "./rolldown-build-CjERPB8v.mjs";
|
||||
import { t as aggregateBindingErrorsIntoJsError } from "./error-DC8XkJKP.mjs";
|
||||
|
||||
//#region ../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/signals.js
|
||||
/**
|
||||
* This is not the set of all possible signals.
|
||||
*
|
||||
* It IS, however, the set of all signals that trigger
|
||||
* an exit on either Linux or BSD systems. Linux is a
|
||||
* superset of the signal names supported on BSD, and
|
||||
* the unknown signals just fail to register, so we can
|
||||
* catch that easily enough.
|
||||
*
|
||||
* Windows signals are a different set, since there are
|
||||
* signals that terminate Windows processes, but don't
|
||||
* terminate (or don't even exist) on Posix systems.
|
||||
*
|
||||
* Don't bother with SIGKILL. It's uncatchable, which
|
||||
* means that we can't fire any callbacks anyway.
|
||||
*
|
||||
* If a user does happen to register a handler on a non-
|
||||
* fatal signal like SIGWINCH or something, and then
|
||||
* exit, it'll end up firing `process.emit('exit')`, so
|
||||
* the handler will be fired anyway.
|
||||
*
|
||||
* SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
|
||||
* artificially, inherently leave the process in a
|
||||
* state from which it is not safe to try and enter JS
|
||||
* listeners.
|
||||
*/
|
||||
const signals = [];
|
||||
signals.push("SIGHUP", "SIGINT", "SIGTERM");
|
||||
if (process.platform !== "win32") signals.push("SIGALRM", "SIGABRT", "SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
|
||||
if (process.platform === "linux") signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT");
|
||||
|
||||
//#endregion
|
||||
//#region ../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/index.js
|
||||
const processOk = (process) => !!process && typeof process === "object" && typeof process.removeListener === "function" && typeof process.emit === "function" && typeof process.reallyExit === "function" && typeof process.listeners === "function" && typeof process.kill === "function" && typeof process.pid === "number" && typeof process.on === "function";
|
||||
const kExitEmitter = Symbol.for("signal-exit emitter");
|
||||
const global = globalThis;
|
||||
const ObjectDefineProperty = Object.defineProperty.bind(Object);
|
||||
var Emitter = class {
|
||||
emitted = {
|
||||
afterExit: false,
|
||||
exit: false
|
||||
};
|
||||
listeners = {
|
||||
afterExit: [],
|
||||
exit: []
|
||||
};
|
||||
count = 0;
|
||||
id = Math.random();
|
||||
constructor() {
|
||||
if (global[kExitEmitter]) return global[kExitEmitter];
|
||||
ObjectDefineProperty(global, kExitEmitter, {
|
||||
value: this,
|
||||
writable: false,
|
||||
enumerable: false,
|
||||
configurable: false
|
||||
});
|
||||
}
|
||||
on(ev, fn) {
|
||||
this.listeners[ev].push(fn);
|
||||
}
|
||||
removeListener(ev, fn) {
|
||||
const list = this.listeners[ev];
|
||||
const i = list.indexOf(fn);
|
||||
/* c8 ignore start */
|
||||
if (i === -1) return;
|
||||
/* c8 ignore stop */
|
||||
if (i === 0 && list.length === 1) list.length = 0;
|
||||
else list.splice(i, 1);
|
||||
}
|
||||
emit(ev, code, signal) {
|
||||
if (this.emitted[ev]) return false;
|
||||
this.emitted[ev] = true;
|
||||
let ret = false;
|
||||
for (const fn of this.listeners[ev]) ret = fn(code, signal) === true || ret;
|
||||
if (ev === "exit") ret = this.emit("afterExit", code, signal) || ret;
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
var SignalExitBase = class {};
|
||||
const signalExitWrap = (handler) => {
|
||||
return {
|
||||
onExit(cb, opts) {
|
||||
return handler.onExit(cb, opts);
|
||||
},
|
||||
load() {
|
||||
return handler.load();
|
||||
},
|
||||
unload() {
|
||||
return handler.unload();
|
||||
}
|
||||
};
|
||||
};
|
||||
var SignalExitFallback = class extends SignalExitBase {
|
||||
onExit() {
|
||||
return () => {};
|
||||
}
|
||||
load() {}
|
||||
unload() {}
|
||||
};
|
||||
var SignalExit = class extends SignalExitBase {
|
||||
/* c8 ignore start */
|
||||
#hupSig = process$1.platform === "win32" ? "SIGINT" : "SIGHUP";
|
||||
/* c8 ignore stop */
|
||||
#emitter = new Emitter();
|
||||
#process;
|
||||
#originalProcessEmit;
|
||||
#originalProcessReallyExit;
|
||||
#sigListeners = {};
|
||||
#loaded = false;
|
||||
constructor(process) {
|
||||
super();
|
||||
this.#process = process;
|
||||
this.#sigListeners = {};
|
||||
for (const sig of signals) this.#sigListeners[sig] = () => {
|
||||
const listeners = this.#process.listeners(sig);
|
||||
let { count } = this.#emitter;
|
||||
/* c8 ignore start */
|
||||
const p = process;
|
||||
if (typeof p.__signal_exit_emitter__ === "object" && typeof p.__signal_exit_emitter__.count === "number") count += p.__signal_exit_emitter__.count;
|
||||
/* c8 ignore stop */
|
||||
if (listeners.length === count) {
|
||||
this.unload();
|
||||
const ret = this.#emitter.emit("exit", null, sig);
|
||||
/* c8 ignore start */
|
||||
const s = sig === "SIGHUP" ? this.#hupSig : sig;
|
||||
if (!ret) process.kill(process.pid, s);
|
||||
}
|
||||
};
|
||||
this.#originalProcessReallyExit = process.reallyExit;
|
||||
this.#originalProcessEmit = process.emit;
|
||||
}
|
||||
onExit(cb, opts) {
|
||||
/* c8 ignore start */
|
||||
if (!processOk(this.#process)) return () => {};
|
||||
/* c8 ignore stop */
|
||||
if (this.#loaded === false) this.load();
|
||||
const ev = opts?.alwaysLast ? "afterExit" : "exit";
|
||||
this.#emitter.on(ev, cb);
|
||||
return () => {
|
||||
this.#emitter.removeListener(ev, cb);
|
||||
if (this.#emitter.listeners["exit"].length === 0 && this.#emitter.listeners["afterExit"].length === 0) this.unload();
|
||||
};
|
||||
}
|
||||
load() {
|
||||
if (this.#loaded) return;
|
||||
this.#loaded = true;
|
||||
this.#emitter.count += 1;
|
||||
for (const sig of signals) try {
|
||||
const fn = this.#sigListeners[sig];
|
||||
if (fn) this.#process.on(sig, fn);
|
||||
} catch (_) {}
|
||||
this.#process.emit = (ev, ...a) => {
|
||||
return this.#processEmit(ev, ...a);
|
||||
};
|
||||
this.#process.reallyExit = (code) => {
|
||||
return this.#processReallyExit(code);
|
||||
};
|
||||
}
|
||||
unload() {
|
||||
if (!this.#loaded) return;
|
||||
this.#loaded = false;
|
||||
signals.forEach((sig) => {
|
||||
const listener = this.#sigListeners[sig];
|
||||
/* c8 ignore start */
|
||||
if (!listener) throw new Error("Listener not defined for signal: " + sig);
|
||||
/* c8 ignore stop */
|
||||
try {
|
||||
this.#process.removeListener(sig, listener);
|
||||
} catch (_) {}
|
||||
/* c8 ignore stop */
|
||||
});
|
||||
this.#process.emit = this.#originalProcessEmit;
|
||||
this.#process.reallyExit = this.#originalProcessReallyExit;
|
||||
this.#emitter.count -= 1;
|
||||
}
|
||||
#processReallyExit(code) {
|
||||
/* c8 ignore start */
|
||||
if (!processOk(this.#process)) return 0;
|
||||
this.#process.exitCode = code || 0;
|
||||
/* c8 ignore stop */
|
||||
this.#emitter.emit("exit", this.#process.exitCode, null);
|
||||
return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
|
||||
}
|
||||
#processEmit(ev, ...args) {
|
||||
const og = this.#originalProcessEmit;
|
||||
if (ev === "exit" && processOk(this.#process)) {
|
||||
if (typeof args[0] === "number") this.#process.exitCode = args[0];
|
||||
/* c8 ignore start */
|
||||
const ret = og.call(this.#process, ev, ...args);
|
||||
/* c8 ignore start */
|
||||
this.#emitter.emit("exit", this.#process.exitCode, null);
|
||||
/* c8 ignore stop */
|
||||
return ret;
|
||||
} else return og.call(this.#process, ev, ...args);
|
||||
}
|
||||
};
|
||||
const process$1 = globalThis.process;
|
||||
const { onExit: onExit$1, load, unload } = signalExitWrap(processOk(process$1) ? new SignalExit(process$1) : new SignalExitFallback());
|
||||
|
||||
//#endregion
|
||||
//#region src/utils/signal-exit.ts
|
||||
function onExit(...args) {
|
||||
if (typeof process === "object" && process.versions.webcontainer) {
|
||||
process.on("exit", (code) => {
|
||||
args[0](code, null);
|
||||
});
|
||||
return;
|
||||
}
|
||||
onExit$1(...args);
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/api/watch/watch-emitter.ts
|
||||
var import_binding = /* @__PURE__ */ __toESM(require_binding());
|
||||
var WatcherEmitter = class {
|
||||
listeners = /* @__PURE__ */ new Map();
|
||||
timer;
|
||||
constructor() {
|
||||
this.timer = setInterval(() => {}, 1e9);
|
||||
}
|
||||
on(event, listener) {
|
||||
const listeners = this.listeners.get(event);
|
||||
if (listeners) listeners.push(listener);
|
||||
else this.listeners.set(event, [listener]);
|
||||
return this;
|
||||
}
|
||||
off(event, listener) {
|
||||
const listeners = this.listeners.get(event);
|
||||
if (listeners) {
|
||||
const index = listeners.indexOf(listener);
|
||||
if (index !== -1) listeners.splice(index, 1);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
clear(event) {
|
||||
if (this.listeners.has(event)) this.listeners.delete(event);
|
||||
}
|
||||
async onEvent(event) {
|
||||
const listeners = this.listeners.get(event.eventKind());
|
||||
if (listeners) switch (event.eventKind()) {
|
||||
case "close":
|
||||
case "restart":
|
||||
for (const listener of listeners) await listener();
|
||||
break;
|
||||
case "event":
|
||||
for (const listener of listeners) {
|
||||
const code = event.bundleEventKind();
|
||||
switch (code) {
|
||||
case "BUNDLE_END":
|
||||
const { duration, output, result } = event.bundleEndData();
|
||||
await listener({
|
||||
code: "BUNDLE_END",
|
||||
duration,
|
||||
output: [output],
|
||||
result
|
||||
});
|
||||
break;
|
||||
case "ERROR":
|
||||
const data = event.bundleErrorData();
|
||||
await listener({
|
||||
code: "ERROR",
|
||||
error: aggregateBindingErrorsIntoJsError(data.error),
|
||||
result: data.result
|
||||
});
|
||||
break;
|
||||
default:
|
||||
await listener({ code });
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "change":
|
||||
for (const listener of listeners) {
|
||||
const { path, kind } = event.watchChangeData();
|
||||
await listener(path, { event: kind });
|
||||
}
|
||||
break;
|
||||
default: throw new Error(`Unknown event: ${event}`);
|
||||
}
|
||||
}
|
||||
async close() {
|
||||
clearInterval(this.timer);
|
||||
}
|
||||
};
|
||||
|
||||
//#endregion
|
||||
//#region src/api/watch/watcher.ts
|
||||
var Watcher = class {
|
||||
closed;
|
||||
inner;
|
||||
emitter;
|
||||
stopWorkers;
|
||||
constructor(emitter, inner, stopWorkers) {
|
||||
this.closed = false;
|
||||
this.inner = inner;
|
||||
this.emitter = emitter;
|
||||
const originClose = emitter.close.bind(emitter);
|
||||
emitter.close = async () => {
|
||||
await this.close();
|
||||
originClose();
|
||||
};
|
||||
this.stopWorkers = stopWorkers;
|
||||
}
|
||||
async close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
for (const stop of this.stopWorkers) await stop?.();
|
||||
await this.inner.close();
|
||||
(0, import_binding.shutdownAsyncRuntime)();
|
||||
}
|
||||
start() {
|
||||
process.nextTick(() => this.inner.start(this.emitter.onEvent.bind(this.emitter)));
|
||||
}
|
||||
};
|
||||
async function createWatcher(emitter, input) {
|
||||
const options = arraify(input);
|
||||
const bundlerOptions = await Promise.all(options.map((option) => arraify(option.output || {}).map(async (output) => {
|
||||
return createBundlerOptions(await PluginDriver.callOptionsHook(option, true), output, true);
|
||||
})).flat());
|
||||
const notifyOptions = getValidNotifyOption(bundlerOptions);
|
||||
new Watcher(emitter, new import_binding.BindingWatcher(bundlerOptions.map((option) => option.bundlerOptions), notifyOptions), bundlerOptions.map((option) => option.stopWorkers)).start();
|
||||
}
|
||||
function getValidNotifyOption(bundlerOptions) {
|
||||
let result;
|
||||
for (const option of bundlerOptions) if (option.inputOptions.watch) {
|
||||
const notifyOption = option.inputOptions.watch.notify;
|
||||
if (notifyOption) if (result) {
|
||||
option.onLog(LOG_LEVEL_WARN, logMultiplyNotifyOption());
|
||||
return result;
|
||||
} else result = notifyOption;
|
||||
}
|
||||
}
|
||||
|
||||
//#endregion
|
||||
//#region src/api/watch/index.ts
|
||||
/**
|
||||
* The API compatible with Rollup's `watch` function.
|
||||
*
|
||||
* This function will rebuild the bundle when it detects that the individual modules have changed on disk.
|
||||
*
|
||||
* Note that when using this function, it is your responsibility to call `event.result.close()` in response to the `BUNDLE_END` event to avoid resource leaks.
|
||||
*
|
||||
* @param input The watch options object or the list of them.
|
||||
* @returns A watcher object.
|
||||
*
|
||||
* @example
|
||||
* ```js
|
||||
* import { watch } from 'rolldown';
|
||||
*
|
||||
* const watcher = watch({ /* ... *\/ });
|
||||
* watcher.on('event', (event) => {
|
||||
* if (event.code === 'BUNDLE_END') {
|
||||
* console.log(event.duration);
|
||||
* event.result.close();
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* // Stop watching
|
||||
* watcher.close();
|
||||
* ```
|
||||
*
|
||||
* @experimental
|
||||
* @category Programmatic APIs
|
||||
*/
|
||||
function watch(input) {
|
||||
const emitter = new WatcherEmitter();
|
||||
createWatcher(emitter, input);
|
||||
return emitter;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
export { onExit as n, watch as t };
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { I as ParseResult, L as ParserOptions, P as MinifyResult, U as TsconfigCache, _ as BindingTsconfigRawOptions, a as BindingEnhancedTransformOptions, g as BindingTsconfigCompilerOptions } from "./shared/binding-BLUhc7Nl.mjs";
|
||||
import { a as minify, c as parseSync, i as MinifyOptions, n as transform, o as minifySync, r as transformSync, s as parse, t as TransformResult } from "./shared/transform-CfCvdTIT.mjs";
|
||||
export { type MinifyOptions, type MinifyResult, type ParseResult, type ParserOptions, type BindingEnhancedTransformOptions as TransformOptions, type TransformResult, TsconfigCache, type BindingTsconfigCompilerOptions as TsconfigCompilerOptions, type BindingTsconfigRawOptions as TsconfigRawOptions, minify, minifySync, parse, parseSync, transform, transformSync };
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import "./shared/binding-DzKFaUu2.mjs";
|
||||
import "./shared/error-DC8XkJKP.mjs";
|
||||
import { n as parseSync, t as parse } from "./shared/parse-DIfx5aEh.mjs";
|
||||
import { a as minifySync, i as minify, n as transform, r as transformSync, t as import_binding } from "./shared/transform-BRmOyKcA.mjs";
|
||||
|
||||
var TsconfigCache = import_binding.TsconfigCache;
|
||||
export { TsconfigCache, minify, minifySync, parse, parseSync, transform, transformSync };
|
||||
Reference in New Issue
Block a user