2603 lines
102 KiB
JavaScript
2603 lines
102 KiB
JavaScript
import { n as __toESM, t as require_binding } from "./binding-B4m_2rFW.mjs";
|
||
import { i as logFailedValidation, n as error, o as logInvalidLogPosition, r as logCycleLoading, t as augmentCodeLocation, u as logPluginError } from "./logs-D6uA606S.mjs";
|
||
import { i as bindingifyManifestPlugin, n as BuiltinPlugin, r as bindingifyBuiltInPlugin, t as normalizedStringOrRegex } from "./normalize-string-or-regex-xyy0kCQR.mjs";
|
||
import { i as noop, n as isPathFragment, o as unreachable, s as unsupported, t as arraify } from "./misc-DOSKtd97.mjs";
|
||
import { a as bindingifySourcemap, i as unwrapBindingResult, t as aggregateBindingErrorsIntoJsError } from "./error-Bj1xBdEY.mjs";
|
||
import { parseAst } from "../parse-ast-index.mjs";
|
||
import path from "node:path";
|
||
import * as filter from "@rolldown/pluginutils";
|
||
import fsp from "node:fs/promises";
|
||
//#region package.json
|
||
var version = "1.2.12";
|
||
var package_default = {
|
||
name: "rolldown",
|
||
version,
|
||
description: "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.",
|
||
keywords: [
|
||
"bundler",
|
||
"esbuild",
|
||
"parcel",
|
||
"rolldown",
|
||
"rollup",
|
||
"webpack"
|
||
],
|
||
homepage: "https://rolldown.rs/",
|
||
bugs: { "url": "https://github.com/rolldown/rolldown/issues" },
|
||
license: "MIT",
|
||
repository: {
|
||
"type": "git",
|
||
"url": "git+https://github.com/rolldown/rolldown.git",
|
||
"directory": "packages/rolldown"
|
||
},
|
||
bin: { "rolldown": "./bin/cli.mjs" },
|
||
files: [
|
||
"bin",
|
||
"cli",
|
||
"dist",
|
||
"LICENSE",
|
||
"THIRD-PARTY-LICENSE",
|
||
"!dist/*.node"
|
||
],
|
||
type: "module",
|
||
main: "./dist/index.mjs",
|
||
module: "./dist/index.mjs",
|
||
types: "./dist/index.d.mts",
|
||
imports: { "#parallel-plugin-worker": "./dist/parallel-plugin-worker.mjs" },
|
||
exports: {
|
||
".": {
|
||
"dev": "./src/index.ts",
|
||
"default": "./dist/index.mjs"
|
||
},
|
||
"./config": {
|
||
"dev": "./src/config.ts",
|
||
"default": "./dist/config.mjs"
|
||
},
|
||
"./experimental": {
|
||
"dev": "./src/experimental-index.ts",
|
||
"default": "./dist/experimental-index.mjs"
|
||
},
|
||
"./experimental/runtime-types": { "types": "./dist/experimental-runtime-types.d.ts" },
|
||
"./experimental/runtime": {
|
||
"types": "./dist/experimental-runtime.d.ts",
|
||
"default": "./dist/experimental-runtime.mjs"
|
||
},
|
||
"./filter": {
|
||
"dev": "./src/filter-index.ts",
|
||
"default": "./dist/filter-index.mjs"
|
||
},
|
||
"./getLogFilter": {
|
||
"dev": "./src/get-log-filter.ts",
|
||
"default": "./dist/get-log-filter.mjs"
|
||
},
|
||
"./parallelPlugin": {
|
||
"dev": "./src/parallel-plugin.ts",
|
||
"default": "./dist/parallel-plugin.mjs"
|
||
},
|
||
"./parseAst": {
|
||
"dev": "./src/parse-ast-index.ts",
|
||
"default": "./dist/parse-ast-index.mjs"
|
||
},
|
||
"./package.json": "./package.json",
|
||
"./plugins": {
|
||
"dev": "./src/plugins-index.ts",
|
||
"default": "./dist/plugins-index.mjs"
|
||
},
|
||
"./utils": {
|
||
"dev": "./src/utils-index.ts",
|
||
"default": "./dist/utils-index.mjs"
|
||
}
|
||
},
|
||
publishConfig: {
|
||
"exports": {
|
||
".": "./dist/index.mjs",
|
||
"./config": "./dist/config.mjs",
|
||
"./experimental": "./dist/experimental-index.mjs",
|
||
"./experimental/runtime-types": { "types": "./dist/experimental-runtime-types.d.ts" },
|
||
"./experimental/runtime": {
|
||
"types": "./dist/experimental-runtime.d.ts",
|
||
"default": "./dist/experimental-runtime.mjs"
|
||
},
|
||
"./filter": "./dist/filter-index.mjs",
|
||
"./getLogFilter": "./dist/get-log-filter.mjs",
|
||
"./parallelPlugin": "./dist/parallel-plugin.mjs",
|
||
"./parseAst": "./dist/parse-ast-index.mjs",
|
||
"./package.json": "./package.json",
|
||
"./plugins": "./dist/plugins-index.mjs",
|
||
"./utils": "./dist/utils-index.mjs"
|
||
},
|
||
"access": "public",
|
||
"registry": "https://registry.npmjs.org/"
|
||
},
|
||
scripts: {
|
||
"# Scrips for binding #": "_",
|
||
"artifacts": "napi artifacts --cwd ./src --package-json-path ../package.json -o=../artifacts --npm-dir ../npm",
|
||
"build-binding": "oxnode ./build-binding.ts",
|
||
"build-binding:release": "pnpm build-binding --release",
|
||
"build-binding:profile": "pnpm build-binding --profile profile --features chrome-tracing",
|
||
"build-binding:wasi": "pnpm build-binding --target wasm32-wasip1-threads",
|
||
"build-binding:wasi:release": "pnpm build-binding --profile release-wasi --target wasm32-wasip1-threads",
|
||
"# Scrips for node #": "_",
|
||
"build-node": "node --enable-source-maps --import @oxc-node/core/register -C dev ./build.ts",
|
||
"build-types-check": "tsc -p ./tsconfig.check.json",
|
||
"build-js-glue": "pnpm run --sequential '/^build-(node|types-check)$/'",
|
||
"build-native:debug": "pnpm run --sequential '/^build-(binding|js-glue)$/'",
|
||
"build-native:release": "pnpm run --sequential '/^build-(binding:release|js-glue)$/'",
|
||
"build-native:profile": "pnpm run build-binding:profile && pnpm run build-js-glue",
|
||
"build-native:memory-profile": "pnpm run build-binding:profile --features default_global_allocator && pnpm run build-js-glue",
|
||
"build-wasi:debug": "TARGET='rolldown-wasi' pnpm run --sequential '/^build-(binding|binding:wasi|node)$/'",
|
||
"build-wasi:release": "TARGET='rolldown-wasi' pnpm run --sequential '/^build-(binding|binding:wasi:release|node)$/'",
|
||
"build-browser-pkg:debug": "TARGET='browser' pnpm run --sequential '/^build-(binding:wasi|node)$/'",
|
||
"build-browser-pkg:release": "TARGET='browser' pnpm run --sequential '/^build-(binding:wasi:release|node)$/'",
|
||
"# Scrips for docs #": "_",
|
||
"prepublishOnly": "napi pre-publish -t npm --no-gh-release ${NAPI_DRY_RUN:+--dry-run} ${NAPI_SKIP_OPTIONAL_PUBLISH:+--skip-optional-publish}",
|
||
"publint": "publint ."
|
||
},
|
||
dependencies: {
|
||
"@oxc-project/types": "catalog:",
|
||
"@rolldown/pluginutils": "catalog:"
|
||
},
|
||
devDependencies: {
|
||
"@emnapi/core": "catalog:",
|
||
"@emnapi/runtime": "catalog:",
|
||
"@napi-rs/cli": "catalog:",
|
||
"@napi-rs/wasm-runtime": "catalog:",
|
||
"@oxc-node/cli": "catalog:",
|
||
"cac": "catalog:",
|
||
"consola": "catalog:",
|
||
"emnapi": "catalog:",
|
||
"execa": "catalog:",
|
||
"fresh-import": "catalog:",
|
||
"glob": "catalog:",
|
||
"oxc-parser": "catalog:",
|
||
"pathe": "catalog:",
|
||
"remeda": "catalog:",
|
||
"rolldown": "workspace:*",
|
||
"rolldown-plugin-dts": "catalog:",
|
||
"rollup": "catalog:",
|
||
"signal-exit": "catalog:",
|
||
"source-map": "catalog:",
|
||
"typescript": "catalog:",
|
||
"valibot": "catalog:"
|
||
},
|
||
napi: {
|
||
"binaryName": "rolldown-binding",
|
||
"dtsHeader": "type MaybePromise<T> = T | Promise<T>\ntype Nullable<T> = T | null | undefined\ntype VoidNullable<T = void> = T | null | undefined | void\nexport type BindingStringOrRegex = string | RegExp\nexport type BindingResult<T> = { errors: BindingError[], isBindingErrors: boolean } | T\n\n",
|
||
"packageName": "@rolldown/binding",
|
||
"targets": [
|
||
"aarch64-apple-darwin",
|
||
"aarch64-linux-android",
|
||
"aarch64-pc-windows-msvc",
|
||
"aarch64-unknown-linux-gnu",
|
||
"aarch64-unknown-linux-musl",
|
||
"aarch64-unknown-linux-ohos",
|
||
"armv7-linux-androideabi",
|
||
"armv7-unknown-linux-gnueabihf",
|
||
"powerpc64le-unknown-linux-gnu",
|
||
"s390x-unknown-linux-gnu",
|
||
"wasm32-wasip1-threads",
|
||
"x86_64-apple-darwin",
|
||
"x86_64-pc-windows-msvc",
|
||
"x86_64-unknown-freebsd",
|
||
"x86_64-unknown-linux-gnu",
|
||
"x86_64-unknown-linux-musl"
|
||
],
|
||
"wasm": {
|
||
"initialMemory": 16384,
|
||
"browser": {
|
||
"fs": true,
|
||
"asyncInit": true,
|
||
"errorEvent": true
|
||
}
|
||
}
|
||
},
|
||
engines: { "node": "^20.19.0 || >=22.12.0" }
|
||
};
|
||
//#endregion
|
||
//#region src/constants/version.ts
|
||
/**
|
||
* The version of Rolldown.
|
||
* @example `'1.0.0'`
|
||
*
|
||
* @category Plugin APIs
|
||
*/
|
||
const VERSION = version;
|
||
//#endregion
|
||
//#region src/log/logging.ts
|
||
const LOG_LEVEL_SILENT = "silent";
|
||
const LOG_LEVEL_ERROR = "error";
|
||
const LOG_LEVEL_WARN = "warn";
|
||
const LOG_LEVEL_INFO = "info";
|
||
const LOG_LEVEL_DEBUG = "debug";
|
||
const logLevelPriority = {
|
||
[LOG_LEVEL_DEBUG]: 0,
|
||
[LOG_LEVEL_INFO]: 1,
|
||
[LOG_LEVEL_WARN]: 2,
|
||
[LOG_LEVEL_SILENT]: 3
|
||
};
|
||
//#endregion
|
||
//#region src/log/log-handler.ts
|
||
const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
|
||
function getLogHandler(level, code, logger, pluginName, logLevel) {
|
||
if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
|
||
return (log, pos) => {
|
||
if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
|
||
log = normalizeLog(log);
|
||
if (log.code && !log.pluginCode) log.pluginCode = log.code;
|
||
log.code = code;
|
||
log.plugin = pluginName;
|
||
logger(level, log);
|
||
};
|
||
}
|
||
//#endregion
|
||
//#region src/utils/normalize-hook.ts
|
||
function normalizeHook(hook) {
|
||
if (typeof hook === "function" || typeof hook === "string") return {
|
||
handler: hook,
|
||
options: {},
|
||
meta: {}
|
||
};
|
||
if (typeof hook === "object" && hook !== null) {
|
||
const { handler, order, ...options } = hook;
|
||
return {
|
||
handler,
|
||
options,
|
||
meta: { order }
|
||
};
|
||
}
|
||
unreachable("Invalid hook type");
|
||
}
|
||
//#endregion
|
||
//#region src/utils/parallel-plugin.ts
|
||
/**
|
||
* Returns the `_parallel` marker of a parallel plugin, or `undefined` if the
|
||
* given plugin is not one.
|
||
*
|
||
* Detection is descriptor-based instead of using the `in` operator: only an
|
||
* own data property named `_parallel` with the expected shape counts. This
|
||
* avoids false positives from inherited or accessor `_parallel` properties on
|
||
* regular plugins, and guarantees that callers can safely read `fileUrl` and
|
||
* `options` from the returned value.
|
||
*/
|
||
function getParallelPluginInfo(plugin) {
|
||
if (plugin === null || typeof plugin !== "object") return;
|
||
const descriptor = Object.getOwnPropertyDescriptor(plugin, "_parallel");
|
||
if (!descriptor || !("value" in descriptor)) return;
|
||
const parallel = descriptor.value;
|
||
if (parallel === null || typeof parallel !== "object" || typeof parallel.fileUrl !== "string") return;
|
||
return parallel;
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/minimal-plugin-context.ts
|
||
var MinimalPluginContextImpl = class {
|
||
pluginName;
|
||
hookName;
|
||
info;
|
||
warn;
|
||
debug;
|
||
meta;
|
||
constructor(onLog, logLevel, pluginName, watchMode, hookName) {
|
||
this.pluginName = pluginName;
|
||
this.hookName = hookName;
|
||
this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
|
||
this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
|
||
this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
|
||
this.meta = {
|
||
rollupVersion: "4.23.0",
|
||
rolldownVersion: VERSION,
|
||
watchMode
|
||
};
|
||
}
|
||
error(e) {
|
||
return error(logPluginError(normalizeLog(e), this.pluginName, { hook: this.hookName }));
|
||
}
|
||
};
|
||
//#endregion
|
||
//#region src/types/plain-object-like.ts
|
||
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
|
||
const LAZY_FIELDS_KEY = Symbol("__lazy_fields__");
|
||
/**
|
||
* Base class for classes that use `@lazyProp` decorated properties.
|
||
*
|
||
* **Design Pattern in Rolldown:**
|
||
* This is a common pattern in Rolldown due to its three-layer architecture:
|
||
* TypeScript API → NAPI Bindings → Rust Core
|
||
*
|
||
* **Why we use getters:**
|
||
* For performance - to lazily fetch data from Rust bindings only when needed,
|
||
* rather than eagerly fetching all data during object construction.
|
||
*
|
||
* **The problem:**
|
||
* Getters defined on class prototypes are non-enumerable by default, which breaks:
|
||
* - Object spread operators ({...obj})
|
||
* - Object.keys() and similar methods
|
||
* - Standard JavaScript object semantics
|
||
*
|
||
* **The solution:**
|
||
* This base class automatically converts `@lazyProp` decorated getters into
|
||
* own enumerable getters on each instance during construction.
|
||
*
|
||
* **Result:**
|
||
* Objects get both lazy-loading performance benefits AND plain JavaScript object behavior.
|
||
*
|
||
* @example
|
||
* ```typescript
|
||
* class MyClass extends PlainObjectLike {
|
||
* @lazyProp
|
||
* get myProp() {
|
||
* return fetchFromRustBinding();
|
||
* }
|
||
* }
|
||
* ```
|
||
*/
|
||
var PlainObjectLike = class {
|
||
constructor() {
|
||
setupLazyProperties(this);
|
||
}
|
||
};
|
||
/**
|
||
* Set up lazy properties as own getters on an instance.
|
||
* This is called automatically by the `PlainObjectLike` base class constructor.
|
||
*
|
||
* @param instance - The instance to set up lazy properties on
|
||
* @internal
|
||
*/
|
||
function setupLazyProperties(instance) {
|
||
const lazyFields = instance.constructor[LAZY_FIELDS_KEY];
|
||
if (!lazyFields) return;
|
||
for (const [propertyKey, originalGetter] of lazyFields.entries()) {
|
||
let cachedValue;
|
||
let hasValue = false;
|
||
Object.defineProperty(instance, propertyKey, {
|
||
get() {
|
||
if (!hasValue) {
|
||
cachedValue = originalGetter.call(this);
|
||
hasValue = true;
|
||
}
|
||
return cachedValue;
|
||
},
|
||
enumerable: true,
|
||
configurable: true
|
||
});
|
||
}
|
||
}
|
||
/**
|
||
* Get all lazy field names from a class instance.
|
||
*
|
||
* @param instance - Instance to inspect
|
||
* @returns Set of lazy property names
|
||
*/
|
||
function getLazyFields(instance) {
|
||
const lazyFields = instance.constructor[LAZY_FIELDS_KEY];
|
||
return lazyFields ? new Set(lazyFields.keys()) : /* @__PURE__ */ new Set();
|
||
}
|
||
//#endregion
|
||
//#region src/decorators/lazy.ts
|
||
/**
|
||
* Decorator that marks a getter as lazy-evaluated and cached.
|
||
*
|
||
* **What "lazy" means here:**
|
||
* 1. Data is lazily fetched from Rust bindings only when the property is accessed (not eagerly on construction)
|
||
* 2. Once fetched, the data is cached for subsequent accesses (performance optimization)
|
||
* 3. Despite being a getter, it behaves like a plain object property (enumerable, appears in Object.keys())
|
||
*
|
||
* **Important**: Properties decorated with `@lazyProp` are defined as own enumerable
|
||
* properties on each instance (not on the prototype). This ensures they:
|
||
* - Appear in Object.keys() and Object.getOwnPropertyNames()
|
||
* - Are included in object spreads ({...obj})
|
||
* - Are enumerable in for...in loops
|
||
*
|
||
* Classes using this decorator must extend `PlainObjectLike` base class.
|
||
*
|
||
* @example
|
||
* ```typescript
|
||
* class MyClass extends PlainObjectLike {
|
||
* @lazyProp
|
||
* get expensiveValue() {
|
||
* return someExpensiveComputation();
|
||
* }
|
||
* }
|
||
* ```
|
||
*/
|
||
function lazyProp(target, propertyKey, descriptor) {
|
||
if (!target.constructor[LAZY_FIELDS_KEY]) target.constructor[LAZY_FIELDS_KEY] = /* @__PURE__ */ new Map();
|
||
const originalGetter = descriptor.get;
|
||
target.constructor[LAZY_FIELDS_KEY].set(propertyKey, originalGetter);
|
||
return {
|
||
enumerable: false,
|
||
configurable: true
|
||
};
|
||
}
|
||
//#endregion
|
||
//#region src/utils/asset-source.ts
|
||
function transformAssetSource(bindingAssetSource) {
|
||
return bindingAssetSource.inner;
|
||
}
|
||
function bindingAssetSource(source) {
|
||
return { inner: source };
|
||
}
|
||
//#endregion
|
||
//#region \0@oxc-project+runtime@0.152.0/helpers/esm/decorate.js
|
||
function __decorate(decorators, target, key, desc) {
|
||
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
||
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
||
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
||
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
||
}
|
||
//#endregion
|
||
//#region src/types/output-asset-impl.ts
|
||
var OutputAssetImpl = class extends PlainObjectLike {
|
||
bindingAsset;
|
||
type = "asset";
|
||
constructor(bindingAsset) {
|
||
super();
|
||
this.bindingAsset = bindingAsset;
|
||
}
|
||
get fileName() {
|
||
return this.bindingAsset.getFileName();
|
||
}
|
||
get originalFileName() {
|
||
return this.bindingAsset.getOriginalFileName() || null;
|
||
}
|
||
get originalFileNames() {
|
||
return this.bindingAsset.getOriginalFileNames();
|
||
}
|
||
get name() {
|
||
return this.bindingAsset.getName() ?? void 0;
|
||
}
|
||
get names() {
|
||
return this.bindingAsset.getNames();
|
||
}
|
||
get source() {
|
||
return transformAssetSource(this.bindingAsset.getSource());
|
||
}
|
||
__rolldown_external_memory_handle__(keepDataAlive) {
|
||
if (keepDataAlive) this.#evaluateAllLazyFields();
|
||
return this.bindingAsset.dropInner();
|
||
}
|
||
#evaluateAllLazyFields() {
|
||
for (const field of getLazyFields(this)) this[field];
|
||
}
|
||
};
|
||
__decorate([lazyProp], OutputAssetImpl.prototype, "fileName", null);
|
||
__decorate([lazyProp], OutputAssetImpl.prototype, "originalFileName", null);
|
||
__decorate([lazyProp], OutputAssetImpl.prototype, "originalFileNames", null);
|
||
__decorate([lazyProp], OutputAssetImpl.prototype, "name", null);
|
||
__decorate([lazyProp], OutputAssetImpl.prototype, "names", null);
|
||
__decorate([lazyProp], OutputAssetImpl.prototype, "source", null);
|
||
//#endregion
|
||
//#region src/utils/transform-rendered-module.ts
|
||
function transformToRenderedModule(bindingRenderedModule) {
|
||
return {
|
||
get code() {
|
||
return bindingRenderedModule.code;
|
||
},
|
||
get renderedLength() {
|
||
return bindingRenderedModule.code?.length || 0;
|
||
},
|
||
get renderedExports() {
|
||
return bindingRenderedModule.renderedExports;
|
||
}
|
||
};
|
||
}
|
||
//#endregion
|
||
//#region src/utils/transform-rendered-chunk.ts
|
||
function transformRenderedChunk(chunk) {
|
||
let modules = null;
|
||
return {
|
||
type: "chunk",
|
||
get name() {
|
||
return chunk.name;
|
||
},
|
||
get isEntry() {
|
||
return chunk.isEntry;
|
||
},
|
||
get isDynamicEntry() {
|
||
return chunk.isDynamicEntry;
|
||
},
|
||
get facadeModuleId() {
|
||
return chunk.facadeModuleId;
|
||
},
|
||
get moduleIds() {
|
||
return chunk.moduleIds;
|
||
},
|
||
get exports() {
|
||
return chunk.exports;
|
||
},
|
||
get fileName() {
|
||
return chunk.fileName;
|
||
},
|
||
get imports() {
|
||
return chunk.imports;
|
||
},
|
||
get dynamicImports() {
|
||
return chunk.dynamicImports;
|
||
},
|
||
get modules() {
|
||
if (!modules) modules = transformChunkModules(chunk.modules);
|
||
return modules;
|
||
}
|
||
};
|
||
}
|
||
function transformChunkModules(modules) {
|
||
const result = {};
|
||
for (let i = 0; i < modules.values.length; i++) {
|
||
let key = modules.keys[i];
|
||
const mod = modules.values[i];
|
||
result[key] = transformToRenderedModule(mod);
|
||
}
|
||
return result;
|
||
}
|
||
//#endregion
|
||
//#region src/types/output-chunk-impl.ts
|
||
var OutputChunkImpl = class extends PlainObjectLike {
|
||
bindingChunk;
|
||
type = "chunk";
|
||
constructor(bindingChunk) {
|
||
super();
|
||
this.bindingChunk = bindingChunk;
|
||
}
|
||
get fileName() {
|
||
return this.bindingChunk.getFileName();
|
||
}
|
||
get name() {
|
||
return this.bindingChunk.getName();
|
||
}
|
||
get exports() {
|
||
return this.bindingChunk.getExports();
|
||
}
|
||
get isEntry() {
|
||
return this.bindingChunk.getIsEntry();
|
||
}
|
||
get facadeModuleId() {
|
||
return this.bindingChunk.getFacadeModuleId() || null;
|
||
}
|
||
get isDynamicEntry() {
|
||
return this.bindingChunk.getIsDynamicEntry();
|
||
}
|
||
get sourcemapFileName() {
|
||
return this.bindingChunk.getSourcemapFileName() || null;
|
||
}
|
||
get preliminaryFileName() {
|
||
return this.bindingChunk.getPreliminaryFileName();
|
||
}
|
||
get code() {
|
||
return this.bindingChunk.getCode();
|
||
}
|
||
get modules() {
|
||
return transformChunkModules(this.bindingChunk.getModules());
|
||
}
|
||
get imports() {
|
||
return this.bindingChunk.getImports();
|
||
}
|
||
get dynamicImports() {
|
||
return this.bindingChunk.getDynamicImports();
|
||
}
|
||
get moduleIds() {
|
||
return this.bindingChunk.getModuleIds();
|
||
}
|
||
get map() {
|
||
const mapString = this.bindingChunk.getMap();
|
||
return mapString ? transformToRollupSourceMap(mapString) : null;
|
||
}
|
||
__rolldown_external_memory_handle__(keepDataAlive) {
|
||
if (keepDataAlive) this.#evaluateAllLazyFields();
|
||
return this.bindingChunk.dropInner();
|
||
}
|
||
#evaluateAllLazyFields() {
|
||
for (const field of getLazyFields(this)) this[field];
|
||
}
|
||
};
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "fileName", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "name", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "exports", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "isEntry", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "facadeModuleId", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "isDynamicEntry", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "sourcemapFileName", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "preliminaryFileName", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "code", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "modules", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "imports", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "dynamicImports", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "moduleIds", null);
|
||
__decorate([lazyProp], OutputChunkImpl.prototype, "map", null);
|
||
//#endregion
|
||
//#region src/utils/transform-to-rollup-output.ts
|
||
function transformToRollupSourceMap(map) {
|
||
const obj = {
|
||
...JSON.parse(map),
|
||
toString() {
|
||
return JSON.stringify(obj);
|
||
},
|
||
toUrl() {
|
||
return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
|
||
}
|
||
};
|
||
Object.defineProperty(obj, "x_google_ignoreList", {
|
||
get: () => obj.ignoreList,
|
||
set: (value) => {
|
||
obj.ignoreList = value;
|
||
}
|
||
});
|
||
return obj;
|
||
}
|
||
function transformToRollupOutputChunk(bindingChunk) {
|
||
return new OutputChunkImpl(bindingChunk);
|
||
}
|
||
function transformToMutableRollupOutputChunk(bindingChunk, changed) {
|
||
const chunk = {
|
||
type: "chunk",
|
||
get code() {
|
||
return bindingChunk.getCode();
|
||
},
|
||
fileName: bindingChunk.getFileName(),
|
||
name: bindingChunk.getName(),
|
||
get modules() {
|
||
return transformChunkModules(bindingChunk.getModules());
|
||
},
|
||
get imports() {
|
||
return bindingChunk.getImports();
|
||
},
|
||
get dynamicImports() {
|
||
return bindingChunk.getDynamicImports();
|
||
},
|
||
exports: bindingChunk.getExports(),
|
||
isEntry: bindingChunk.getIsEntry(),
|
||
facadeModuleId: bindingChunk.getFacadeModuleId() || null,
|
||
isDynamicEntry: bindingChunk.getIsDynamicEntry(),
|
||
get moduleIds() {
|
||
return bindingChunk.getModuleIds();
|
||
},
|
||
get map() {
|
||
const map = bindingChunk.getMap();
|
||
return map ? transformToRollupSourceMap(map) : null;
|
||
},
|
||
sourcemapFileName: bindingChunk.getSourcemapFileName() || null,
|
||
preliminaryFileName: bindingChunk.getPreliminaryFileName()
|
||
};
|
||
const cache = {};
|
||
return new Proxy(chunk, {
|
||
get(target, p) {
|
||
if (p in cache) return cache[p];
|
||
const value = target[p];
|
||
cache[p] = value;
|
||
return value;
|
||
},
|
||
set(_target, p, newValue) {
|
||
cache[p] = newValue;
|
||
changed.updated.add(bindingChunk.getFileName());
|
||
return true;
|
||
},
|
||
has(target, p) {
|
||
if (p in cache) return true;
|
||
return p in target;
|
||
}
|
||
});
|
||
}
|
||
function transformToRollupOutputAsset(bindingAsset) {
|
||
return new OutputAssetImpl(bindingAsset);
|
||
}
|
||
function transformToMutableRollupOutputAsset(bindingAsset, changed) {
|
||
const asset = {
|
||
type: "asset",
|
||
fileName: bindingAsset.getFileName(),
|
||
originalFileName: bindingAsset.getOriginalFileName() || null,
|
||
originalFileNames: bindingAsset.getOriginalFileNames(),
|
||
get source() {
|
||
return transformAssetSource(bindingAsset.getSource());
|
||
},
|
||
name: bindingAsset.getName() ?? void 0,
|
||
names: bindingAsset.getNames()
|
||
};
|
||
const cache = {};
|
||
return new Proxy(asset, {
|
||
get(target, p) {
|
||
if (p in cache) return cache[p];
|
||
const value = target[p];
|
||
cache[p] = value;
|
||
return value;
|
||
},
|
||
set(_target, p, newValue) {
|
||
cache[p] = newValue;
|
||
changed.updated.add(bindingAsset.getFileName());
|
||
return true;
|
||
}
|
||
});
|
||
}
|
||
function transformToRollupOutput(output) {
|
||
const { chunks, assets } = output;
|
||
const transformed = { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk)), ...assets.map((asset) => transformToRollupOutputAsset(asset))] };
|
||
if (output.mangleCache !== void 0) transformed.mangleCache = output.mangleCache;
|
||
return transformed;
|
||
}
|
||
function transformToMutableRollupOutput(output, changed) {
|
||
const { chunks, assets } = output;
|
||
return { output: [...chunks.map((chunk) => transformToMutableRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToMutableRollupOutputAsset(asset, changed))] };
|
||
}
|
||
function transformToOutputBundle(context, output, changed) {
|
||
const bundle = Object.fromEntries(transformToMutableRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
|
||
return new Proxy(bundle, {
|
||
set(_target, _p, _newValue, _receiver) {
|
||
const originalStackTraceLimit = Error.stackTraceLimit;
|
||
Error.stackTraceLimit = 2;
|
||
const message = "This plugin assigns to bundle variable. This is discouraged by Rollup and is not supported by Rolldown. This will be ignored. https://rollupjs.org/plugin-development/#generatebundle:~:text=DANGER,this.emitFile.";
|
||
const stack = (/* @__PURE__ */ new Error(message)).stack ?? message;
|
||
Error.stackTraceLimit = originalStackTraceLimit;
|
||
context.warn({
|
||
message: stack,
|
||
code: "UNSUPPORTED_BUNDLE_ASSIGNMENT"
|
||
});
|
||
return true;
|
||
},
|
||
deleteProperty(target, property) {
|
||
if (typeof property === "string") changed.deleted.add(property);
|
||
delete target[property];
|
||
return true;
|
||
}
|
||
});
|
||
}
|
||
function collectChangedBundle(changed, bundle) {
|
||
const changes = {};
|
||
for (const key in bundle) {
|
||
if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
|
||
const item = bundle[key];
|
||
if (item.type === "asset") changes[key] = {
|
||
filename: item.fileName,
|
||
originalFileNames: item.originalFileNames,
|
||
source: bindingAssetSource(item.source),
|
||
names: item.names
|
||
};
|
||
else changes[key] = {
|
||
code: item.code,
|
||
filename: item.fileName,
|
||
name: item.name,
|
||
isEntry: item.isEntry,
|
||
exports: item.exports,
|
||
modules: {},
|
||
imports: item.imports,
|
||
dynamicImports: item.dynamicImports,
|
||
facadeModuleId: item.facadeModuleId || void 0,
|
||
isDynamicEntry: item.isDynamicEntry,
|
||
moduleIds: item.moduleIds,
|
||
map: bindingifySourcemap(item.map),
|
||
sourcemapFilename: item.sourcemapFileName || void 0,
|
||
preliminaryFilename: item.preliminaryFileName
|
||
};
|
||
}
|
||
return {
|
||
changes,
|
||
deleted: changed.deleted
|
||
};
|
||
}
|
||
//#endregion
|
||
//#region src/options/normalized-input-options.ts
|
||
var NormalizedInputOptionsImpl = class extends PlainObjectLike {
|
||
onLog;
|
||
inputPlugins;
|
||
inner;
|
||
constructor(inner, onLog, inputPlugins) {
|
||
super();
|
||
this.onLog = onLog;
|
||
this.inputPlugins = inputPlugins;
|
||
this.inner = inner;
|
||
}
|
||
get shimMissingExports() {
|
||
return this.inner.shimMissingExports;
|
||
}
|
||
get input() {
|
||
return this.inner.input;
|
||
}
|
||
get cwd() {
|
||
return this.inner.cwd;
|
||
}
|
||
get platform() {
|
||
return this.inner.platform;
|
||
}
|
||
get context() {
|
||
return this.inner.context;
|
||
}
|
||
get plugins() {
|
||
return this.inputPlugins;
|
||
}
|
||
};
|
||
__decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "shimMissingExports", null);
|
||
__decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "input", null);
|
||
__decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "cwd", null);
|
||
__decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "platform", null);
|
||
__decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "context", null);
|
||
//#endregion
|
||
//#region src/options/normalized-output-options.ts
|
||
var NormalizedOutputOptionsImpl = class extends PlainObjectLike {
|
||
inner;
|
||
outputOptions;
|
||
normalizedOutputPlugins;
|
||
constructor(inner, outputOptions, normalizedOutputPlugins) {
|
||
super();
|
||
this.inner = inner;
|
||
this.outputOptions = outputOptions;
|
||
this.normalizedOutputPlugins = normalizedOutputPlugins;
|
||
}
|
||
get dir() {
|
||
return this.inner.dir ?? void 0;
|
||
}
|
||
get entryFileNames() {
|
||
return this.inner.entryFilenames || this.outputOptions.entryFileNames;
|
||
}
|
||
get chunkFileNames() {
|
||
return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
|
||
}
|
||
get assetFileNames() {
|
||
return this.inner.assetFilenames || this.outputOptions.assetFileNames;
|
||
}
|
||
get format() {
|
||
return this.inner.format;
|
||
}
|
||
get exports() {
|
||
return this.inner.exports;
|
||
}
|
||
get sourcemap() {
|
||
return this.inner.sourcemap;
|
||
}
|
||
get sourcemapFileNames() {
|
||
return this.inner.sourcemapFilenames || this.outputOptions.sourcemapFileNames;
|
||
}
|
||
get sourcemapBaseUrl() {
|
||
return this.inner.sourcemapBaseUrl ?? void 0;
|
||
}
|
||
get shimMissingExports() {
|
||
return this.inner.shimMissingExports;
|
||
}
|
||
get name() {
|
||
return this.inner.name ?? void 0;
|
||
}
|
||
get file() {
|
||
return this.inner.file ?? void 0;
|
||
}
|
||
get codeSplitting() {
|
||
return this.inner.codeSplitting;
|
||
}
|
||
/**
|
||
* @deprecated Use `codeSplitting` instead.
|
||
*/
|
||
get inlineDynamicImports() {
|
||
return !this.inner.codeSplitting;
|
||
}
|
||
get dynamicImportInCjs() {
|
||
return this.inner.dynamicImportInCjs;
|
||
}
|
||
get externalLiveBindings() {
|
||
return this.inner.externalLiveBindings;
|
||
}
|
||
get banner() {
|
||
return normalizeAddon(this.outputOptions.banner);
|
||
}
|
||
get footer() {
|
||
return normalizeAddon(this.outputOptions.footer);
|
||
}
|
||
get postBanner() {
|
||
return normalizeAddon(this.outputOptions.postBanner);
|
||
}
|
||
get postFooter() {
|
||
return normalizeAddon(this.outputOptions.postFooter);
|
||
}
|
||
get intro() {
|
||
return normalizeAddon(this.outputOptions.intro);
|
||
}
|
||
get outro() {
|
||
return normalizeAddon(this.outputOptions.outro);
|
||
}
|
||
get esModule() {
|
||
return this.inner.esModule;
|
||
}
|
||
get extend() {
|
||
return this.inner.extend;
|
||
}
|
||
get globals() {
|
||
return this.inner.globals || this.outputOptions.globals;
|
||
}
|
||
get paths() {
|
||
return this.outputOptions.paths;
|
||
}
|
||
get hashCharacters() {
|
||
return this.inner.hashCharacters;
|
||
}
|
||
get sourcemapDebugIds() {
|
||
return this.inner.sourcemapDebugIds;
|
||
}
|
||
get sourcemapExcludeSources() {
|
||
return this.inner.sourcemapExcludeSources;
|
||
}
|
||
get sourcemapIgnoreList() {
|
||
return this.outputOptions.sourcemapIgnoreList;
|
||
}
|
||
get sourcemapPathTransform() {
|
||
return this.outputOptions.sourcemapPathTransform;
|
||
}
|
||
get minify() {
|
||
let ret = this.inner.minify;
|
||
if (typeof ret === "object" && ret !== null) {
|
||
delete ret["codegen"];
|
||
delete ret["module"];
|
||
delete ret["sourcemap"];
|
||
}
|
||
return ret;
|
||
}
|
||
get legalComments() {
|
||
return this.inner.legalComments;
|
||
}
|
||
get comments() {
|
||
const c = this.inner.comments;
|
||
return {
|
||
legal: c.legal ?? true,
|
||
annotation: c.annotation ?? true,
|
||
jsdoc: c.jsdoc ?? true
|
||
};
|
||
}
|
||
get polyfillRequire() {
|
||
return this.inner.polyfillRequire;
|
||
}
|
||
get plugins() {
|
||
return this.normalizedOutputPlugins;
|
||
}
|
||
get preserveModules() {
|
||
return this.inner.preserveModules;
|
||
}
|
||
get preserveModulesRoot() {
|
||
return this.inner.preserveModulesRoot;
|
||
}
|
||
get virtualDirname() {
|
||
return this.inner.virtualDirname;
|
||
}
|
||
get topLevelVar() {
|
||
return this.inner.topLevelVar ?? false;
|
||
}
|
||
get minifyInternalExports() {
|
||
return this.inner.minifyInternalExports ?? false;
|
||
}
|
||
};
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "dir", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "entryFileNames", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "chunkFileNames", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "assetFileNames", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "format", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "exports", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemap", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapFileNames", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapBaseUrl", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "shimMissingExports", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "name", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "file", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "codeSplitting", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "inlineDynamicImports", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "dynamicImportInCjs", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "externalLiveBindings", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "banner", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "footer", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "postBanner", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "postFooter", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "intro", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "outro", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "esModule", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "extend", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "globals", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "paths", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "hashCharacters", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapDebugIds", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapExcludeSources", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapIgnoreList", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapPathTransform", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "minify", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "legalComments", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "comments", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "polyfillRequire", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "plugins", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "preserveModules", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "preserveModulesRoot", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "virtualDirname", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "topLevelVar", null);
|
||
__decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "minifyInternalExports", null);
|
||
function normalizeAddon(value) {
|
||
if (typeof value === "function") return value;
|
||
return () => value || "";
|
||
}
|
||
//#endregion
|
||
//#region src/utils/transform-module-info.ts
|
||
function transformModuleInfo(info, option) {
|
||
return {
|
||
get ast() {
|
||
return unsupported("ModuleInfo#ast");
|
||
},
|
||
get code() {
|
||
return info.code;
|
||
},
|
||
id: info.id,
|
||
importers: info.importers,
|
||
dynamicImporters: info.dynamicImporters,
|
||
importedIds: info.importedIds,
|
||
dynamicallyImportedIds: info.dynamicallyImportedIds,
|
||
exports: info.exports,
|
||
isEntry: info.isEntry,
|
||
inputFormat: info.inputFormat,
|
||
...option
|
||
};
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/plugin-context-data.ts
|
||
var PluginContextData = class {
|
||
onLog;
|
||
outputOptions;
|
||
normalizedInputPlugins;
|
||
normalizedOutputPlugins;
|
||
moduleOptionMap = /* @__PURE__ */ new Map();
|
||
resolveOptionsMap = /* @__PURE__ */ new Map();
|
||
loadModulePromiseMap = /* @__PURE__ */ new Map();
|
||
renderedChunkMeta = null;
|
||
normalizedInputOptions = null;
|
||
normalizedOutputOptions = null;
|
||
constructor(onLog, outputOptions, normalizedInputPlugins, normalizedOutputPlugins) {
|
||
this.onLog = onLog;
|
||
this.outputOptions = outputOptions;
|
||
this.normalizedInputPlugins = normalizedInputPlugins;
|
||
this.normalizedOutputPlugins = normalizedOutputPlugins;
|
||
}
|
||
updateModuleOption(id, option) {
|
||
const existing = this.moduleOptionMap.get(id);
|
||
if (existing) {
|
||
if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
|
||
if (option.meta != null) Object.assign(existing.meta, option.meta);
|
||
if (option.invalidate != null) existing.invalidate = option.invalidate;
|
||
} else {
|
||
this.moduleOptionMap.set(id, option);
|
||
return option;
|
||
}
|
||
return existing;
|
||
}
|
||
getModuleOption(id) {
|
||
const option = this.moduleOptionMap.get(id);
|
||
if (!option) {
|
||
const raw = {
|
||
moduleSideEffects: null,
|
||
meta: {}
|
||
};
|
||
this.moduleOptionMap.set(id, raw);
|
||
return raw;
|
||
}
|
||
return option;
|
||
}
|
||
getModuleInfo(id, context) {
|
||
const bindingInfo = context.getModuleInfo(id);
|
||
if (bindingInfo) {
|
||
const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
|
||
return this.proxyModuleInfo(id, info);
|
||
}
|
||
return null;
|
||
}
|
||
proxyModuleInfo(id, info) {
|
||
let moduleSideEffects = info.moduleSideEffects;
|
||
Object.defineProperty(info, "moduleSideEffects", {
|
||
get() {
|
||
return moduleSideEffects;
|
||
},
|
||
set: (v) => {
|
||
this.updateModuleOption(id, {
|
||
moduleSideEffects: v,
|
||
meta: info.meta,
|
||
invalidate: true
|
||
});
|
||
moduleSideEffects = v;
|
||
}
|
||
});
|
||
return info;
|
||
}
|
||
getModuleIds(context) {
|
||
return context.getModuleIds().values();
|
||
}
|
||
saveResolveOptions(options) {
|
||
const index = this.resolveOptionsMap.size;
|
||
this.resolveOptionsMap.set(index, options);
|
||
return index;
|
||
}
|
||
getSavedResolveOptions(receipt) {
|
||
return this.resolveOptionsMap.get(receipt);
|
||
}
|
||
removeSavedResolveOptions(receipt) {
|
||
this.resolveOptionsMap.delete(receipt);
|
||
}
|
||
setRenderChunkMeta(meta) {
|
||
this.renderedChunkMeta = meta;
|
||
}
|
||
getRenderChunkMeta() {
|
||
return this.renderedChunkMeta;
|
||
}
|
||
getInputOptions(opts) {
|
||
this.normalizedInputOptions ??= new NormalizedInputOptionsImpl(opts, this.onLog, this.normalizedInputPlugins);
|
||
return this.normalizedInputOptions;
|
||
}
|
||
getOutputOptions(opts) {
|
||
this.normalizedOutputOptions ??= new NormalizedOutputOptionsImpl(opts, this.outputOptions, this.normalizedOutputPlugins);
|
||
return this.normalizedOutputOptions;
|
||
}
|
||
clear() {
|
||
this.renderedChunkMeta = null;
|
||
this.loadModulePromiseMap.clear();
|
||
}
|
||
};
|
||
//#endregion
|
||
//#region src/binding-magic-string.ts
|
||
Object.defineProperty(import_binding.BindingMagicString.prototype, "isRolldownMagicString", {
|
||
value: true,
|
||
writable: false,
|
||
configurable: false
|
||
});
|
||
function assertString(content, msg) {
|
||
if (typeof content !== "string") throw new TypeError(msg);
|
||
}
|
||
const nativeAppend = import_binding.BindingMagicString.prototype.append;
|
||
const nativePrepend = import_binding.BindingMagicString.prototype.prepend;
|
||
const nativeAppendLeft = import_binding.BindingMagicString.prototype.appendLeft;
|
||
const nativeAppendRight = import_binding.BindingMagicString.prototype.appendRight;
|
||
const nativePrependLeft = import_binding.BindingMagicString.prototype.prependLeft;
|
||
const nativePrependRight = import_binding.BindingMagicString.prototype.prependRight;
|
||
const nativeOverwrite = import_binding.BindingMagicString.prototype.overwrite;
|
||
const nativeUpdate = import_binding.BindingMagicString.prototype.update;
|
||
import_binding.BindingMagicString.prototype.append = function(content) {
|
||
assertString(content, "outro content must be a string");
|
||
return nativeAppend.call(this, content);
|
||
};
|
||
import_binding.BindingMagicString.prototype.prepend = function(content) {
|
||
assertString(content, "outro content must be a string");
|
||
return nativePrepend.call(this, content);
|
||
};
|
||
import_binding.BindingMagicString.prototype.appendLeft = function(index, content) {
|
||
assertString(content, "inserted content must be a string");
|
||
return nativeAppendLeft.call(this, index, content);
|
||
};
|
||
import_binding.BindingMagicString.prototype.appendRight = function(index, content) {
|
||
assertString(content, "inserted content must be a string");
|
||
return nativeAppendRight.call(this, index, content);
|
||
};
|
||
import_binding.BindingMagicString.prototype.prependLeft = function(index, content) {
|
||
assertString(content, "inserted content must be a string");
|
||
return nativePrependLeft.call(this, index, content);
|
||
};
|
||
import_binding.BindingMagicString.prototype.prependRight = function(index, content) {
|
||
assertString(content, "inserted content must be a string");
|
||
return nativePrependRight.call(this, index, content);
|
||
};
|
||
import_binding.BindingMagicString.prototype.overwrite = function(start, end, content, options) {
|
||
assertString(content, "replacement content must be a string");
|
||
return nativeOverwrite.call(this, start, end, content, options);
|
||
};
|
||
import_binding.BindingMagicString.prototype.update = function(start, end, content, options) {
|
||
assertString(content, "replacement content must be a string");
|
||
return nativeUpdate.call(this, start, end, content, options);
|
||
};
|
||
const nativeReplace = import_binding.BindingMagicString.prototype.replace;
|
||
const nativeReplaceAll = import_binding.BindingMagicString.prototype.replaceAll;
|
||
import_binding.BindingMagicString.prototype.replace = function(searchValue, replacement) {
|
||
if (typeof searchValue === "string") return nativeReplace.call(this, searchValue, replacement);
|
||
if (searchValue.global) searchValue.lastIndex = 0;
|
||
const lastMatchEnd = this.replaceRegex(searchValue, replacement);
|
||
if (searchValue.global) searchValue.lastIndex = 0;
|
||
else if (searchValue.sticky) searchValue.lastIndex = lastMatchEnd === -1 ? 0 : lastMatchEnd;
|
||
return this;
|
||
};
|
||
import_binding.BindingMagicString.prototype.replaceAll = function(searchValue, replacement) {
|
||
if (typeof searchValue === "string") return nativeReplaceAll.call(this, searchValue, replacement);
|
||
if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
|
||
searchValue.lastIndex = 0;
|
||
this.replaceRegex(searchValue, replacement);
|
||
searchValue.lastIndex = 0;
|
||
return this;
|
||
};
|
||
/**
|
||
* A native MagicString implementation powered by Rust.
|
||
*
|
||
* @experimental
|
||
*/
|
||
const RolldownMagicString = import_binding.BindingMagicString;
|
||
//#endregion
|
||
//#region src/utils/transform-sourcemap.ts
|
||
function isEmptySourcemapFiled(array) {
|
||
if (!array) return true;
|
||
if (array.length === 0 || !array[0]) return true;
|
||
return false;
|
||
}
|
||
function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
|
||
if (!rawMap) return;
|
||
let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
|
||
if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
|
||
if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
|
||
return map;
|
||
}
|
||
//#endregion
|
||
//#region ../../node_modules/.pnpm/remeda@2.50.0/node_modules/remeda/dist/lazyDataLastImpl--3B10z3s.js
|
||
function e(e, t, n) {
|
||
let r = (n) => e(n, ...t);
|
||
return n === void 0 ? r : Object.assign(r, {
|
||
lazy: n,
|
||
lazyArgs: t
|
||
});
|
||
}
|
||
//#endregion
|
||
//#region ../../node_modules/.pnpm/remeda@2.50.0/node_modules/remeda/dist/purry.js
|
||
function t$1(t, n, r) {
|
||
let i = t.length - n.length;
|
||
if (i === 0) return t(...n);
|
||
if (i === 1) return e(t, n, r);
|
||
throw Error(`Wrong number of arguments`);
|
||
}
|
||
//#endregion
|
||
//#region ../../node_modules/.pnpm/remeda@2.50.0/node_modules/remeda/dist/partition.js
|
||
function t(...t) {
|
||
return t$1(n, t);
|
||
}
|
||
const n = (e, t) => {
|
||
let n = [[], []];
|
||
for (let [r, i] of e.entries()) t(i, r, e) ? n[0].push(i) : n[1].push(i);
|
||
return n;
|
||
};
|
||
//#endregion
|
||
//#region src/plugin/bindingify-hook-filter.ts
|
||
function generalHookFilterMatcherToFilterExprs(matcher, stringKind) {
|
||
if (typeof matcher === "string" || matcher instanceof RegExp) return [filter.include(generateAtomMatcher(stringKind, matcher))];
|
||
if (Array.isArray(matcher)) return matcher.map((m) => filter.include(generateAtomMatcher(stringKind, m)));
|
||
let ret = [];
|
||
if (matcher.exclude) ret.push(...arraify(matcher.exclude).map((m) => filter.exclude(generateAtomMatcher(stringKind, m))));
|
||
if (matcher.include) ret.push(...arraify(matcher.include).map((m) => filter.include(generateAtomMatcher(stringKind, m))));
|
||
return ret;
|
||
}
|
||
function generateAtomMatcher(kind, matcher) {
|
||
return kind === "code" ? filter.code(matcher) : filter.id(matcher);
|
||
}
|
||
function transformFilterMatcherToFilterExprs(filterOption) {
|
||
if (!filterOption) return;
|
||
if (Array.isArray(filterOption)) return filterOption;
|
||
const { id, code, moduleType } = filterOption;
|
||
let ret = [];
|
||
let idIncludes = [];
|
||
let idExcludes = [];
|
||
let codeIncludes = [];
|
||
let codeExcludes = [];
|
||
if (id) [idIncludes, idExcludes] = t(generalHookFilterMatcherToFilterExprs(id, "id") ?? [], (m) => m.kind === "include");
|
||
if (code) [codeIncludes, codeExcludes] = t(generalHookFilterMatcherToFilterExprs(code, "code") ?? [], (m) => m.kind === "include");
|
||
ret.push(...idExcludes);
|
||
ret.push(...codeExcludes);
|
||
let andExprList = [];
|
||
if (moduleType) {
|
||
let moduleTypes = Array.isArray(moduleType) ? moduleType : moduleType.include ?? [];
|
||
andExprList.push(filter.or(...moduleTypes.map((m) => filter.moduleType(m))));
|
||
}
|
||
if (idIncludes.length) andExprList.push(filter.or(...idIncludes.map((item) => item.expr)));
|
||
if (codeIncludes.length) andExprList.push(filter.or(...codeIncludes.map((item) => item.expr)));
|
||
if (andExprList.length) ret.push(filter.include(filter.and(...andExprList)));
|
||
return ret;
|
||
}
|
||
function bindingifyGeneralHookFilter(stringKind, pattern) {
|
||
let filterExprs = generalHookFilterMatcherToFilterExprs(pattern, stringKind);
|
||
let ret = [];
|
||
if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
|
||
return ret.length > 0 ? { value: ret } : void 0;
|
||
}
|
||
function bindingifyFilterExpr(expr) {
|
||
let list = [];
|
||
bindingifyFilterExprImpl(expr, list);
|
||
return list;
|
||
}
|
||
function containsImporterId(expr) {
|
||
switch (expr.kind) {
|
||
case "and":
|
||
case "or": return expr.args.some(containsImporterId);
|
||
case "not":
|
||
case "include":
|
||
case "exclude": return containsImporterId(expr.expr);
|
||
case "importerId": return true;
|
||
default: return false;
|
||
}
|
||
}
|
||
function assertNoImporterId(filterExprs, hookName) {
|
||
if (filterExprs?.some(containsImporterId)) throw new Error(`The \`importerId\` filter can only be used with the \`resolveId\` hook, but it was used with the \`${hookName}\` hook.`);
|
||
}
|
||
function containsStringId(expr) {
|
||
switch (expr.kind) {
|
||
case "and":
|
||
case "or": return expr.args.some(containsStringId);
|
||
case "not":
|
||
case "include":
|
||
case "exclude": return containsStringId(expr.expr);
|
||
case "id": return typeof expr.pattern === "string";
|
||
default: return false;
|
||
}
|
||
}
|
||
function assertNoStringId(filterExprs, hookName) {
|
||
if (filterExprs?.some(containsStringId)) throw new Error(`A string \`id\` filter is not supported for the \`${hookName}\` hook, because its \`id\` is the import specifier rather than a resolved path. Use a RegExp instead.`);
|
||
}
|
||
function bindingifyFilterExprImpl(expr, list) {
|
||
switch (expr.kind) {
|
||
case "and": {
|
||
let args = expr.args;
|
||
for (let i = args.length - 1; i >= 0; i--) bindingifyFilterExprImpl(args[i], list);
|
||
list.push({
|
||
kind: "And",
|
||
payload: args.length
|
||
});
|
||
break;
|
||
}
|
||
case "or": {
|
||
let args = expr.args;
|
||
for (let i = args.length - 1; i >= 0; i--) bindingifyFilterExprImpl(args[i], list);
|
||
list.push({
|
||
kind: "Or",
|
||
payload: args.length
|
||
});
|
||
break;
|
||
}
|
||
case "not":
|
||
bindingifyFilterExprImpl(expr.expr, list);
|
||
list.push({ kind: "Not" });
|
||
break;
|
||
case "id":
|
||
list.push({
|
||
kind: "Id",
|
||
payload: expr.pattern
|
||
});
|
||
if (expr.params.cleanUrl) list.push({ kind: "CleanUrl" });
|
||
break;
|
||
case "importerId":
|
||
list.push({
|
||
kind: "ImporterId",
|
||
payload: expr.pattern
|
||
});
|
||
if (expr.params.cleanUrl) list.push({ kind: "CleanUrl" });
|
||
break;
|
||
case "moduleType":
|
||
list.push({
|
||
kind: "ModuleType",
|
||
payload: expr.pattern
|
||
});
|
||
break;
|
||
case "code":
|
||
list.push({
|
||
kind: "Code",
|
||
payload: expr.pattern
|
||
});
|
||
break;
|
||
case "include":
|
||
bindingifyFilterExprImpl(expr.expr, list);
|
||
list.push({ kind: "Include" });
|
||
break;
|
||
case "exclude":
|
||
bindingifyFilterExprImpl(expr.expr, list);
|
||
list.push({ kind: "Exclude" });
|
||
break;
|
||
case "query":
|
||
list.push({
|
||
kind: "QueryKey",
|
||
payload: expr.key
|
||
});
|
||
list.push({
|
||
kind: "QueryValue",
|
||
payload: expr.pattern
|
||
});
|
||
break;
|
||
default: throw new Error(`Unknown filter expression: ${expr}`);
|
||
}
|
||
}
|
||
function bindingifyResolveIdFilter(filterOption) {
|
||
if (!filterOption) return;
|
||
const filterExprs = Array.isArray(filterOption) ? filterOption : filterOption.id ? generalHookFilterMatcherToFilterExprs(filterOption.id, "id") : void 0;
|
||
assertNoStringId(filterExprs, "resolveId");
|
||
if (!filterExprs) return;
|
||
const value = filterExprs.map(bindingifyFilterExpr);
|
||
return value.length > 0 ? { value } : void 0;
|
||
}
|
||
function bindingifyLoadFilter(filterOption) {
|
||
if (!filterOption) return;
|
||
if (Array.isArray(filterOption)) {
|
||
assertNoImporterId(filterOption, "load");
|
||
return { value: filterOption.map(bindingifyFilterExpr) };
|
||
}
|
||
return filterOption.id ? bindingifyGeneralHookFilter("id", filterOption.id) : void 0;
|
||
}
|
||
function bindingifyTransformFilter(filterOption) {
|
||
if (!filterOption) return;
|
||
let filterExprs = transformFilterMatcherToFilterExprs(filterOption);
|
||
assertNoImporterId(filterExprs, "transform");
|
||
let ret = [];
|
||
if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
|
||
return { value: ret.length > 0 ? ret : void 0 };
|
||
}
|
||
function bindingifyRenderChunkFilter(filterOption) {
|
||
if (!filterOption) return;
|
||
if (Array.isArray(filterOption)) {
|
||
assertNoImporterId(filterOption, "renderChunk");
|
||
return { value: filterOption.map(bindingifyFilterExpr) };
|
||
}
|
||
return filterOption.code ? bindingifyGeneralHookFilter("code", filterOption.code) : void 0;
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/bindingify-plugin-hook-meta.ts
|
||
function bindingifyPluginHookMeta(options) {
|
||
return { order: bindingPluginOrder(options.order) };
|
||
}
|
||
function bindingPluginOrder(order) {
|
||
switch (order) {
|
||
case "post": return import_binding.BindingPluginOrder.Post;
|
||
case "pre": return import_binding.BindingPluginOrder.Pre;
|
||
case null:
|
||
case void 0: return;
|
||
default: throw new Error(`Unknown plugin order: ${order}`);
|
||
}
|
||
}
|
||
function bindingifyHook(hook, build) {
|
||
if (!hook) return {};
|
||
const normalized = normalizeHook(hook);
|
||
return {
|
||
...build(normalized),
|
||
meta: bindingifyPluginHookMeta(normalized.meta)
|
||
};
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/fs.ts
|
||
const fsModule = {
|
||
appendFile: fsp.appendFile,
|
||
copyFile: fsp.copyFile,
|
||
mkdir: fsp.mkdir,
|
||
mkdtemp: fsp.mkdtemp,
|
||
readdir: fsp.readdir,
|
||
readFile: fsp.readFile,
|
||
realpath: fsp.realpath,
|
||
rename: fsp.rename,
|
||
rmdir: fsp.rmdir,
|
||
stat: fsp.stat,
|
||
lstat: fsp.lstat,
|
||
unlink: fsp.unlink,
|
||
writeFile: fsp.writeFile
|
||
};
|
||
//#endregion
|
||
//#region src/plugin/plugin-context.ts
|
||
var PluginContextImpl = class extends MinimalPluginContextImpl {
|
||
outputOptions;
|
||
context;
|
||
data;
|
||
onLog;
|
||
currentLoadingModule;
|
||
fs = fsModule;
|
||
getModuleInfo;
|
||
constructor(outputOptions, context, plugin, data, onLog, logLevel, watchMode, currentLoadingModule) {
|
||
super(onLog, logLevel, plugin.name, watchMode);
|
||
this.outputOptions = outputOptions;
|
||
this.context = context;
|
||
this.data = data;
|
||
this.onLog = onLog;
|
||
this.currentLoadingModule = currentLoadingModule;
|
||
this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
|
||
}
|
||
async load(options) {
|
||
const id = options.id;
|
||
if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
|
||
const moduleInfo = this.data.getModuleInfo(id, this.context);
|
||
if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
|
||
const rawOptions = {
|
||
meta: options.meta || {},
|
||
moduleSideEffects: options.moduleSideEffects || null,
|
||
invalidate: false
|
||
};
|
||
this.data.updateModuleOption(id, rawOptions);
|
||
let loadPromise = this.data.loadModulePromiseMap.get(id);
|
||
if (!loadPromise) {
|
||
loadPromise = this.context.load(id, options.moduleSideEffects ?? void 0, options.packageJsonPath ?? void 0).catch(() => {
|
||
this.data.loadModulePromiseMap.delete(id);
|
||
});
|
||
this.data.loadModulePromiseMap.set(id, loadPromise);
|
||
}
|
||
await loadPromise;
|
||
return this.data.getModuleInfo(id, this.context);
|
||
}
|
||
async resolve(source, importer, options) {
|
||
let receipt = void 0;
|
||
if (options != null) receipt = this.data.saveResolveOptions(options);
|
||
const vitePluginCustom = Object.entries(options?.custom ?? {}).reduce((acc, [key, value]) => {
|
||
if (key.startsWith("vite:")) (acc ??= {})[key] = value;
|
||
return acc;
|
||
}, void 0);
|
||
const res = await this.context.resolve(source, importer, {
|
||
importKind: options?.kind,
|
||
custom: receipt,
|
||
isEntry: options?.isEntry,
|
||
skipSelf: options?.skipSelf,
|
||
vitePluginCustom
|
||
});
|
||
if (receipt != null) this.data.removeSavedResolveOptions(receipt);
|
||
if (res == null) return null;
|
||
const info = this.data.getModuleOption(res.id) || {};
|
||
return {
|
||
...res,
|
||
external: res.external === "relative" ? unreachable(`The PluginContext resolve result external couldn't be 'relative'`) : res.external,
|
||
...info,
|
||
moduleSideEffects: info.moduleSideEffects ?? res.moduleSideEffects ?? null,
|
||
packageJsonPath: res.packageJsonPath
|
||
};
|
||
}
|
||
emitFile = (file) => {
|
||
if (file.type === "prebuilt-chunk") {
|
||
if (typeof file.code !== "string") return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${file.code}".`));
|
||
if (typeof file.fileName !== "string" || isPathFragment(file.fileName)) return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${file.fileName}".`));
|
||
return this.context.emitPrebuiltChunk({
|
||
fileName: file.fileName,
|
||
name: file.name,
|
||
code: file.code,
|
||
exports: file.exports,
|
||
map: bindingifySourcemap(file.map),
|
||
sourcemapFileName: file.sourcemapFileName,
|
||
facadeModuleId: file.facadeModuleId,
|
||
isEntry: file.isEntry,
|
||
isDynamicEntry: file.isDynamicEntry
|
||
});
|
||
}
|
||
const validatedName = file.fileName || file.name;
|
||
if (typeof validatedName === "string" && isPathFragment(validatedName)) return error(logFailedValidation(`The "fileName" or "name" properties of emitted chunks and assets must be strings that are neither absolute nor relative paths, received "${validatedName}".`));
|
||
if (file.type === "chunk") return this.context.emitChunk({
|
||
preserveEntrySignatures: bindingifyPreserveEntrySignatures(file.preserveSignature),
|
||
...file
|
||
});
|
||
const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
|
||
const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
|
||
return this.context.emitFile({
|
||
...file,
|
||
originalFileName: file.originalFileName || void 0,
|
||
source: bindingAssetSource(file.source)
|
||
}, filename, fnSanitizedFileName);
|
||
};
|
||
getAssetFileNames(file) {
|
||
if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
|
||
type: "asset",
|
||
name: file.name,
|
||
names: file.name ? [file.name] : [],
|
||
originalFileName: file.originalFileName,
|
||
originalFileNames: file.originalFileName ? [file.originalFileName] : [],
|
||
source: file.source
|
||
});
|
||
}
|
||
getFileName(referenceId) {
|
||
return this.context.getFileName(referenceId);
|
||
}
|
||
getModuleIds() {
|
||
return this.data.getModuleIds(this.context);
|
||
}
|
||
addWatchFile(id) {
|
||
this.context.addWatchFile(id);
|
||
}
|
||
parse(input, options) {
|
||
return parseAst(input, options);
|
||
}
|
||
};
|
||
function createPluginContext(args, ctx) {
|
||
return new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode);
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/load-plugin-context.ts
|
||
var LoadPluginContextImpl = class extends PluginContextImpl {
|
||
inner;
|
||
constructor(outputOptions, context, plugin, data, inner, moduleId, onLog, logLevelOption, watchMode) {
|
||
super(outputOptions, context, plugin, data, onLog, logLevelOption, watchMode, moduleId);
|
||
this.inner = inner;
|
||
}
|
||
addWatchFile(id) {
|
||
this.inner.addWatchFile(id);
|
||
}
|
||
};
|
||
//#endregion
|
||
//#region src/plugin/transform-plugin-context.ts
|
||
var TransformPluginContextImpl = class extends PluginContextImpl {
|
||
inner;
|
||
moduleId;
|
||
moduleSource;
|
||
constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption, watchMode) {
|
||
super(outputOptions, context, plugin, data, onLog, LogLevelOption, watchMode, moduleId);
|
||
this.inner = inner;
|
||
this.moduleId = moduleId;
|
||
this.moduleSource = moduleSource;
|
||
const getLogHandler = (handler) => (log, pos) => {
|
||
log = normalizeLog(log);
|
||
if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
|
||
log.id = moduleId;
|
||
log.hook = "transform";
|
||
handler(log);
|
||
};
|
||
this.debug = getLogHandler(this.debug);
|
||
this.warn = getLogHandler(this.warn);
|
||
this.info = getLogHandler(this.info);
|
||
}
|
||
error(e, pos) {
|
||
if (typeof e === "string") e = { message: e };
|
||
if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
|
||
e.id = this.moduleId;
|
||
e.hook = "transform";
|
||
return error(logPluginError(normalizeLog(e), this.pluginName));
|
||
}
|
||
getCombinedSourcemap() {
|
||
return JSON.parse(this.inner.getCombinedSourcemap());
|
||
}
|
||
addWatchFile(id) {
|
||
this.inner.addWatchFile(id);
|
||
}
|
||
sendMagicString(s) {
|
||
this.inner.sendMagicString(s);
|
||
}
|
||
};
|
||
//#endregion
|
||
//#region src/plugin/bindingify-build-hooks.ts
|
||
function bindingifyBuildStart(args) {
|
||
return bindingifyHook(args.plugin.buildStart, ({ handler }) => ({ plugin: async (ctx, opts) => {
|
||
await handler.call(createPluginContext(args, ctx), args.pluginContextData.getInputOptions(opts));
|
||
} }));
|
||
}
|
||
function bindingifyBuildEnd(args) {
|
||
return bindingifyHook(args.plugin.buildEnd, ({ handler }) => ({ plugin: async (ctx, err) => {
|
||
await handler.call(createPluginContext(args, ctx), err ? aggregateBindingErrorsIntoJsError(err) : void 0);
|
||
} }));
|
||
}
|
||
function bindingifyResolveId(args) {
|
||
const hook = args.plugin.resolveId;
|
||
return bindingifyHook(hook, ({ handler, options }) => ({
|
||
plugin: async (ctx, specifier, importer, extraOptions) => {
|
||
const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
|
||
const ret = await handler.call(createPluginContext(args, ctx), specifier, importer ?? void 0, {
|
||
...extraOptions,
|
||
custom: contextResolveOptions?.custom
|
||
});
|
||
if (ret == null) return;
|
||
if (ret === false) return {
|
||
id: specifier,
|
||
external: true,
|
||
normalizeExternalId: true
|
||
};
|
||
if (typeof ret === "string") return {
|
||
id: ret,
|
||
normalizeExternalId: false
|
||
};
|
||
let exist = args.pluginContextData.updateModuleOption(ret.id, {
|
||
meta: ret.meta || {},
|
||
moduleSideEffects: ret.moduleSideEffects ?? null,
|
||
invalidate: false
|
||
});
|
||
return {
|
||
id: ret.id,
|
||
external: ret.external,
|
||
normalizeExternalId: false,
|
||
moduleSideEffects: exist.moduleSideEffects ?? void 0,
|
||
packageJsonPath: ret.packageJsonPath
|
||
};
|
||
},
|
||
filter: bindingifyResolveIdFilter(options.filter)
|
||
}));
|
||
}
|
||
function bindingifyResolveDynamicImport(args) {
|
||
return bindingifyHook(args.plugin.resolveDynamicImport, ({ handler }) => ({ plugin: async (ctx, specifier, importer) => {
|
||
const ret = await handler.call(createPluginContext(args, ctx), specifier, importer ?? void 0);
|
||
if (ret == null) return;
|
||
if (ret === false) return {
|
||
id: specifier,
|
||
external: true
|
||
};
|
||
if (typeof ret === "string") return { id: ret };
|
||
const result = {
|
||
id: ret.id,
|
||
external: ret.external,
|
||
packageJsonPath: ret.packageJsonPath
|
||
};
|
||
if (ret.moduleSideEffects !== null) result.moduleSideEffects = ret.moduleSideEffects;
|
||
args.pluginContextData.updateModuleOption(ret.id, {
|
||
meta: ret.meta || {},
|
||
moduleSideEffects: ret.moduleSideEffects || null,
|
||
invalidate: false
|
||
});
|
||
return result;
|
||
} }));
|
||
}
|
||
function bindingifyTransform(args) {
|
||
return bindingifyHook(args.plugin.transform, ({ handler, options }) => ({
|
||
plugin: async (ctx, code, id, meta) => {
|
||
let magicStringInstance, astInstance;
|
||
Object.defineProperties(meta, {
|
||
magicString: { get() {
|
||
if (magicStringInstance) return magicStringInstance;
|
||
magicStringInstance = new RolldownMagicString(code);
|
||
return magicStringInstance;
|
||
} },
|
||
ast: { get() {
|
||
if (astInstance) return astInstance;
|
||
let lang = "js";
|
||
switch (meta.moduleType) {
|
||
case "js":
|
||
case "jsx":
|
||
case "ts":
|
||
case "tsx": lang = meta.moduleType;
|
||
}
|
||
astInstance = parseAst(code, {
|
||
astType: meta.moduleType.includes("ts") ? "ts" : "js",
|
||
lang
|
||
});
|
||
return astInstance;
|
||
} }
|
||
});
|
||
const transformCtx = new TransformPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel, args.watchMode);
|
||
const ret = await handler.call(transformCtx, code, id, meta);
|
||
if (ret == null) return;
|
||
if (typeof ret === "string") return { code: ret };
|
||
let moduleOption = args.pluginContextData.updateModuleOption(id, {
|
||
meta: ret.meta ?? {},
|
||
moduleSideEffects: ret.moduleSideEffects ?? null,
|
||
invalidate: false
|
||
});
|
||
let normalizedCode = void 0;
|
||
let map = ret.map;
|
||
let mapHandledByNativeChannel = false;
|
||
if (typeof ret.code === "string") normalizedCode = ret.code;
|
||
else if (ret.code instanceof RolldownMagicString) {
|
||
let magicString = ret.code;
|
||
normalizedCode = magicString.toString();
|
||
let fallbackSourcemap = ctx.sendMagicString(magicString);
|
||
if (fallbackSourcemap != void 0) map = fallbackSourcemap;
|
||
else mapHandledByNativeChannel = true;
|
||
}
|
||
return {
|
||
code: normalizedCode,
|
||
map: bindingifySourcemap(normalizeTransformHookSourcemap(id, code, map)) ?? (mapHandledByNativeChannel || ret.map === null ? null : void 0),
|
||
moduleSideEffects: moduleOption.moduleSideEffects ?? void 0,
|
||
moduleType: ret.moduleType
|
||
};
|
||
},
|
||
filter: bindingifyTransformFilter(options.filter)
|
||
}));
|
||
}
|
||
function bindingifyLoad(args) {
|
||
return bindingifyHook(args.plugin.load, ({ handler, options }) => ({
|
||
plugin: async (ctx, id) => {
|
||
const ret = await handler.call(new LoadPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, args.onLog, args.logLevel, args.watchMode), id);
|
||
if (ret == null) return;
|
||
if (typeof ret === "string") return { code: ret };
|
||
let moduleOption = args.pluginContextData.updateModuleOption(id, {
|
||
meta: ret.meta || {},
|
||
moduleSideEffects: ret.moduleSideEffects ?? null,
|
||
invalidate: false
|
||
});
|
||
let map = preProcessSourceMap(ret, id);
|
||
return {
|
||
code: ret.code,
|
||
map: bindingifySourcemap(map),
|
||
moduleType: ret.moduleType,
|
||
moduleSideEffects: moduleOption.moduleSideEffects ?? void 0
|
||
};
|
||
},
|
||
filter: bindingifyLoadFilter(options.filter)
|
||
}));
|
||
}
|
||
function preProcessSourceMap(ret, id) {
|
||
if (!ret.map) return;
|
||
let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
|
||
if (!isEmptySourcemapFiled(map.sources)) {
|
||
const directory = path.dirname(id) || ".";
|
||
const sourceRoot = map.sourceRoot || ".";
|
||
map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
|
||
}
|
||
return map;
|
||
}
|
||
function bindingifyModuleParsed(args) {
|
||
return bindingifyHook(args.plugin.moduleParsed, ({ handler }) => ({ plugin: async (ctx, moduleInfo) => {
|
||
await handler.call(createPluginContext(args, ctx), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
|
||
} }));
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/bindingify-output-hooks.ts
|
||
function bindingifyRenderStart(args) {
|
||
return bindingifyHook(args.plugin.renderStart, ({ handler }) => ({ plugin: async (ctx, opts) => {
|
||
await handler.call(createPluginContext(args, ctx), args.pluginContextData.getOutputOptions(opts), args.pluginContextData.getInputOptions(opts));
|
||
} }));
|
||
}
|
||
function bindingifyRenderChunk(args) {
|
||
return bindingifyHook(args.plugin.renderChunk, ({ handler, options }) => ({
|
||
plugin: async (ctx, code, chunk, opts, meta) => {
|
||
if (args.pluginContextData.getRenderChunkMeta() == null) args.pluginContextData.setRenderChunkMeta({ chunks: Object.fromEntries(Object.entries(meta.chunks).map(([key, value]) => [key, transformRenderedChunk(value)])) });
|
||
const renderChunkMeta = args.pluginContextData.getRenderChunkMeta();
|
||
let magicStringInstance;
|
||
if (args.options.experimental?.nativeMagicString) Object.defineProperty(renderChunkMeta, "magicString", {
|
||
get() {
|
||
if (magicStringInstance) return magicStringInstance;
|
||
magicStringInstance = new RolldownMagicString(code);
|
||
return magicStringInstance;
|
||
},
|
||
configurable: true
|
||
});
|
||
const ret = await handler.call(createPluginContext(args, ctx), code, transformRenderedChunk(chunk), args.pluginContextData.getOutputOptions(opts), renderChunkMeta);
|
||
if (ret == null) return;
|
||
if (ret instanceof RolldownMagicString) {
|
||
const normalizedCode = ret.toString();
|
||
const generatedMap = ret.generateMap();
|
||
return {
|
||
code: normalizedCode,
|
||
map: bindingifySourcemap({
|
||
file: generatedMap.file,
|
||
mappings: generatedMap.mappings,
|
||
names: generatedMap.names,
|
||
sources: generatedMap.sources,
|
||
sourcesContent: generatedMap.sourcesContent.map((s) => s ?? null)
|
||
})
|
||
};
|
||
}
|
||
if (typeof ret === "string") return { code: ret };
|
||
if (ret.code instanceof RolldownMagicString) {
|
||
const magicString = ret.code;
|
||
const normalizedCode = magicString.toString();
|
||
if (ret.map === null) return {
|
||
code: normalizedCode,
|
||
map: null
|
||
};
|
||
if (ret.map === void 0) {
|
||
const generatedMap = magicString.generateMap();
|
||
return {
|
||
code: normalizedCode,
|
||
map: bindingifySourcemap({
|
||
file: generatedMap.file,
|
||
mappings: generatedMap.mappings,
|
||
names: generatedMap.names,
|
||
sources: generatedMap.sources,
|
||
sourcesContent: generatedMap.sourcesContent.map((s) => s ?? null)
|
||
})
|
||
};
|
||
}
|
||
return {
|
||
code: normalizedCode,
|
||
map: bindingifySourcemap(ret.map)
|
||
};
|
||
}
|
||
if (ret.map === null) return {
|
||
code: ret.code,
|
||
map: null
|
||
};
|
||
return {
|
||
code: ret.code,
|
||
map: bindingifySourcemap(ret.map)
|
||
};
|
||
},
|
||
filter: bindingifyRenderChunkFilter(options.filter)
|
||
}));
|
||
}
|
||
function bindingifyAugmentChunkHash(args) {
|
||
return bindingifyHook(args.plugin.augmentChunkHash, ({ handler }) => ({ plugin: async (ctx, chunk) => {
|
||
return handler.call(createPluginContext(args, ctx), transformRenderedChunk(chunk));
|
||
} }));
|
||
}
|
||
function bindingifyResolveFileUrl(args) {
|
||
return bindingifyHook(args.plugin.resolveFileUrl, ({ handler }) => ({ plugin: async (ctx, resolveFileUrlArgs) => {
|
||
return handler.call(createPluginContext(args, ctx), resolveFileUrlArgs);
|
||
} }));
|
||
}
|
||
function bindingifyRenderError(args) {
|
||
return bindingifyHook(args.plugin.renderError, ({ handler }) => ({ plugin: async (ctx, err) => {
|
||
await handler.call(createPluginContext(args, ctx), aggregateBindingErrorsIntoJsError(err));
|
||
} }));
|
||
}
|
||
function createOutputBundle(args, ctx, bundle) {
|
||
const changed = {
|
||
updated: /* @__PURE__ */ new Set(),
|
||
deleted: /* @__PURE__ */ new Set()
|
||
};
|
||
const context = createPluginContext(args, ctx);
|
||
return {
|
||
changed,
|
||
context,
|
||
output: transformToOutputBundle(context, unwrapBindingResult(bundle), changed)
|
||
};
|
||
}
|
||
function bindingifyGenerateBundle(args) {
|
||
return bindingifyHook(args.plugin.generateBundle, ({ handler }) => ({ plugin: async (ctx, bundle, isWrite, opts) => {
|
||
const { changed, context, output } = createOutputBundle(args, ctx, bundle);
|
||
await handler.call(context, args.pluginContextData.getOutputOptions(opts), output, isWrite);
|
||
return collectChangedBundle(changed, output);
|
||
} }));
|
||
}
|
||
function bindingifyWriteBundle(args) {
|
||
return bindingifyHook(args.plugin.writeBundle, ({ handler }) => ({ plugin: async (ctx, bundle, opts) => {
|
||
const { changed, context, output } = createOutputBundle(args, ctx, bundle);
|
||
await handler.call(context, args.pluginContextData.getOutputOptions(opts), output);
|
||
return collectChangedBundle(changed, output);
|
||
} }));
|
||
}
|
||
function bindingifyCloseBundle(args) {
|
||
return bindingifyHook(args.plugin.closeBundle, ({ handler }) => ({ plugin: async (ctx, err) => {
|
||
await handler.call(createPluginContext(args, ctx), err ? aggregateBindingErrorsIntoJsError(err) : void 0);
|
||
} }));
|
||
}
|
||
function bindingifyAddonHook(args, name) {
|
||
return bindingifyHook(args.plugin[name], ({ handler }) => ({ plugin: async (ctx, chunk) => {
|
||
if (typeof handler === "string") return handler;
|
||
return handler.call(createPluginContext(args, ctx), transformRenderedChunk(chunk));
|
||
} }));
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/bindingify-watch-hooks.ts
|
||
function bindingifyHotUpdate(args) {
|
||
return bindingifyHook(args.plugin.hotUpdate, ({ handler }) => ({ plugin: async (ctx, hookArgs) => {
|
||
return await handler.call(createPluginContext(args, ctx), {
|
||
type: hookArgs.kind,
|
||
file: hookArgs.file,
|
||
modules: hookArgs.modules
|
||
}) ?? void 0;
|
||
} }));
|
||
}
|
||
function bindingifyWatchChange(args) {
|
||
return bindingifyHook(args.plugin.watchChange, ({ handler }) => ({ plugin: async (ctx, id, event) => {
|
||
await handler.call(createPluginContext(args, ctx), id, { event });
|
||
} }));
|
||
}
|
||
function bindingifyCloseWatcher(args) {
|
||
return bindingifyHook(args.plugin.closeWatcher, ({ handler }) => ({ plugin: async (ctx) => {
|
||
await handler.call(createPluginContext(args, ctx));
|
||
} }));
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/generated/hook-usage.ts
|
||
var HookUsage = class {
|
||
bitflag = BigInt(0);
|
||
constructor() {}
|
||
union(kind) {
|
||
this.bitflag |= BigInt(kind);
|
||
}
|
||
inner() {
|
||
return Number(this.bitflag);
|
||
}
|
||
};
|
||
function extractHookUsage(plugin) {
|
||
let hookUsage = new HookUsage();
|
||
if (plugin.buildStart) hookUsage.union(1);
|
||
if (plugin.resolveId) hookUsage.union(2);
|
||
if (plugin.resolveDynamicImport) hookUsage.union(4);
|
||
if (plugin.load) hookUsage.union(8);
|
||
if (plugin.transform) hookUsage.union(16);
|
||
if (plugin.moduleParsed) hookUsage.union(32);
|
||
if (plugin.buildEnd) hookUsage.union(64);
|
||
if (plugin.renderStart) hookUsage.union(128);
|
||
if (plugin.renderError) hookUsage.union(256);
|
||
if (plugin.renderChunk) hookUsage.union(512);
|
||
if (plugin.augmentChunkHash) hookUsage.union(1024);
|
||
if (plugin.generateBundle) hookUsage.union(2048);
|
||
if (plugin.writeBundle) hookUsage.union(4096);
|
||
if (plugin.closeBundle) hookUsage.union(8192);
|
||
if (plugin.watchChange) hookUsage.union(16384);
|
||
if (plugin.closeWatcher) hookUsage.union(32768);
|
||
if (plugin.banner) hookUsage.union(131072);
|
||
if (plugin.footer) hookUsage.union(262144);
|
||
if (plugin.intro) hookUsage.union(524288);
|
||
if (plugin.outro) hookUsage.union(1048576);
|
||
if (plugin.resolveFileUrl) hookUsage.union(2097152);
|
||
if (plugin.hotUpdate) hookUsage.union(4194304);
|
||
return hookUsage;
|
||
}
|
||
//#endregion
|
||
//#region src/utils/plugin-timings.ts
|
||
/**
|
||
* Measure what plugin hooks cost, from inside the JavaScript callback.
|
||
*
|
||
* Internal to Rolldown. Nothing here is on a public entry point, and the measurement is not
|
||
* offered as an API — the only consumer is the core, which pulls it while the build closes.
|
||
*
|
||
* The bundler core can only bracket *dispatch* and *completion*. For a hook it invokes
|
||
* concurrently those two points are separated mostly by the queue the call waited in on
|
||
* JavaScript's single thread, and the queue is deepest behind whichever callback is doing
|
||
* the most work — so the hook blocking the thread dilutes its own credit while cheap hooks
|
||
* collect credit for waiting. Ranking from those numbers reliably puts the *cheapest* hook
|
||
* first.
|
||
*
|
||
* The missing quantity is when the callback began running, and that is known here. Starting
|
||
* the clock inside the callback removes the dispatch queue by construction.
|
||
*
|
||
* ## `maxInFlight` decides whether a total means anything
|
||
*
|
||
* Entry-to-exit spans may be summed only if they never overlap. A synchronous callback
|
||
* cannot overlap: it holds the thread until it returns. An `async` one can — it may suspend
|
||
* at an `await` and let another call of the same hook begin, and then both spans cover the
|
||
* same wall clock and the sum counts it twice.
|
||
*
|
||
* Overlap also changes what the span is measuring. A hook that awaits the bundler (say
|
||
* `this.resolve`) spends most of its span waiting for Rust, so the number describes the
|
||
* bundler rather than the plugin. Observed on a real build: one `resolveId` accumulated
|
||
* ~47,000s of span inside a 44s module-loading window.
|
||
*
|
||
* So overlap is measured rather than assumed, per hook: `overlapMs` is the wall time
|
||
* double counted in `ms` because two or more calls were in flight together. A hook is
|
||
* reported with a number when that is a negligible share of its span, and named without one
|
||
* when it is not.
|
||
*
|
||
* The test is deliberately a tolerance rather than "did this ever happen". A peak in-flight
|
||
* count of 2 can mean one incidental overlap in twenty thousand calls, and discarding a
|
||
* twelve-second measurement over that both throws away good data and makes the report
|
||
* depend on scheduling luck — the same hook would appear in one run and vanish in the next.
|
||
*
|
||
* This keeps the rule the core followed — never present a number that cannot be defended —
|
||
* while narrowing "cannot measure" from a property of the *call site* to a property of the
|
||
* *callback*, which is where it actually lives. A hook dispatched concurrently but whose
|
||
* body barely overlaps is measured to within the tolerance.
|
||
*
|
||
* A measured row is still wall time for that callback rather than CPU: a hook that awaits
|
||
* I/O without overlapping another call of itself is charged for the wait. Excluding the
|
||
* dispatch queue is what this buys; it does not distinguish running from awaiting.
|
||
*/
|
||
/**
|
||
* How much of a hook's span may be double counted before its total stops being reportable,
|
||
* as a fraction of that span.
|
||
*/
|
||
const OVERLAP_TOLERANCE = .01;
|
||
/**
|
||
* One recorder per build, keyed on the object that identifies it.
|
||
*
|
||
* Counters cannot be module-global. A plugin is free to run a nested `rolldown()` build of
|
||
* its own, which finishes first; shared counters would let it flush the outer build's
|
||
* half-accumulated totals and report a window belonging to neither.
|
||
*/
|
||
const recorders = /* @__PURE__ */ new WeakMap();
|
||
/** The recorder for one build, created on first use. */
|
||
function pluginTimingsRecorderFor(key) {
|
||
let recorder = recorders.get(key);
|
||
if (recorder === void 0) {
|
||
recorder = {
|
||
costs: /* @__PURE__ */ new Map(),
|
||
warnedMissingGroupLabels: /* @__PURE__ */ new Set(),
|
||
busyMs: 0,
|
||
inFlight: 0,
|
||
busyStart: 0
|
||
};
|
||
recorders.set(key, recorder);
|
||
}
|
||
return recorder;
|
||
}
|
||
function costFor(recorder, owner, hookName) {
|
||
let byHook = recorder.costs.get(owner.key);
|
||
if (byHook === void 0) {
|
||
byHook = /* @__PURE__ */ new Map();
|
||
recorder.costs.set(owner.key, byHook);
|
||
}
|
||
let cost = byHook.get(hookName);
|
||
if (cost === void 0) {
|
||
cost = {
|
||
owner: owner.name,
|
||
kind: owner.kind,
|
||
hookName,
|
||
calls: 0,
|
||
ms: 0,
|
||
inFlight: 0,
|
||
maxInFlight: 0,
|
||
overlapMs: 0,
|
||
lastChange: 0
|
||
};
|
||
byHook.set(hookName, cost);
|
||
}
|
||
return cost;
|
||
}
|
||
/**
|
||
* Fold the interval since the last in-flight change into `overlapMs`, then move the mark.
|
||
* Call immediately before every increment and decrement of `cost.inFlight`.
|
||
*/
|
||
function markInFlightChange(cost, at) {
|
||
if (cost.inFlight > 1) cost.overlapMs += (cost.inFlight - 1) * (at - cost.lastChange);
|
||
cost.lastChange = at;
|
||
}
|
||
/**
|
||
* Close out one call. A module-level function rather than a closure per invocation: hooks
|
||
* run hundreds of thousands of times in a large build, and the synchronous path would
|
||
* otherwise allocate one closure per call only to invoke it immediately.
|
||
*/
|
||
function settle(recorder, cost, started) {
|
||
const ended = performance.now();
|
||
markInFlightChange(cost, ended);
|
||
cost.inFlight -= 1;
|
||
cost.ms += ended - started;
|
||
recorder.inFlight -= 1;
|
||
if (recorder.inFlight === 0) recorder.busyMs += ended - recorder.busyStart;
|
||
}
|
||
/**
|
||
* Wrap one callback so its execution time is recorded.
|
||
*
|
||
* Returns the callback untouched when there is no recorder, so a build that is not
|
||
* measuring pays nothing beyond one branch at setup.
|
||
*/
|
||
function measureHookCost(recorder, owner, hookName, handler) {
|
||
if (recorder === void 0) return handler;
|
||
const cost = costFor(recorder, owner, hookName);
|
||
return function(...args) {
|
||
const started = performance.now();
|
||
markInFlightChange(cost, started);
|
||
cost.calls += 1;
|
||
cost.inFlight += 1;
|
||
if (cost.inFlight > cost.maxInFlight) cost.maxInFlight = cost.inFlight;
|
||
if (recorder.inFlight === 0) recorder.busyStart = started;
|
||
recorder.inFlight += 1;
|
||
let result;
|
||
try {
|
||
result = handler.apply(this, args);
|
||
} catch (error) {
|
||
settle(recorder, cost, started);
|
||
throw error;
|
||
}
|
||
if (typeof result?.then === "function") return result.then((value) => {
|
||
settle(recorder, cost, started);
|
||
return value;
|
||
}, (error) => {
|
||
settle(recorder, cost, started);
|
||
throw error;
|
||
});
|
||
settle(recorder, cost, started);
|
||
return result;
|
||
};
|
||
}
|
||
/**
|
||
* The shared owner for callbacks that users configure directly on the output options.
|
||
* Code-splitting groups use their group objects as owner keys. Each group then has separate
|
||
* timing rows.
|
||
*/
|
||
const OUTPUT_OPTIONS_OWNER = {
|
||
key: Symbol("output options"),
|
||
name: "output options",
|
||
kind: "outputOption"
|
||
};
|
||
/** As {@link OUTPUT_OPTIONS_OWNER}, for callbacks configured on the input options. */
|
||
const INPUT_OPTIONS_OWNER = {
|
||
key: Symbol("input options"),
|
||
name: "input options",
|
||
kind: "inputOption"
|
||
};
|
||
/**
|
||
* Wrap `value` when the user supplied a function, and leave every other form alone.
|
||
*
|
||
* Most option callbacks are declared as `string | RegExp | Function | ...`, so this keeps
|
||
* the one cast the wrapping needs in a single place.
|
||
*/
|
||
function measureIfFunction(recorder, owner, hookName, value) {
|
||
if (typeof value !== "function") return value;
|
||
return measureHookCost(recorder, owner, hookName, value);
|
||
}
|
||
/**
|
||
* What the build's callbacks have cost so far, leaving the recorder in place.
|
||
*
|
||
* Ungated on purpose: whether a build is worth reporting on is decided from the clocks Rust
|
||
* holds, so the question is not this side's to ask.
|
||
*
|
||
* Rust calls this while the build is closing, so what it gets includes `closeBundle`.
|
||
*/
|
||
function summarizePluginTimings(key) {
|
||
const recorder = recorders.get(key);
|
||
if (recorder === void 0) return {
|
||
busyMs: 0,
|
||
rows: []
|
||
};
|
||
const rows = [];
|
||
for (const byHook of recorder.costs.values()) for (const cost of byHook.values()) {
|
||
if (cost.calls === 0) continue;
|
||
rows.push({
|
||
owner: cost.owner,
|
||
kind: cost.kind,
|
||
hook: cost.hookName,
|
||
calls: cost.calls,
|
||
ms: cost.ms,
|
||
maxInFlight: cost.maxInFlight,
|
||
overlapMs: cost.overlapMs,
|
||
rankable: cost.overlapMs <= cost.ms * OVERLAP_TOLERANCE
|
||
});
|
||
}
|
||
return {
|
||
busyMs: recorder.busyMs,
|
||
rows
|
||
};
|
||
}
|
||
//#endregion
|
||
//#region src/plugin/bindingify-plugin.ts
|
||
function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings) {
|
||
const args = {
|
||
plugin,
|
||
options,
|
||
outputOptions,
|
||
pluginContextData,
|
||
onLog,
|
||
logLevel,
|
||
watchMode,
|
||
normalizedOutputPlugins
|
||
};
|
||
const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
|
||
const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
|
||
const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
|
||
const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
|
||
const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
|
||
const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
|
||
const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
|
||
const { plugin: renderChunk, meta: renderChunkMeta, filter: renderChunkFilter } = bindingifyRenderChunk(args);
|
||
const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
|
||
const { plugin: resolveFileUrl, meta: resolveFileUrlMeta } = bindingifyResolveFileUrl(args);
|
||
const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
|
||
const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
|
||
const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
|
||
const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
|
||
const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
|
||
const { plugin: banner, meta: bannerMeta } = bindingifyAddonHook(args, "banner");
|
||
const { plugin: footer, meta: footerMeta } = bindingifyAddonHook(args, "footer");
|
||
const { plugin: intro, meta: introMeta } = bindingifyAddonHook(args, "intro");
|
||
const { plugin: outro, meta: outroMeta } = bindingifyAddonHook(args, "outro");
|
||
const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
|
||
const { plugin: hotUpdate, meta: hotUpdateMeta } = bindingifyHotUpdate(args);
|
||
const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
|
||
let hookUsage = extractHookUsage(plugin).inner();
|
||
const result = {
|
||
name: plugin.name,
|
||
buildStart,
|
||
buildStartMeta,
|
||
resolveId,
|
||
resolveIdMeta,
|
||
resolveIdFilter,
|
||
resolveDynamicImport,
|
||
resolveDynamicImportMeta,
|
||
buildEnd,
|
||
buildEndMeta,
|
||
transform,
|
||
transformMeta,
|
||
transformFilter,
|
||
moduleParsed,
|
||
moduleParsedMeta,
|
||
load,
|
||
loadMeta,
|
||
loadFilter,
|
||
renderChunk,
|
||
renderChunkMeta,
|
||
renderChunkFilter,
|
||
augmentChunkHash,
|
||
augmentChunkHashMeta,
|
||
resolveFileUrl,
|
||
resolveFileUrlMeta,
|
||
renderStart,
|
||
renderStartMeta,
|
||
renderError,
|
||
renderErrorMeta,
|
||
generateBundle,
|
||
generateBundleMeta,
|
||
writeBundle,
|
||
writeBundleMeta,
|
||
closeBundle,
|
||
closeBundleMeta,
|
||
banner,
|
||
bannerMeta,
|
||
footer,
|
||
footerMeta,
|
||
intro,
|
||
introMeta,
|
||
outro,
|
||
outroMeta,
|
||
watchChange,
|
||
watchChangeMeta,
|
||
hotUpdate,
|
||
hotUpdateMeta,
|
||
closeWatcher,
|
||
closeWatcherMeta,
|
||
hookUsage
|
||
};
|
||
return wrapHandlers(result, {
|
||
key: plugin,
|
||
name: result.name,
|
||
kind: "plugin"
|
||
}, timings);
|
||
}
|
||
function wrapHandlers(plugin, owner, timings) {
|
||
for (const hookName of [
|
||
"buildStart",
|
||
"resolveId",
|
||
"resolveDynamicImport",
|
||
"buildEnd",
|
||
"transform",
|
||
"moduleParsed",
|
||
"load",
|
||
"renderChunk",
|
||
"augmentChunkHash",
|
||
"resolveFileUrl",
|
||
"renderStart",
|
||
"renderError",
|
||
"generateBundle",
|
||
"writeBundle",
|
||
"closeBundle",
|
||
"banner",
|
||
"footer",
|
||
"intro",
|
||
"outro",
|
||
"watchChange",
|
||
"hotUpdate",
|
||
"closeWatcher"
|
||
]) {
|
||
const raw = plugin[hookName];
|
||
const handler = raw && measureHookCost(timings, owner, hookName, raw);
|
||
if (handler) plugin[hookName] = async (...args) => {
|
||
try {
|
||
return await handler(...args);
|
||
} catch (e) {
|
||
return error(logPluginError(e, plugin.name, {
|
||
hook: hookName,
|
||
id: hookName === "transform" ? args[2] : void 0
|
||
}));
|
||
}
|
||
};
|
||
}
|
||
return plugin;
|
||
}
|
||
//#endregion
|
||
//#region src/utils/normalize-transform-options.ts
|
||
/**
|
||
* Normalizes transform options by extracting `define`, `inject`, and `dropLabels` separately from OXC transform options.
|
||
*
|
||
* Prioritizes values from `transform.define`, `transform.inject`, and `transform.dropLabels` over deprecated top-level options.
|
||
*/
|
||
function normalizeTransformOptions(inputOptions) {
|
||
const transform = inputOptions.transform;
|
||
const define = transform?.define ? Object.entries(transform.define) : void 0;
|
||
const inject = transform?.inject;
|
||
const dropLabels = transform?.dropLabels;
|
||
let oxcTransformOptions;
|
||
if (transform) {
|
||
const { define: _define, inject: _inject, dropLabels: _dropLabels, ...rest } = transform;
|
||
if (Object.keys(rest).length > 0) {
|
||
if (rest.jsx === false) rest.jsx = "disable";
|
||
oxcTransformOptions = rest;
|
||
}
|
||
}
|
||
return {
|
||
define,
|
||
inject,
|
||
dropLabels,
|
||
oxcTransformOptions
|
||
};
|
||
}
|
||
//#endregion
|
||
//#region src/utils/default-dev-runtime.ts
|
||
function getDefaultDevRuntime(host = "localhost", port = 3e3) {
|
||
return "// @ts-check\n\nclass Module {\n /**\n * @type {{ exports: any }}\n */\n exportsHolder = { exports: null };\n /**\n * @type {string}\n */\n id;\n\n /**\n * @param {string} id\n */\n constructor(id) {\n this.id = id;\n }\n\n get exports() {\n return this.exportsHolder.exports;\n }\n}\n\n/**\n * Compiler-emitted module-graph delta — topology (static + dynamic edges).\n * `ids[0, localCount)` are the modules this payload carries; `ids[localCount, …)` are foreign edge targets.\n * `edges[i]` / `dynamicEdges[i]` are the static / dynamic-`import()` out-edges of `ids[i]`.\n * `bindings[i][j]` are the export names `ids[i]` imports through `edges[i][j]`. `bindings` holds\n * only some rows; a missing row, or a missing or `null` entry, means the whole namespace.\n * `dynamicEdges` also holds only some rows; a missing row means no dynamic edges.\n * @typedef {{ ids: string[], localCount: number, edges: number[][], bindings?: Record<number, (string[] | null)[]>, dynamicEdges?: Record<number, number[]> }} ModuleGraphDelta\n * @typedef {{ createModuleHotContext(moduleId: string): any, onModuleCacheRemoval(moduleId: string): void }} DevRuntimeHooks\n */\n\nexport class MissingFactoryError extends Error {\n /**\n * @param {string} id\n */\n constructor(id) {\n super(`No factory registered for module ${id}`);\n this.id = id;\n }\n}\n\nexport class DevRuntime {\n /**\n * Client ID generated at runtime initialization, used for lazy compilation requests.\n * @type {string}\n */\n clientId;\n\n /**\n * @param {string} clientId\n */\n constructor(clientId) {\n this.clientId = clientId;\n }\n\n /**\n * Static import edges from `registerGraph` — entries persist across `removeModuleCache`\n * and change only by replacement from a newer payload (last write wins).\n * `bindings` is the payload row as sent; `getImportedBindings` resolves a missing entry.\n * @type {Map<string, { edges: string[], bindings: (string[] | null)[] | undefined }>}\n */\n staticImports = new Map();\n /**\n * Reverse index over the static imports.\n * @type {Map<string, Set<string>>}\n */\n importers = new Map();\n /**\n * Dynamic `import()` edges from `registerGraph`, keyed by importer — mirror of\n * `staticImports` for the dynamic reverse index.\n * @type {Map<string, { edges: string[] }>}\n */\n dynamicImports = new Map();\n /**\n * Reverse index over the dynamic imports.\n * @type {Map<string, Set<string>>}\n */\n dynamicImporters = new Map();\n /**\n * The module cache. Membership means \"this module's side effects ran in this tab\" —\n * registration is emitted ahead of every module body, and nothing un-registers on\n * unwind, so a factory that throws mid-body stays registered. A `Map` rather than a\n * plain object: HMR eviction deletes entries, and a `delete` on an object drops V8\n * into dictionary mode, taxing every later lookup on the hottest read path.\n * @type {Map<string, Module>}\n */\n moduleCache = new Map();\n /**\n * Re-runnable factories from HMR patches and lazy chunks. The initial bundle stays\n * scope-hoisted and contributes none.\n * @type {Map<string, (id: string) => void>}\n */\n factories = new Map();\n /**\n * Installed by the dev client at boot. The runtime is a store + executor and makes\n * no HMR decisions; accepting, disposing, and reloading live behind these hooks.\n * @type {DevRuntimeHooks | null}\n */\n hooks = null;\n\n /**\n * @param {ModuleGraphDelta} delta\n */\n registerGraph(delta) {\n for (let i = 0; i < delta.localCount; i++) {\n const id = delta.ids[i];\n const edges = delta.edges[i].map((j) => delta.ids[j]);\n for (const target of this.staticImports.get(id)?.edges ?? []) {\n this.importers.get(target)?.delete(id);\n }\n for (const target of edges) {\n let importerSet = this.importers.get(target);\n if (!importerSet) {\n importerSet = new Set();\n this.importers.set(target, importerSet);\n }\n importerSet.add(id);\n }\n this.staticImports.set(id, { edges, bindings: delta.bindings?.[i] });\n\n // Dynamic `import()` edges are maintained in a parallel reverse index with the same\n // last-write-wins bookkeeping; `getImporters` unions the two.\n const dynamicEdges = (delta.dynamicEdges?.[i] ?? []).map((j) => delta.ids[j]);\n for (const target of this.dynamicImports.get(id)?.edges ?? []) {\n this.dynamicImporters.get(target)?.delete(id);\n }\n for (const target of dynamicEdges) {\n let importerSet = this.dynamicImporters.get(target);\n if (!importerSet) {\n importerSet = new Set();\n this.dynamicImporters.set(target, importerSet);\n }\n importerSet.add(id);\n }\n this.dynamicImports.set(id, { edges: dynamicEdges });\n }\n }\n\n /**\n * @param {string} id\n * @param {(id: string) => void} fn\n */\n registerFactory(id, fn) {\n this.factories.set(id, fn);\n }\n\n /**\n * @param {string} id\n * @param {{ exports: any }} [exportsHolder]\n */\n registerModule(id, exportsHolder = { exports: {} }) {\n const module = new Module(id);\n module.exportsHolder = exportsHolder;\n this.moduleCache.set(id, module);\n }\n\n /**\n * @param {string} id\n * @returns {string[]}\n */\n getImporters(id) {\n // Static ∪ dynamic importers — the boundary walk treats both kinds the same (parity\n // with Vite `node.importers` / webpack `module.parents`). Deduped so a module that\n // imports `id` both statically and via `import()` appears once.\n const dynamic = this.dynamicImporters.get(id);\n if (!dynamic || dynamic.size === 0) {\n return [...(this.importers.get(id) ?? [])];\n }\n return [...new Set([...(this.importers.get(id) ?? []), ...dynamic])];\n }\n\n /**\n * `\"*\"` means the whole namespace, an empty list a side-effect-only import, `undefined` no edge.\n * @param {string} importer\n * @param {string} id\n * @returns {string[] | undefined}\n */\n getImportedBindings(importer, id) {\n const record = this.staticImports.get(importer);\n const j = record ? record.edges.indexOf(id) : -1;\n const names = j === -1 ? undefined : (record?.bindings?.[j] ?? ['*']);\n if (!this.dynamicImports.get(importer)?.edges.includes(id)) {\n return names;\n }\n if (!names) return ['*'];\n return names.includes('*') ? names : [...names, '*'];\n }\n\n /**\n * @param {string} id\n */\n isExecuted(id) {\n return this.moduleCache.has(id);\n }\n\n /**\n * @param {string} id\n */\n hasFactory(id) {\n return this.factories.has(id);\n }\n\n /**\n * Module-cache delete only — static imports and factories persist. Removal is what\n * re-arms a cache-gated factory for `initModule`.\n * @param {string} id\n */\n removeModuleCache(id) {\n this.moduleCache.delete(id);\n this.hooks?.onModuleCacheRemoval(id);\n }\n\n /**\n * The one re-execution gate: registered → return the live exports; otherwise run the\n * mapped factory (which registers itself first, then runs the body).\n * @param {string} id\n */\n initModule(id) {\n if (this.moduleCache.has(id)) {\n return this.loadExports(id);\n }\n const factory = this.factories.get(id);\n if (!factory) {\n throw new MissingFactoryError(id);\n }\n factory(id);\n return this.loadExports(id);\n }\n\n /**\n * @param {string} id\n */\n loadExports(id) {\n const module = this.moduleCache.get(id);\n if (module) {\n return module.exportsHolder.exports;\n } else {\n console.warn(`Module ${id} not found`);\n return {};\n }\n }\n\n /**\n * @param {string} moduleId\n */\n createModuleHotContext(moduleId) {\n if (this.hooks) {\n return this.hooks.createModuleHotContext(moduleId);\n }\n throw new Error('createModuleHotContext requires installed hooks or an override');\n }\n\n /** @internal */\n // @ts-expect-error The variable will be injected at build time.\n __toESM = __toESM;\n /** @internal */\n // @ts-expect-error The variable will be injected at build time.\n __toCommonJS = __toCommonJS;\n /** @internal */\n // @ts-expect-error The variable will be injected at build time.\n __exportAll = __exportAll;\n /**\n * @param {boolean} [isNodeMode]\n * @returns {(mod: any) => any}\n * @internal\n */\n // @ts-expect-error The variable will be injected at build time.\n __toDynamicImportESM = (isNodeMode) => (mod) => __toESM(mod.default, isNodeMode);\n /** @internal */\n // @ts-expect-error The variable will be injected at build time.\n __reExport = __reExport;\n}\n\n// @ts-check\n\n/** @import { DevRuntime } from './runtime-extra-dev-common.js' */\n\n/** @type {typeof DevRuntime} */\n// @ts-expect-error -- there's no way to declare a variable by JSDoc\nvar BaseDevRuntime = DevRuntime;\n\nclass ModuleHotContext {\n /**\n * @type {{ deps: [string], fn: (moduleExports: Record<string, any>[]) => void }[]}\n */\n acceptCallbacks = [];\n /**\n * @param {string} moduleId\n * @param {InstanceType<BaseDevRuntime>} devRuntime\n */\n constructor(moduleId, devRuntime) {\n this.moduleId = moduleId;\n this.devRuntime = devRuntime;\n }\n\n /**\n * @overload\n * @param {(mod: Record<string, any>) => void} cb\n * @returns {void}\n */\n /**\n * @param {...any} args\n * @returns {void}\n */\n accept(...args) {\n if (args.length === 1) {\n const [cb] = /** @type {[(mod: Record<string, any>) => void]} */ (args);\n const acceptingPath = this.moduleId;\n this.acceptCallbacks.push({\n deps: [acceptingPath],\n fn: cb,\n });\n } else if (args.length === 0) {}\n else {\n throw new Error('Invalid arguments for `import.meta.hot.accept`');\n }\n }\n\n invalidate() {\n socket.send(JSON.stringify({\n type: 'hmr:invalidate',\n moduleId: this.moduleId,\n }));\n }\n}\n\nclass DefaultDevRuntime extends BaseDevRuntime {\n /**\n * @type {Map<string, ModuleHotContext>}\n */\n moduleHotContexts = new Map();\n /**\n * @override\n * @param {string} moduleId\n */\n createModuleHotContext(moduleId) {\n const hotContext = new ModuleHotContext(moduleId, this);\n this.moduleHotContexts.set(moduleId, hotContext);\n return hotContext;\n }\n}\n\n/** @param {string} url */\nfunction loadScript(url) {\n var script = document.createElement('script');\n script.src = url;\n script.type = 'module';\n script.onerror = function() {\n console.error('Failed to load script: ' + url);\n };\n document.body.appendChild(script);\n}\n\nconsole.debug('HMR runtime loaded', '$ADDR');\n// Generate client ID immediately at runtime initialization\n// This ensures the client ID is available before any lazy imports\nconst clientId = crypto.randomUUID();\nconst addr = new URL('ws://$ADDR');\naddr.searchParams.set('clientId', clientId);\n\nconst socket = new WebSocket(addr);\n\n(/** @type {any} */ (globalThis)).__rolldown_runtime__ ??=\n new DefaultDevRuntime(clientId);\n\n/** @param {MessageEvent} event */\nsocket.onmessage = function(event) {\n const data = JSON.parse(event.data);\n console.debug('Received message:', data);\n if (data.type === 'connected') {\n // Server acknowledged the connection\n console.debug('[hmr]: Connection established with server');\n } else if (data.type === 'hmr:update') {\n if (typeof process === 'object') {\n import(data.path);\n console.debug(`[hmr]: Importing HMR patch: ${data.path}`);\n } else {\n console.debug(`[hmr]: Loading HMR patch: ${data.path}`);\n loadScript(data.url);\n }\n } else if (data.type === 'hmr:reload') {\n console.log('[hmr]: Full reload required, reloading page');\n if (typeof location !== 'undefined') {\n location.reload();\n } else {\n console.log('[hmr]: location is undefined, cannot reload page');\n }\n }\n};\n".replaceAll("$ADDR", `${host}:${port}`);
|
||
}
|
||
//#endregion
|
||
//#region src/utils/bindingify-input-options.ts
|
||
function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings) {
|
||
const plugins = rawPlugins.map((plugin) => {
|
||
if (getParallelPluginInfo(plugin)) return;
|
||
if (plugin instanceof BuiltinPlugin) switch (plugin.name) {
|
||
case "builtin:vite-manifest": return bindingifyManifestPlugin(plugin, pluginContextData);
|
||
default: return bindingifyBuiltInPlugin(plugin);
|
||
}
|
||
return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings);
|
||
});
|
||
const normalizedTransform = normalizeTransformOptions(inputOptions);
|
||
return {
|
||
input: bindingifyInput(inputOptions.input),
|
||
plugins,
|
||
cwd: inputOptions.cwd ?? process.cwd(),
|
||
external: bindingifyExternal(inputOptions.external, timings),
|
||
resolve: bindingifyResolve(inputOptions.resolve),
|
||
platform: inputOptions.platform,
|
||
shimMissingExports: inputOptions.shimMissingExports,
|
||
logLevel: bindingifyLogLevel(logLevel),
|
||
onLog,
|
||
treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake, timings),
|
||
moduleTypes: inputOptions.moduleTypes,
|
||
define: normalizedTransform.define,
|
||
inject: bindingifyInject(normalizedTransform.inject),
|
||
experimental: bindingifyExperimental(inputOptions.experimental),
|
||
profilerNames: outputOptions.generatedCode?.profilerNames,
|
||
transform: normalizedTransform.oxcTransformOptions,
|
||
watch: bindingifyWatch(inputOptions.watch),
|
||
dropLabels: normalizedTransform.dropLabels,
|
||
keepNames: outputOptions.keepNames,
|
||
checks: inputOptions.checks,
|
||
pluginTimings: timings ? () => summarizePluginTimings(inputOptions) : void 0,
|
||
deferSyncScanData: () => {
|
||
let ret = [];
|
||
pluginContextData.moduleOptionMap.forEach((value, key) => {
|
||
if (value.invalidate) ret.push({
|
||
id: key,
|
||
sideEffects: value.moduleSideEffects ?? void 0
|
||
});
|
||
});
|
||
return ret;
|
||
},
|
||
makeAbsoluteExternalsRelative: bindingifyMakeAbsoluteExternalsRelative(inputOptions.makeAbsoluteExternalsRelative),
|
||
devtools: inputOptions.devtools,
|
||
invalidateJsSideCache: pluginContextData.clear.bind(pluginContextData),
|
||
preserveEntrySignatures: bindingifyPreserveEntrySignatures(inputOptions.preserveEntrySignatures),
|
||
optimization: inputOptions.optimization,
|
||
context: inputOptions.context,
|
||
tsconfig: inputOptions.resolve?.tsconfigFilename ?? inputOptions.tsconfig
|
||
};
|
||
}
|
||
function bindingifyDevMode(devMode) {
|
||
if (devMode) {
|
||
if (typeof devMode === "boolean") return devMode ? {
|
||
implement: getDefaultDevRuntime(),
|
||
skipCommonRuntimeInjection: true
|
||
} : void 0;
|
||
const usesDefaultRuntime = devMode.implement == null;
|
||
return {
|
||
...devMode,
|
||
implement: devMode.implement ?? getDefaultDevRuntime(devMode.host, devMode.port),
|
||
skipCommonRuntimeInjection: usesDefaultRuntime ? true : devMode.skipCommonRuntimeInjection
|
||
};
|
||
}
|
||
}
|
||
function bindingifyAttachDebugInfo(attachDebugInfo) {
|
||
switch (attachDebugInfo) {
|
||
case void 0: return;
|
||
case "full": return import_binding.BindingAttachDebugInfo.Full;
|
||
case "simple": return import_binding.BindingAttachDebugInfo.Simple;
|
||
case "none": return import_binding.BindingAttachDebugInfo.None;
|
||
}
|
||
}
|
||
function bindingifyExternal(external, timings) {
|
||
if (external) {
|
||
if (typeof external === "function") {
|
||
const measured = measureHookCost(timings, INPUT_OPTIONS_OWNER, "external", external);
|
||
return (id, importer, isResolved) => {
|
||
if (id.startsWith("\0")) return false;
|
||
return measured(id, importer, isResolved) ?? false;
|
||
};
|
||
}
|
||
return arraify(external);
|
||
}
|
||
}
|
||
function bindingifyExperimental(experimental) {
|
||
let chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ExecOrder;
|
||
if (experimental?.chunkModulesOrder) switch (experimental.chunkModulesOrder) {
|
||
case "exec-order":
|
||
chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ExecOrder;
|
||
break;
|
||
case "module-id":
|
||
chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ModuleId;
|
||
break;
|
||
default: throw new Error(`Unexpected chunkModulesOrder: ${experimental.chunkModulesOrder}`);
|
||
}
|
||
return {
|
||
viteMode: experimental?.viteMode,
|
||
resolveNewUrlToAsset: experimental?.resolveNewUrlToAsset,
|
||
devMode: bindingifyDevMode(experimental?.devMode),
|
||
attachDebugInfo: bindingifyAttachDebugInfo(experimental?.attachDebugInfo),
|
||
chunkModulesOrder,
|
||
chunkImportMap: experimental?.chunkImportMap,
|
||
onDemandWrapping: experimental?.onDemandWrapping,
|
||
incrementalBuild: experimental?.incrementalBuild,
|
||
nativeMagicString: experimental?.nativeMagicString,
|
||
chunkOptimization: experimental?.chunkOptimization,
|
||
lazyBarrel: experimental?.lazyBarrel
|
||
};
|
||
}
|
||
function bindingifyResolve(resolve) {
|
||
const yarnPnp = typeof process === "object" && !!process.versions?.pnp;
|
||
if (resolve) {
|
||
const { alias, extensionAlias, ...rest } = resolve;
|
||
return {
|
||
alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
|
||
find: name,
|
||
replacements: replacement === false ? [void 0] : arraify(replacement)
|
||
})) : void 0,
|
||
extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
|
||
target: name,
|
||
replacements: value
|
||
})) : void 0,
|
||
yarnPnp,
|
||
...rest
|
||
};
|
||
} else return { yarnPnp };
|
||
}
|
||
function bindingifyInject(inject) {
|
||
if (inject) return Object.entries(inject).map(([alias, item]) => {
|
||
if (Array.isArray(item)) {
|
||
if (item[1] === "*") return {
|
||
tagNamespace: true,
|
||
alias,
|
||
from: item[0]
|
||
};
|
||
return {
|
||
tagNamed: true,
|
||
alias,
|
||
from: item[0],
|
||
imported: item[1]
|
||
};
|
||
} else return {
|
||
tagNamed: true,
|
||
imported: "default",
|
||
alias,
|
||
from: item
|
||
};
|
||
});
|
||
}
|
||
function bindingifyLogLevel(logLevel) {
|
||
switch (logLevel) {
|
||
case "silent": return import_binding.BindingLogLevel.Silent;
|
||
case "debug": return import_binding.BindingLogLevel.Debug;
|
||
case "warn": return import_binding.BindingLogLevel.Warn;
|
||
case "info": return import_binding.BindingLogLevel.Info;
|
||
default: throw new Error(`Unexpected log level: ${logLevel}`);
|
||
}
|
||
}
|
||
function bindingifyInput(input) {
|
||
if (input === void 0) return [];
|
||
if (typeof input === "string") return [{ import: input }];
|
||
if (Array.isArray(input)) return input.map((src) => ({ import: src }));
|
||
return Object.entries(input).map(([name, import_path]) => {
|
||
return {
|
||
name,
|
||
import: import_path
|
||
};
|
||
});
|
||
}
|
||
function bindingifyWatch(watch) {
|
||
if (watch) {
|
||
const watcher = watch.watcher ?? {};
|
||
return {
|
||
buildDelay: watch.buildDelay,
|
||
skipWrite: watch.skipWrite,
|
||
usePolling: watcher.usePolling,
|
||
pollInterval: watcher.pollInterval,
|
||
compareContentsForPolling: watcher.compareContentsForPolling,
|
||
useDebounce: watcher.useDebounce,
|
||
debounceDelay: watcher.debounceDelay,
|
||
debounceTickRate: watcher.debounceTickRate,
|
||
include: normalizedStringOrRegex(watch.include),
|
||
exclude: normalizedStringOrRegex(watch.exclude),
|
||
onInvalidate: (...args) => watch.onInvalidate?.(...args)
|
||
};
|
||
}
|
||
}
|
||
function bindingifyTreeshakeOptions(config, timings) {
|
||
if (config === false) return;
|
||
if (config === true || config === void 0) return { moduleSideEffects: true };
|
||
let normalizedConfig = {
|
||
moduleSideEffects: true,
|
||
annotations: config.annotations,
|
||
manualPureFunctions: config.manualPureFunctions,
|
||
unknownGlobalSideEffects: config.unknownGlobalSideEffects,
|
||
invalidImportSideEffects: config.invalidImportSideEffects,
|
||
commonjs: config.commonjs
|
||
};
|
||
switch (config.propertyReadSideEffects) {
|
||
case "always":
|
||
normalizedConfig.propertyReadSideEffects = import_binding.BindingPropertyReadSideEffects.Always;
|
||
break;
|
||
case false: normalizedConfig.propertyReadSideEffects = import_binding.BindingPropertyReadSideEffects.False;
|
||
}
|
||
switch (config.propertyWriteSideEffects) {
|
||
case "always":
|
||
normalizedConfig.propertyWriteSideEffects = import_binding.BindingPropertyWriteSideEffects.Always;
|
||
break;
|
||
case false: normalizedConfig.propertyWriteSideEffects = import_binding.BindingPropertyWriteSideEffects.False;
|
||
}
|
||
if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
|
||
else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
|
||
external: true,
|
||
sideEffects: false
|
||
}, {
|
||
external: false,
|
||
sideEffects: true
|
||
}];
|
||
else normalizedConfig.moduleSideEffects = measureIfFunction(timings, INPUT_OPTIONS_OWNER, "treeshake.moduleSideEffects", config.moduleSideEffects);
|
||
return normalizedConfig;
|
||
}
|
||
function bindingifyMakeAbsoluteExternalsRelative(makeAbsoluteExternalsRelative) {
|
||
if (makeAbsoluteExternalsRelative === "ifRelativeSource") return { type: "IfRelativeSource" };
|
||
if (typeof makeAbsoluteExternalsRelative === "boolean") return {
|
||
type: "Bool",
|
||
field0: makeAbsoluteExternalsRelative
|
||
};
|
||
}
|
||
function bindingifyPreserveEntrySignatures(preserveEntrySignatures) {
|
||
if (preserveEntrySignatures == void 0) return;
|
||
else if (typeof preserveEntrySignatures === "string") return {
|
||
type: "String",
|
||
field0: preserveEntrySignatures
|
||
};
|
||
else return {
|
||
type: "Bool",
|
||
field0: preserveEntrySignatures
|
||
};
|
||
}
|
||
//#endregion
|
||
export { LOG_LEVEL_WARN as C, version as D, package_default as E, LOG_LEVEL_INFO as S, VERSION as T, getParallelPluginInfo as _, measureIfFunction as a, LOG_LEVEL_DEBUG as b, PluginContextData as c, transformRenderedChunk as d, __decorate as f, MinimalPluginContextImpl as g, PlainObjectLike as h, measureHookCost as i, transformModuleInfo as l, lazyProp as m, bindingifyPlugin as n, pluginTimingsRecorderFor as o, transformAssetSource as p, OUTPUT_OPTIONS_OWNER as r, RolldownMagicString as s, bindingifyInputOptions as t, transformToRollupOutput as u, normalizeHook as v, logLevelPriority as w, LOG_LEVEL_ERROR as x, normalizeLog as y };
|