bindingify-input-options-DCTviPFW.mjs 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602
  1. import { n as __toESM, t as require_binding } from "./binding-B4m_2rFW.mjs";
  2. import { i as logFailedValidation, n as error, o as logInvalidLogPosition, r as logCycleLoading, t as augmentCodeLocation, u as logPluginError } from "./logs-D6uA606S.mjs";
  3. import { i as bindingifyManifestPlugin, n as BuiltinPlugin, r as bindingifyBuiltInPlugin, t as normalizedStringOrRegex } from "./normalize-string-or-regex-xyy0kCQR.mjs";
  4. import { i as noop, n as isPathFragment, o as unreachable, s as unsupported, t as arraify } from "./misc-DOSKtd97.mjs";
  5. import { a as bindingifySourcemap, i as unwrapBindingResult, t as aggregateBindingErrorsIntoJsError } from "./error-Bj1xBdEY.mjs";
  6. import { parseAst } from "../parse-ast-index.mjs";
  7. import path from "node:path";
  8. import * as filter from "@rolldown/pluginutils";
  9. import fsp from "node:fs/promises";
  10. //#region package.json
  11. var version = "1.2.12";
  12. var package_default = {
  13. name: "rolldown",
  14. version,
  15. description: "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.",
  16. keywords: [
  17. "bundler",
  18. "esbuild",
  19. "parcel",
  20. "rolldown",
  21. "rollup",
  22. "webpack"
  23. ],
  24. homepage: "https://rolldown.rs/",
  25. bugs: { "url": "https://github.com/rolldown/rolldown/issues" },
  26. license: "MIT",
  27. repository: {
  28. "type": "git",
  29. "url": "git+https://github.com/rolldown/rolldown.git",
  30. "directory": "packages/rolldown"
  31. },
  32. bin: { "rolldown": "./bin/cli.mjs" },
  33. files: [
  34. "bin",
  35. "cli",
  36. "dist",
  37. "LICENSE",
  38. "THIRD-PARTY-LICENSE",
  39. "!dist/*.node"
  40. ],
  41. type: "module",
  42. main: "./dist/index.mjs",
  43. module: "./dist/index.mjs",
  44. types: "./dist/index.d.mts",
  45. imports: { "#parallel-plugin-worker": "./dist/parallel-plugin-worker.mjs" },
  46. exports: {
  47. ".": {
  48. "dev": "./src/index.ts",
  49. "default": "./dist/index.mjs"
  50. },
  51. "./config": {
  52. "dev": "./src/config.ts",
  53. "default": "./dist/config.mjs"
  54. },
  55. "./experimental": {
  56. "dev": "./src/experimental-index.ts",
  57. "default": "./dist/experimental-index.mjs"
  58. },
  59. "./experimental/runtime-types": { "types": "./dist/experimental-runtime-types.d.ts" },
  60. "./experimental/runtime": {
  61. "types": "./dist/experimental-runtime.d.ts",
  62. "default": "./dist/experimental-runtime.mjs"
  63. },
  64. "./filter": {
  65. "dev": "./src/filter-index.ts",
  66. "default": "./dist/filter-index.mjs"
  67. },
  68. "./getLogFilter": {
  69. "dev": "./src/get-log-filter.ts",
  70. "default": "./dist/get-log-filter.mjs"
  71. },
  72. "./parallelPlugin": {
  73. "dev": "./src/parallel-plugin.ts",
  74. "default": "./dist/parallel-plugin.mjs"
  75. },
  76. "./parseAst": {
  77. "dev": "./src/parse-ast-index.ts",
  78. "default": "./dist/parse-ast-index.mjs"
  79. },
  80. "./package.json": "./package.json",
  81. "./plugins": {
  82. "dev": "./src/plugins-index.ts",
  83. "default": "./dist/plugins-index.mjs"
  84. },
  85. "./utils": {
  86. "dev": "./src/utils-index.ts",
  87. "default": "./dist/utils-index.mjs"
  88. }
  89. },
  90. publishConfig: {
  91. "exports": {
  92. ".": "./dist/index.mjs",
  93. "./config": "./dist/config.mjs",
  94. "./experimental": "./dist/experimental-index.mjs",
  95. "./experimental/runtime-types": { "types": "./dist/experimental-runtime-types.d.ts" },
  96. "./experimental/runtime": {
  97. "types": "./dist/experimental-runtime.d.ts",
  98. "default": "./dist/experimental-runtime.mjs"
  99. },
  100. "./filter": "./dist/filter-index.mjs",
  101. "./getLogFilter": "./dist/get-log-filter.mjs",
  102. "./parallelPlugin": "./dist/parallel-plugin.mjs",
  103. "./parseAst": "./dist/parse-ast-index.mjs",
  104. "./package.json": "./package.json",
  105. "./plugins": "./dist/plugins-index.mjs",
  106. "./utils": "./dist/utils-index.mjs"
  107. },
  108. "access": "public",
  109. "registry": "https://registry.npmjs.org/"
  110. },
  111. scripts: {
  112. "# Scrips for binding #": "_",
  113. "artifacts": "napi artifacts --cwd ./src --package-json-path ../package.json -o=../artifacts --npm-dir ../npm",
  114. "build-binding": "oxnode ./build-binding.ts",
  115. "build-binding:release": "pnpm build-binding --release",
  116. "build-binding:profile": "pnpm build-binding --profile profile --features chrome-tracing",
  117. "build-binding:wasi": "pnpm build-binding --target wasm32-wasip1-threads",
  118. "build-binding:wasi:release": "pnpm build-binding --profile release-wasi --target wasm32-wasip1-threads",
  119. "# Scrips for node #": "_",
  120. "build-node": "node --enable-source-maps --import @oxc-node/core/register -C dev ./build.ts",
  121. "build-types-check": "tsc -p ./tsconfig.check.json",
  122. "build-js-glue": "pnpm run --sequential '/^build-(node|types-check)$/'",
  123. "build-native:debug": "pnpm run --sequential '/^build-(binding|js-glue)$/'",
  124. "build-native:release": "pnpm run --sequential '/^build-(binding:release|js-glue)$/'",
  125. "build-native:profile": "pnpm run build-binding:profile && pnpm run build-js-glue",
  126. "build-native:memory-profile": "pnpm run build-binding:profile --features default_global_allocator && pnpm run build-js-glue",
  127. "build-wasi:debug": "TARGET='rolldown-wasi' pnpm run --sequential '/^build-(binding|binding:wasi|node)$/'",
  128. "build-wasi:release": "TARGET='rolldown-wasi' pnpm run --sequential '/^build-(binding|binding:wasi:release|node)$/'",
  129. "build-browser-pkg:debug": "TARGET='browser' pnpm run --sequential '/^build-(binding:wasi|node)$/'",
  130. "build-browser-pkg:release": "TARGET='browser' pnpm run --sequential '/^build-(binding:wasi:release|node)$/'",
  131. "# Scrips for docs #": "_",
  132. "prepublishOnly": "napi pre-publish -t npm --no-gh-release ${NAPI_DRY_RUN:+--dry-run} ${NAPI_SKIP_OPTIONAL_PUBLISH:+--skip-optional-publish}",
  133. "publint": "publint ."
  134. },
  135. dependencies: {
  136. "@oxc-project/types": "catalog:",
  137. "@rolldown/pluginutils": "catalog:"
  138. },
  139. devDependencies: {
  140. "@emnapi/core": "catalog:",
  141. "@emnapi/runtime": "catalog:",
  142. "@napi-rs/cli": "catalog:",
  143. "@napi-rs/wasm-runtime": "catalog:",
  144. "@oxc-node/cli": "catalog:",
  145. "cac": "catalog:",
  146. "consola": "catalog:",
  147. "emnapi": "catalog:",
  148. "execa": "catalog:",
  149. "fresh-import": "catalog:",
  150. "glob": "catalog:",
  151. "oxc-parser": "catalog:",
  152. "pathe": "catalog:",
  153. "remeda": "catalog:",
  154. "rolldown": "workspace:*",
  155. "rolldown-plugin-dts": "catalog:",
  156. "rollup": "catalog:",
  157. "signal-exit": "catalog:",
  158. "source-map": "catalog:",
  159. "typescript": "catalog:",
  160. "valibot": "catalog:"
  161. },
  162. napi: {
  163. "binaryName": "rolldown-binding",
  164. "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",
  165. "packageName": "@rolldown/binding",
  166. "targets": [
  167. "aarch64-apple-darwin",
  168. "aarch64-linux-android",
  169. "aarch64-pc-windows-msvc",
  170. "aarch64-unknown-linux-gnu",
  171. "aarch64-unknown-linux-musl",
  172. "aarch64-unknown-linux-ohos",
  173. "armv7-linux-androideabi",
  174. "armv7-unknown-linux-gnueabihf",
  175. "powerpc64le-unknown-linux-gnu",
  176. "s390x-unknown-linux-gnu",
  177. "wasm32-wasip1-threads",
  178. "x86_64-apple-darwin",
  179. "x86_64-pc-windows-msvc",
  180. "x86_64-unknown-freebsd",
  181. "x86_64-unknown-linux-gnu",
  182. "x86_64-unknown-linux-musl"
  183. ],
  184. "wasm": {
  185. "initialMemory": 16384,
  186. "browser": {
  187. "fs": true,
  188. "asyncInit": true,
  189. "errorEvent": true
  190. }
  191. }
  192. },
  193. engines: { "node": "^20.19.0 || >=22.12.0" }
  194. };
  195. //#endregion
  196. //#region src/constants/version.ts
  197. /**
  198. * The version of Rolldown.
  199. * @example `'1.0.0'`
  200. *
  201. * @category Plugin APIs
  202. */
  203. const VERSION = version;
  204. //#endregion
  205. //#region src/log/logging.ts
  206. const LOG_LEVEL_SILENT = "silent";
  207. const LOG_LEVEL_ERROR = "error";
  208. const LOG_LEVEL_WARN = "warn";
  209. const LOG_LEVEL_INFO = "info";
  210. const LOG_LEVEL_DEBUG = "debug";
  211. const logLevelPriority = {
  212. [LOG_LEVEL_DEBUG]: 0,
  213. [LOG_LEVEL_INFO]: 1,
  214. [LOG_LEVEL_WARN]: 2,
  215. [LOG_LEVEL_SILENT]: 3
  216. };
  217. //#endregion
  218. //#region src/log/log-handler.ts
  219. const normalizeLog = (log) => typeof log === "string" ? { message: log } : typeof log === "function" ? normalizeLog(log()) : log;
  220. function getLogHandler(level, code, logger, pluginName, logLevel) {
  221. if (logLevelPriority[level] < logLevelPriority[logLevel]) return noop;
  222. return (log, pos) => {
  223. if (pos != null) logger(LOG_LEVEL_WARN, logInvalidLogPosition(pluginName));
  224. log = normalizeLog(log);
  225. if (log.code && !log.pluginCode) log.pluginCode = log.code;
  226. log.code = code;
  227. log.plugin = pluginName;
  228. logger(level, log);
  229. };
  230. }
  231. //#endregion
  232. //#region src/utils/normalize-hook.ts
  233. function normalizeHook(hook) {
  234. if (typeof hook === "function" || typeof hook === "string") return {
  235. handler: hook,
  236. options: {},
  237. meta: {}
  238. };
  239. if (typeof hook === "object" && hook !== null) {
  240. const { handler, order, ...options } = hook;
  241. return {
  242. handler,
  243. options,
  244. meta: { order }
  245. };
  246. }
  247. unreachable("Invalid hook type");
  248. }
  249. //#endregion
  250. //#region src/utils/parallel-plugin.ts
  251. /**
  252. * Returns the `_parallel` marker of a parallel plugin, or `undefined` if the
  253. * given plugin is not one.
  254. *
  255. * Detection is descriptor-based instead of using the `in` operator: only an
  256. * own data property named `_parallel` with the expected shape counts. This
  257. * avoids false positives from inherited or accessor `_parallel` properties on
  258. * regular plugins, and guarantees that callers can safely read `fileUrl` and
  259. * `options` from the returned value.
  260. */
  261. function getParallelPluginInfo(plugin) {
  262. if (plugin === null || typeof plugin !== "object") return;
  263. const descriptor = Object.getOwnPropertyDescriptor(plugin, "_parallel");
  264. if (!descriptor || !("value" in descriptor)) return;
  265. const parallel = descriptor.value;
  266. if (parallel === null || typeof parallel !== "object" || typeof parallel.fileUrl !== "string") return;
  267. return parallel;
  268. }
  269. //#endregion
  270. //#region src/plugin/minimal-plugin-context.ts
  271. var MinimalPluginContextImpl = class {
  272. pluginName;
  273. hookName;
  274. info;
  275. warn;
  276. debug;
  277. meta;
  278. constructor(onLog, logLevel, pluginName, watchMode, hookName) {
  279. this.pluginName = pluginName;
  280. this.hookName = hookName;
  281. this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
  282. this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
  283. this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
  284. this.meta = {
  285. rollupVersion: "4.23.0",
  286. rolldownVersion: VERSION,
  287. watchMode
  288. };
  289. }
  290. error(e) {
  291. return error(logPluginError(normalizeLog(e), this.pluginName, { hook: this.hookName }));
  292. }
  293. };
  294. //#endregion
  295. //#region src/types/plain-object-like.ts
  296. var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
  297. const LAZY_FIELDS_KEY = Symbol("__lazy_fields__");
  298. /**
  299. * Base class for classes that use `@lazyProp` decorated properties.
  300. *
  301. * **Design Pattern in Rolldown:**
  302. * This is a common pattern in Rolldown due to its three-layer architecture:
  303. * TypeScript API → NAPI Bindings → Rust Core
  304. *
  305. * **Why we use getters:**
  306. * For performance - to lazily fetch data from Rust bindings only when needed,
  307. * rather than eagerly fetching all data during object construction.
  308. *
  309. * **The problem:**
  310. * Getters defined on class prototypes are non-enumerable by default, which breaks:
  311. * - Object spread operators ({...obj})
  312. * - Object.keys() and similar methods
  313. * - Standard JavaScript object semantics
  314. *
  315. * **The solution:**
  316. * This base class automatically converts `@lazyProp` decorated getters into
  317. * own enumerable getters on each instance during construction.
  318. *
  319. * **Result:**
  320. * Objects get both lazy-loading performance benefits AND plain JavaScript object behavior.
  321. *
  322. * @example
  323. * ```typescript
  324. * class MyClass extends PlainObjectLike {
  325. * @lazyProp
  326. * get myProp() {
  327. * return fetchFromRustBinding();
  328. * }
  329. * }
  330. * ```
  331. */
  332. var PlainObjectLike = class {
  333. constructor() {
  334. setupLazyProperties(this);
  335. }
  336. };
  337. /**
  338. * Set up lazy properties as own getters on an instance.
  339. * This is called automatically by the `PlainObjectLike` base class constructor.
  340. *
  341. * @param instance - The instance to set up lazy properties on
  342. * @internal
  343. */
  344. function setupLazyProperties(instance) {
  345. const lazyFields = instance.constructor[LAZY_FIELDS_KEY];
  346. if (!lazyFields) return;
  347. for (const [propertyKey, originalGetter] of lazyFields.entries()) {
  348. let cachedValue;
  349. let hasValue = false;
  350. Object.defineProperty(instance, propertyKey, {
  351. get() {
  352. if (!hasValue) {
  353. cachedValue = originalGetter.call(this);
  354. hasValue = true;
  355. }
  356. return cachedValue;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. }
  362. }
  363. /**
  364. * Get all lazy field names from a class instance.
  365. *
  366. * @param instance - Instance to inspect
  367. * @returns Set of lazy property names
  368. */
  369. function getLazyFields(instance) {
  370. const lazyFields = instance.constructor[LAZY_FIELDS_KEY];
  371. return lazyFields ? new Set(lazyFields.keys()) : /* @__PURE__ */ new Set();
  372. }
  373. //#endregion
  374. //#region src/decorators/lazy.ts
  375. /**
  376. * Decorator that marks a getter as lazy-evaluated and cached.
  377. *
  378. * **What "lazy" means here:**
  379. * 1. Data is lazily fetched from Rust bindings only when the property is accessed (not eagerly on construction)
  380. * 2. Once fetched, the data is cached for subsequent accesses (performance optimization)
  381. * 3. Despite being a getter, it behaves like a plain object property (enumerable, appears in Object.keys())
  382. *
  383. * **Important**: Properties decorated with `@lazyProp` are defined as own enumerable
  384. * properties on each instance (not on the prototype). This ensures they:
  385. * - Appear in Object.keys() and Object.getOwnPropertyNames()
  386. * - Are included in object spreads ({...obj})
  387. * - Are enumerable in for...in loops
  388. *
  389. * Classes using this decorator must extend `PlainObjectLike` base class.
  390. *
  391. * @example
  392. * ```typescript
  393. * class MyClass extends PlainObjectLike {
  394. * @lazyProp
  395. * get expensiveValue() {
  396. * return someExpensiveComputation();
  397. * }
  398. * }
  399. * ```
  400. */
  401. function lazyProp(target, propertyKey, descriptor) {
  402. if (!target.constructor[LAZY_FIELDS_KEY]) target.constructor[LAZY_FIELDS_KEY] = /* @__PURE__ */ new Map();
  403. const originalGetter = descriptor.get;
  404. target.constructor[LAZY_FIELDS_KEY].set(propertyKey, originalGetter);
  405. return {
  406. enumerable: false,
  407. configurable: true
  408. };
  409. }
  410. //#endregion
  411. //#region src/utils/asset-source.ts
  412. function transformAssetSource(bindingAssetSource) {
  413. return bindingAssetSource.inner;
  414. }
  415. function bindingAssetSource(source) {
  416. return { inner: source };
  417. }
  418. //#endregion
  419. //#region \0@oxc-project+runtime@0.152.0/helpers/esm/decorate.js
  420. function __decorate(decorators, target, key, desc) {
  421. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  422. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  423. 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;
  424. return c > 3 && r && Object.defineProperty(target, key, r), r;
  425. }
  426. //#endregion
  427. //#region src/types/output-asset-impl.ts
  428. var OutputAssetImpl = class extends PlainObjectLike {
  429. bindingAsset;
  430. type = "asset";
  431. constructor(bindingAsset) {
  432. super();
  433. this.bindingAsset = bindingAsset;
  434. }
  435. get fileName() {
  436. return this.bindingAsset.getFileName();
  437. }
  438. get originalFileName() {
  439. return this.bindingAsset.getOriginalFileName() || null;
  440. }
  441. get originalFileNames() {
  442. return this.bindingAsset.getOriginalFileNames();
  443. }
  444. get name() {
  445. return this.bindingAsset.getName() ?? void 0;
  446. }
  447. get names() {
  448. return this.bindingAsset.getNames();
  449. }
  450. get source() {
  451. return transformAssetSource(this.bindingAsset.getSource());
  452. }
  453. __rolldown_external_memory_handle__(keepDataAlive) {
  454. if (keepDataAlive) this.#evaluateAllLazyFields();
  455. return this.bindingAsset.dropInner();
  456. }
  457. #evaluateAllLazyFields() {
  458. for (const field of getLazyFields(this)) this[field];
  459. }
  460. };
  461. __decorate([lazyProp], OutputAssetImpl.prototype, "fileName", null);
  462. __decorate([lazyProp], OutputAssetImpl.prototype, "originalFileName", null);
  463. __decorate([lazyProp], OutputAssetImpl.prototype, "originalFileNames", null);
  464. __decorate([lazyProp], OutputAssetImpl.prototype, "name", null);
  465. __decorate([lazyProp], OutputAssetImpl.prototype, "names", null);
  466. __decorate([lazyProp], OutputAssetImpl.prototype, "source", null);
  467. //#endregion
  468. //#region src/utils/transform-rendered-module.ts
  469. function transformToRenderedModule(bindingRenderedModule) {
  470. return {
  471. get code() {
  472. return bindingRenderedModule.code;
  473. },
  474. get renderedLength() {
  475. return bindingRenderedModule.code?.length || 0;
  476. },
  477. get renderedExports() {
  478. return bindingRenderedModule.renderedExports;
  479. }
  480. };
  481. }
  482. //#endregion
  483. //#region src/utils/transform-rendered-chunk.ts
  484. function transformRenderedChunk(chunk) {
  485. let modules = null;
  486. return {
  487. type: "chunk",
  488. get name() {
  489. return chunk.name;
  490. },
  491. get isEntry() {
  492. return chunk.isEntry;
  493. },
  494. get isDynamicEntry() {
  495. return chunk.isDynamicEntry;
  496. },
  497. get facadeModuleId() {
  498. return chunk.facadeModuleId;
  499. },
  500. get moduleIds() {
  501. return chunk.moduleIds;
  502. },
  503. get exports() {
  504. return chunk.exports;
  505. },
  506. get fileName() {
  507. return chunk.fileName;
  508. },
  509. get imports() {
  510. return chunk.imports;
  511. },
  512. get dynamicImports() {
  513. return chunk.dynamicImports;
  514. },
  515. get modules() {
  516. if (!modules) modules = transformChunkModules(chunk.modules);
  517. return modules;
  518. }
  519. };
  520. }
  521. function transformChunkModules(modules) {
  522. const result = {};
  523. for (let i = 0; i < modules.values.length; i++) {
  524. let key = modules.keys[i];
  525. const mod = modules.values[i];
  526. result[key] = transformToRenderedModule(mod);
  527. }
  528. return result;
  529. }
  530. //#endregion
  531. //#region src/types/output-chunk-impl.ts
  532. var OutputChunkImpl = class extends PlainObjectLike {
  533. bindingChunk;
  534. type = "chunk";
  535. constructor(bindingChunk) {
  536. super();
  537. this.bindingChunk = bindingChunk;
  538. }
  539. get fileName() {
  540. return this.bindingChunk.getFileName();
  541. }
  542. get name() {
  543. return this.bindingChunk.getName();
  544. }
  545. get exports() {
  546. return this.bindingChunk.getExports();
  547. }
  548. get isEntry() {
  549. return this.bindingChunk.getIsEntry();
  550. }
  551. get facadeModuleId() {
  552. return this.bindingChunk.getFacadeModuleId() || null;
  553. }
  554. get isDynamicEntry() {
  555. return this.bindingChunk.getIsDynamicEntry();
  556. }
  557. get sourcemapFileName() {
  558. return this.bindingChunk.getSourcemapFileName() || null;
  559. }
  560. get preliminaryFileName() {
  561. return this.bindingChunk.getPreliminaryFileName();
  562. }
  563. get code() {
  564. return this.bindingChunk.getCode();
  565. }
  566. get modules() {
  567. return transformChunkModules(this.bindingChunk.getModules());
  568. }
  569. get imports() {
  570. return this.bindingChunk.getImports();
  571. }
  572. get dynamicImports() {
  573. return this.bindingChunk.getDynamicImports();
  574. }
  575. get moduleIds() {
  576. return this.bindingChunk.getModuleIds();
  577. }
  578. get map() {
  579. const mapString = this.bindingChunk.getMap();
  580. return mapString ? transformToRollupSourceMap(mapString) : null;
  581. }
  582. __rolldown_external_memory_handle__(keepDataAlive) {
  583. if (keepDataAlive) this.#evaluateAllLazyFields();
  584. return this.bindingChunk.dropInner();
  585. }
  586. #evaluateAllLazyFields() {
  587. for (const field of getLazyFields(this)) this[field];
  588. }
  589. };
  590. __decorate([lazyProp], OutputChunkImpl.prototype, "fileName", null);
  591. __decorate([lazyProp], OutputChunkImpl.prototype, "name", null);
  592. __decorate([lazyProp], OutputChunkImpl.prototype, "exports", null);
  593. __decorate([lazyProp], OutputChunkImpl.prototype, "isEntry", null);
  594. __decorate([lazyProp], OutputChunkImpl.prototype, "facadeModuleId", null);
  595. __decorate([lazyProp], OutputChunkImpl.prototype, "isDynamicEntry", null);
  596. __decorate([lazyProp], OutputChunkImpl.prototype, "sourcemapFileName", null);
  597. __decorate([lazyProp], OutputChunkImpl.prototype, "preliminaryFileName", null);
  598. __decorate([lazyProp], OutputChunkImpl.prototype, "code", null);
  599. __decorate([lazyProp], OutputChunkImpl.prototype, "modules", null);
  600. __decorate([lazyProp], OutputChunkImpl.prototype, "imports", null);
  601. __decorate([lazyProp], OutputChunkImpl.prototype, "dynamicImports", null);
  602. __decorate([lazyProp], OutputChunkImpl.prototype, "moduleIds", null);
  603. __decorate([lazyProp], OutputChunkImpl.prototype, "map", null);
  604. //#endregion
  605. //#region src/utils/transform-to-rollup-output.ts
  606. function transformToRollupSourceMap(map) {
  607. const obj = {
  608. ...JSON.parse(map),
  609. toString() {
  610. return JSON.stringify(obj);
  611. },
  612. toUrl() {
  613. return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
  614. }
  615. };
  616. Object.defineProperty(obj, "x_google_ignoreList", {
  617. get: () => obj.ignoreList,
  618. set: (value) => {
  619. obj.ignoreList = value;
  620. }
  621. });
  622. return obj;
  623. }
  624. function transformToRollupOutputChunk(bindingChunk) {
  625. return new OutputChunkImpl(bindingChunk);
  626. }
  627. function transformToMutableRollupOutputChunk(bindingChunk, changed) {
  628. const chunk = {
  629. type: "chunk",
  630. get code() {
  631. return bindingChunk.getCode();
  632. },
  633. fileName: bindingChunk.getFileName(),
  634. name: bindingChunk.getName(),
  635. get modules() {
  636. return transformChunkModules(bindingChunk.getModules());
  637. },
  638. get imports() {
  639. return bindingChunk.getImports();
  640. },
  641. get dynamicImports() {
  642. return bindingChunk.getDynamicImports();
  643. },
  644. exports: bindingChunk.getExports(),
  645. isEntry: bindingChunk.getIsEntry(),
  646. facadeModuleId: bindingChunk.getFacadeModuleId() || null,
  647. isDynamicEntry: bindingChunk.getIsDynamicEntry(),
  648. get moduleIds() {
  649. return bindingChunk.getModuleIds();
  650. },
  651. get map() {
  652. const map = bindingChunk.getMap();
  653. return map ? transformToRollupSourceMap(map) : null;
  654. },
  655. sourcemapFileName: bindingChunk.getSourcemapFileName() || null,
  656. preliminaryFileName: bindingChunk.getPreliminaryFileName()
  657. };
  658. const cache = {};
  659. return new Proxy(chunk, {
  660. get(target, p) {
  661. if (p in cache) return cache[p];
  662. const value = target[p];
  663. cache[p] = value;
  664. return value;
  665. },
  666. set(_target, p, newValue) {
  667. cache[p] = newValue;
  668. changed.updated.add(bindingChunk.getFileName());
  669. return true;
  670. },
  671. has(target, p) {
  672. if (p in cache) return true;
  673. return p in target;
  674. }
  675. });
  676. }
  677. function transformToRollupOutputAsset(bindingAsset) {
  678. return new OutputAssetImpl(bindingAsset);
  679. }
  680. function transformToMutableRollupOutputAsset(bindingAsset, changed) {
  681. const asset = {
  682. type: "asset",
  683. fileName: bindingAsset.getFileName(),
  684. originalFileName: bindingAsset.getOriginalFileName() || null,
  685. originalFileNames: bindingAsset.getOriginalFileNames(),
  686. get source() {
  687. return transformAssetSource(bindingAsset.getSource());
  688. },
  689. name: bindingAsset.getName() ?? void 0,
  690. names: bindingAsset.getNames()
  691. };
  692. const cache = {};
  693. return new Proxy(asset, {
  694. get(target, p) {
  695. if (p in cache) return cache[p];
  696. const value = target[p];
  697. cache[p] = value;
  698. return value;
  699. },
  700. set(_target, p, newValue) {
  701. cache[p] = newValue;
  702. changed.updated.add(bindingAsset.getFileName());
  703. return true;
  704. }
  705. });
  706. }
  707. function transformToRollupOutput(output) {
  708. const { chunks, assets } = output;
  709. const transformed = { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk)), ...assets.map((asset) => transformToRollupOutputAsset(asset))] };
  710. if (output.mangleCache !== void 0) transformed.mangleCache = output.mangleCache;
  711. return transformed;
  712. }
  713. function transformToMutableRollupOutput(output, changed) {
  714. const { chunks, assets } = output;
  715. return { output: [...chunks.map((chunk) => transformToMutableRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToMutableRollupOutputAsset(asset, changed))] };
  716. }
  717. function transformToOutputBundle(context, output, changed) {
  718. const bundle = Object.fromEntries(transformToMutableRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
  719. return new Proxy(bundle, {
  720. set(_target, _p, _newValue, _receiver) {
  721. const originalStackTraceLimit = Error.stackTraceLimit;
  722. Error.stackTraceLimit = 2;
  723. 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.";
  724. const stack = (/* @__PURE__ */ new Error(message)).stack ?? message;
  725. Error.stackTraceLimit = originalStackTraceLimit;
  726. context.warn({
  727. message: stack,
  728. code: "UNSUPPORTED_BUNDLE_ASSIGNMENT"
  729. });
  730. return true;
  731. },
  732. deleteProperty(target, property) {
  733. if (typeof property === "string") changed.deleted.add(property);
  734. delete target[property];
  735. return true;
  736. }
  737. });
  738. }
  739. function collectChangedBundle(changed, bundle) {
  740. const changes = {};
  741. for (const key in bundle) {
  742. if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
  743. const item = bundle[key];
  744. if (item.type === "asset") changes[key] = {
  745. filename: item.fileName,
  746. originalFileNames: item.originalFileNames,
  747. source: bindingAssetSource(item.source),
  748. names: item.names
  749. };
  750. else changes[key] = {
  751. code: item.code,
  752. filename: item.fileName,
  753. name: item.name,
  754. isEntry: item.isEntry,
  755. exports: item.exports,
  756. modules: {},
  757. imports: item.imports,
  758. dynamicImports: item.dynamicImports,
  759. facadeModuleId: item.facadeModuleId || void 0,
  760. isDynamicEntry: item.isDynamicEntry,
  761. moduleIds: item.moduleIds,
  762. map: bindingifySourcemap(item.map),
  763. sourcemapFilename: item.sourcemapFileName || void 0,
  764. preliminaryFilename: item.preliminaryFileName
  765. };
  766. }
  767. return {
  768. changes,
  769. deleted: changed.deleted
  770. };
  771. }
  772. //#endregion
  773. //#region src/options/normalized-input-options.ts
  774. var NormalizedInputOptionsImpl = class extends PlainObjectLike {
  775. onLog;
  776. inputPlugins;
  777. inner;
  778. constructor(inner, onLog, inputPlugins) {
  779. super();
  780. this.onLog = onLog;
  781. this.inputPlugins = inputPlugins;
  782. this.inner = inner;
  783. }
  784. get shimMissingExports() {
  785. return this.inner.shimMissingExports;
  786. }
  787. get input() {
  788. return this.inner.input;
  789. }
  790. get cwd() {
  791. return this.inner.cwd;
  792. }
  793. get platform() {
  794. return this.inner.platform;
  795. }
  796. get context() {
  797. return this.inner.context;
  798. }
  799. get plugins() {
  800. return this.inputPlugins;
  801. }
  802. };
  803. __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "shimMissingExports", null);
  804. __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "input", null);
  805. __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "cwd", null);
  806. __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "platform", null);
  807. __decorate([lazyProp], NormalizedInputOptionsImpl.prototype, "context", null);
  808. //#endregion
  809. //#region src/options/normalized-output-options.ts
  810. var NormalizedOutputOptionsImpl = class extends PlainObjectLike {
  811. inner;
  812. outputOptions;
  813. normalizedOutputPlugins;
  814. constructor(inner, outputOptions, normalizedOutputPlugins) {
  815. super();
  816. this.inner = inner;
  817. this.outputOptions = outputOptions;
  818. this.normalizedOutputPlugins = normalizedOutputPlugins;
  819. }
  820. get dir() {
  821. return this.inner.dir ?? void 0;
  822. }
  823. get entryFileNames() {
  824. return this.inner.entryFilenames || this.outputOptions.entryFileNames;
  825. }
  826. get chunkFileNames() {
  827. return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
  828. }
  829. get assetFileNames() {
  830. return this.inner.assetFilenames || this.outputOptions.assetFileNames;
  831. }
  832. get format() {
  833. return this.inner.format;
  834. }
  835. get exports() {
  836. return this.inner.exports;
  837. }
  838. get sourcemap() {
  839. return this.inner.sourcemap;
  840. }
  841. get sourcemapFileNames() {
  842. return this.inner.sourcemapFilenames || this.outputOptions.sourcemapFileNames;
  843. }
  844. get sourcemapBaseUrl() {
  845. return this.inner.sourcemapBaseUrl ?? void 0;
  846. }
  847. get shimMissingExports() {
  848. return this.inner.shimMissingExports;
  849. }
  850. get name() {
  851. return this.inner.name ?? void 0;
  852. }
  853. get file() {
  854. return this.inner.file ?? void 0;
  855. }
  856. get codeSplitting() {
  857. return this.inner.codeSplitting;
  858. }
  859. /**
  860. * @deprecated Use `codeSplitting` instead.
  861. */
  862. get inlineDynamicImports() {
  863. return !this.inner.codeSplitting;
  864. }
  865. get dynamicImportInCjs() {
  866. return this.inner.dynamicImportInCjs;
  867. }
  868. get externalLiveBindings() {
  869. return this.inner.externalLiveBindings;
  870. }
  871. get banner() {
  872. return normalizeAddon(this.outputOptions.banner);
  873. }
  874. get footer() {
  875. return normalizeAddon(this.outputOptions.footer);
  876. }
  877. get postBanner() {
  878. return normalizeAddon(this.outputOptions.postBanner);
  879. }
  880. get postFooter() {
  881. return normalizeAddon(this.outputOptions.postFooter);
  882. }
  883. get intro() {
  884. return normalizeAddon(this.outputOptions.intro);
  885. }
  886. get outro() {
  887. return normalizeAddon(this.outputOptions.outro);
  888. }
  889. get esModule() {
  890. return this.inner.esModule;
  891. }
  892. get extend() {
  893. return this.inner.extend;
  894. }
  895. get globals() {
  896. return this.inner.globals || this.outputOptions.globals;
  897. }
  898. get paths() {
  899. return this.outputOptions.paths;
  900. }
  901. get hashCharacters() {
  902. return this.inner.hashCharacters;
  903. }
  904. get sourcemapDebugIds() {
  905. return this.inner.sourcemapDebugIds;
  906. }
  907. get sourcemapExcludeSources() {
  908. return this.inner.sourcemapExcludeSources;
  909. }
  910. get sourcemapIgnoreList() {
  911. return this.outputOptions.sourcemapIgnoreList;
  912. }
  913. get sourcemapPathTransform() {
  914. return this.outputOptions.sourcemapPathTransform;
  915. }
  916. get minify() {
  917. let ret = this.inner.minify;
  918. if (typeof ret === "object" && ret !== null) {
  919. delete ret["codegen"];
  920. delete ret["module"];
  921. delete ret["sourcemap"];
  922. }
  923. return ret;
  924. }
  925. get legalComments() {
  926. return this.inner.legalComments;
  927. }
  928. get comments() {
  929. const c = this.inner.comments;
  930. return {
  931. legal: c.legal ?? true,
  932. annotation: c.annotation ?? true,
  933. jsdoc: c.jsdoc ?? true
  934. };
  935. }
  936. get polyfillRequire() {
  937. return this.inner.polyfillRequire;
  938. }
  939. get plugins() {
  940. return this.normalizedOutputPlugins;
  941. }
  942. get preserveModules() {
  943. return this.inner.preserveModules;
  944. }
  945. get preserveModulesRoot() {
  946. return this.inner.preserveModulesRoot;
  947. }
  948. get virtualDirname() {
  949. return this.inner.virtualDirname;
  950. }
  951. get topLevelVar() {
  952. return this.inner.topLevelVar ?? false;
  953. }
  954. get minifyInternalExports() {
  955. return this.inner.minifyInternalExports ?? false;
  956. }
  957. };
  958. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "dir", null);
  959. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "entryFileNames", null);
  960. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "chunkFileNames", null);
  961. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "assetFileNames", null);
  962. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "format", null);
  963. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "exports", null);
  964. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemap", null);
  965. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapFileNames", null);
  966. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapBaseUrl", null);
  967. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "shimMissingExports", null);
  968. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "name", null);
  969. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "file", null);
  970. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "codeSplitting", null);
  971. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "inlineDynamicImports", null);
  972. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "dynamicImportInCjs", null);
  973. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "externalLiveBindings", null);
  974. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "banner", null);
  975. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "footer", null);
  976. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "postBanner", null);
  977. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "postFooter", null);
  978. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "intro", null);
  979. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "outro", null);
  980. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "esModule", null);
  981. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "extend", null);
  982. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "globals", null);
  983. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "paths", null);
  984. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "hashCharacters", null);
  985. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapDebugIds", null);
  986. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapExcludeSources", null);
  987. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapIgnoreList", null);
  988. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "sourcemapPathTransform", null);
  989. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "minify", null);
  990. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "legalComments", null);
  991. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "comments", null);
  992. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "polyfillRequire", null);
  993. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "plugins", null);
  994. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "preserveModules", null);
  995. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "preserveModulesRoot", null);
  996. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "virtualDirname", null);
  997. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "topLevelVar", null);
  998. __decorate([lazyProp], NormalizedOutputOptionsImpl.prototype, "minifyInternalExports", null);
  999. function normalizeAddon(value) {
  1000. if (typeof value === "function") return value;
  1001. return () => value || "";
  1002. }
  1003. //#endregion
  1004. //#region src/utils/transform-module-info.ts
  1005. function transformModuleInfo(info, option) {
  1006. return {
  1007. get ast() {
  1008. return unsupported("ModuleInfo#ast");
  1009. },
  1010. get code() {
  1011. return info.code;
  1012. },
  1013. id: info.id,
  1014. importers: info.importers,
  1015. dynamicImporters: info.dynamicImporters,
  1016. importedIds: info.importedIds,
  1017. dynamicallyImportedIds: info.dynamicallyImportedIds,
  1018. exports: info.exports,
  1019. isEntry: info.isEntry,
  1020. inputFormat: info.inputFormat,
  1021. ...option
  1022. };
  1023. }
  1024. //#endregion
  1025. //#region src/plugin/plugin-context-data.ts
  1026. var PluginContextData = class {
  1027. onLog;
  1028. outputOptions;
  1029. normalizedInputPlugins;
  1030. normalizedOutputPlugins;
  1031. moduleOptionMap = /* @__PURE__ */ new Map();
  1032. resolveOptionsMap = /* @__PURE__ */ new Map();
  1033. loadModulePromiseMap = /* @__PURE__ */ new Map();
  1034. renderedChunkMeta = null;
  1035. normalizedInputOptions = null;
  1036. normalizedOutputOptions = null;
  1037. constructor(onLog, outputOptions, normalizedInputPlugins, normalizedOutputPlugins) {
  1038. this.onLog = onLog;
  1039. this.outputOptions = outputOptions;
  1040. this.normalizedInputPlugins = normalizedInputPlugins;
  1041. this.normalizedOutputPlugins = normalizedOutputPlugins;
  1042. }
  1043. updateModuleOption(id, option) {
  1044. const existing = this.moduleOptionMap.get(id);
  1045. if (existing) {
  1046. if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
  1047. if (option.meta != null) Object.assign(existing.meta, option.meta);
  1048. if (option.invalidate != null) existing.invalidate = option.invalidate;
  1049. } else {
  1050. this.moduleOptionMap.set(id, option);
  1051. return option;
  1052. }
  1053. return existing;
  1054. }
  1055. getModuleOption(id) {
  1056. const option = this.moduleOptionMap.get(id);
  1057. if (!option) {
  1058. const raw = {
  1059. moduleSideEffects: null,
  1060. meta: {}
  1061. };
  1062. this.moduleOptionMap.set(id, raw);
  1063. return raw;
  1064. }
  1065. return option;
  1066. }
  1067. getModuleInfo(id, context) {
  1068. const bindingInfo = context.getModuleInfo(id);
  1069. if (bindingInfo) {
  1070. const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
  1071. return this.proxyModuleInfo(id, info);
  1072. }
  1073. return null;
  1074. }
  1075. proxyModuleInfo(id, info) {
  1076. let moduleSideEffects = info.moduleSideEffects;
  1077. Object.defineProperty(info, "moduleSideEffects", {
  1078. get() {
  1079. return moduleSideEffects;
  1080. },
  1081. set: (v) => {
  1082. this.updateModuleOption(id, {
  1083. moduleSideEffects: v,
  1084. meta: info.meta,
  1085. invalidate: true
  1086. });
  1087. moduleSideEffects = v;
  1088. }
  1089. });
  1090. return info;
  1091. }
  1092. getModuleIds(context) {
  1093. return context.getModuleIds().values();
  1094. }
  1095. saveResolveOptions(options) {
  1096. const index = this.resolveOptionsMap.size;
  1097. this.resolveOptionsMap.set(index, options);
  1098. return index;
  1099. }
  1100. getSavedResolveOptions(receipt) {
  1101. return this.resolveOptionsMap.get(receipt);
  1102. }
  1103. removeSavedResolveOptions(receipt) {
  1104. this.resolveOptionsMap.delete(receipt);
  1105. }
  1106. setRenderChunkMeta(meta) {
  1107. this.renderedChunkMeta = meta;
  1108. }
  1109. getRenderChunkMeta() {
  1110. return this.renderedChunkMeta;
  1111. }
  1112. getInputOptions(opts) {
  1113. this.normalizedInputOptions ??= new NormalizedInputOptionsImpl(opts, this.onLog, this.normalizedInputPlugins);
  1114. return this.normalizedInputOptions;
  1115. }
  1116. getOutputOptions(opts) {
  1117. this.normalizedOutputOptions ??= new NormalizedOutputOptionsImpl(opts, this.outputOptions, this.normalizedOutputPlugins);
  1118. return this.normalizedOutputOptions;
  1119. }
  1120. clear() {
  1121. this.renderedChunkMeta = null;
  1122. this.loadModulePromiseMap.clear();
  1123. }
  1124. };
  1125. //#endregion
  1126. //#region src/binding-magic-string.ts
  1127. Object.defineProperty(import_binding.BindingMagicString.prototype, "isRolldownMagicString", {
  1128. value: true,
  1129. writable: false,
  1130. configurable: false
  1131. });
  1132. function assertString(content, msg) {
  1133. if (typeof content !== "string") throw new TypeError(msg);
  1134. }
  1135. const nativeAppend = import_binding.BindingMagicString.prototype.append;
  1136. const nativePrepend = import_binding.BindingMagicString.prototype.prepend;
  1137. const nativeAppendLeft = import_binding.BindingMagicString.prototype.appendLeft;
  1138. const nativeAppendRight = import_binding.BindingMagicString.prototype.appendRight;
  1139. const nativePrependLeft = import_binding.BindingMagicString.prototype.prependLeft;
  1140. const nativePrependRight = import_binding.BindingMagicString.prototype.prependRight;
  1141. const nativeOverwrite = import_binding.BindingMagicString.prototype.overwrite;
  1142. const nativeUpdate = import_binding.BindingMagicString.prototype.update;
  1143. import_binding.BindingMagicString.prototype.append = function(content) {
  1144. assertString(content, "outro content must be a string");
  1145. return nativeAppend.call(this, content);
  1146. };
  1147. import_binding.BindingMagicString.prototype.prepend = function(content) {
  1148. assertString(content, "outro content must be a string");
  1149. return nativePrepend.call(this, content);
  1150. };
  1151. import_binding.BindingMagicString.prototype.appendLeft = function(index, content) {
  1152. assertString(content, "inserted content must be a string");
  1153. return nativeAppendLeft.call(this, index, content);
  1154. };
  1155. import_binding.BindingMagicString.prototype.appendRight = function(index, content) {
  1156. assertString(content, "inserted content must be a string");
  1157. return nativeAppendRight.call(this, index, content);
  1158. };
  1159. import_binding.BindingMagicString.prototype.prependLeft = function(index, content) {
  1160. assertString(content, "inserted content must be a string");
  1161. return nativePrependLeft.call(this, index, content);
  1162. };
  1163. import_binding.BindingMagicString.prototype.prependRight = function(index, content) {
  1164. assertString(content, "inserted content must be a string");
  1165. return nativePrependRight.call(this, index, content);
  1166. };
  1167. import_binding.BindingMagicString.prototype.overwrite = function(start, end, content, options) {
  1168. assertString(content, "replacement content must be a string");
  1169. return nativeOverwrite.call(this, start, end, content, options);
  1170. };
  1171. import_binding.BindingMagicString.prototype.update = function(start, end, content, options) {
  1172. assertString(content, "replacement content must be a string");
  1173. return nativeUpdate.call(this, start, end, content, options);
  1174. };
  1175. const nativeReplace = import_binding.BindingMagicString.prototype.replace;
  1176. const nativeReplaceAll = import_binding.BindingMagicString.prototype.replaceAll;
  1177. import_binding.BindingMagicString.prototype.replace = function(searchValue, replacement) {
  1178. if (typeof searchValue === "string") return nativeReplace.call(this, searchValue, replacement);
  1179. if (searchValue.global) searchValue.lastIndex = 0;
  1180. const lastMatchEnd = this.replaceRegex(searchValue, replacement);
  1181. if (searchValue.global) searchValue.lastIndex = 0;
  1182. else if (searchValue.sticky) searchValue.lastIndex = lastMatchEnd === -1 ? 0 : lastMatchEnd;
  1183. return this;
  1184. };
  1185. import_binding.BindingMagicString.prototype.replaceAll = function(searchValue, replacement) {
  1186. if (typeof searchValue === "string") return nativeReplaceAll.call(this, searchValue, replacement);
  1187. if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
  1188. searchValue.lastIndex = 0;
  1189. this.replaceRegex(searchValue, replacement);
  1190. searchValue.lastIndex = 0;
  1191. return this;
  1192. };
  1193. /**
  1194. * A native MagicString implementation powered by Rust.
  1195. *
  1196. * @experimental
  1197. */
  1198. const RolldownMagicString = import_binding.BindingMagicString;
  1199. //#endregion
  1200. //#region src/utils/transform-sourcemap.ts
  1201. function isEmptySourcemapFiled(array) {
  1202. if (!array) return true;
  1203. if (array.length === 0 || !array[0]) return true;
  1204. return false;
  1205. }
  1206. function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
  1207. if (!rawMap) return;
  1208. let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
  1209. if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
  1210. if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
  1211. return map;
  1212. }
  1213. //#endregion
  1214. //#region ../../node_modules/.pnpm/remeda@2.50.0/node_modules/remeda/dist/lazyDataLastImpl--3B10z3s.js
  1215. function e(e, t, n) {
  1216. let r = (n) => e(n, ...t);
  1217. return n === void 0 ? r : Object.assign(r, {
  1218. lazy: n,
  1219. lazyArgs: t
  1220. });
  1221. }
  1222. //#endregion
  1223. //#region ../../node_modules/.pnpm/remeda@2.50.0/node_modules/remeda/dist/purry.js
  1224. function t$1(t, n, r) {
  1225. let i = t.length - n.length;
  1226. if (i === 0) return t(...n);
  1227. if (i === 1) return e(t, n, r);
  1228. throw Error(`Wrong number of arguments`);
  1229. }
  1230. //#endregion
  1231. //#region ../../node_modules/.pnpm/remeda@2.50.0/node_modules/remeda/dist/partition.js
  1232. function t(...t) {
  1233. return t$1(n, t);
  1234. }
  1235. const n = (e, t) => {
  1236. let n = [[], []];
  1237. for (let [r, i] of e.entries()) t(i, r, e) ? n[0].push(i) : n[1].push(i);
  1238. return n;
  1239. };
  1240. //#endregion
  1241. //#region src/plugin/bindingify-hook-filter.ts
  1242. function generalHookFilterMatcherToFilterExprs(matcher, stringKind) {
  1243. if (typeof matcher === "string" || matcher instanceof RegExp) return [filter.include(generateAtomMatcher(stringKind, matcher))];
  1244. if (Array.isArray(matcher)) return matcher.map((m) => filter.include(generateAtomMatcher(stringKind, m)));
  1245. let ret = [];
  1246. if (matcher.exclude) ret.push(...arraify(matcher.exclude).map((m) => filter.exclude(generateAtomMatcher(stringKind, m))));
  1247. if (matcher.include) ret.push(...arraify(matcher.include).map((m) => filter.include(generateAtomMatcher(stringKind, m))));
  1248. return ret;
  1249. }
  1250. function generateAtomMatcher(kind, matcher) {
  1251. return kind === "code" ? filter.code(matcher) : filter.id(matcher);
  1252. }
  1253. function transformFilterMatcherToFilterExprs(filterOption) {
  1254. if (!filterOption) return;
  1255. if (Array.isArray(filterOption)) return filterOption;
  1256. const { id, code, moduleType } = filterOption;
  1257. let ret = [];
  1258. let idIncludes = [];
  1259. let idExcludes = [];
  1260. let codeIncludes = [];
  1261. let codeExcludes = [];
  1262. if (id) [idIncludes, idExcludes] = t(generalHookFilterMatcherToFilterExprs(id, "id") ?? [], (m) => m.kind === "include");
  1263. if (code) [codeIncludes, codeExcludes] = t(generalHookFilterMatcherToFilterExprs(code, "code") ?? [], (m) => m.kind === "include");
  1264. ret.push(...idExcludes);
  1265. ret.push(...codeExcludes);
  1266. let andExprList = [];
  1267. if (moduleType) {
  1268. let moduleTypes = Array.isArray(moduleType) ? moduleType : moduleType.include ?? [];
  1269. andExprList.push(filter.or(...moduleTypes.map((m) => filter.moduleType(m))));
  1270. }
  1271. if (idIncludes.length) andExprList.push(filter.or(...idIncludes.map((item) => item.expr)));
  1272. if (codeIncludes.length) andExprList.push(filter.or(...codeIncludes.map((item) => item.expr)));
  1273. if (andExprList.length) ret.push(filter.include(filter.and(...andExprList)));
  1274. return ret;
  1275. }
  1276. function bindingifyGeneralHookFilter(stringKind, pattern) {
  1277. let filterExprs = generalHookFilterMatcherToFilterExprs(pattern, stringKind);
  1278. let ret = [];
  1279. if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
  1280. return ret.length > 0 ? { value: ret } : void 0;
  1281. }
  1282. function bindingifyFilterExpr(expr) {
  1283. let list = [];
  1284. bindingifyFilterExprImpl(expr, list);
  1285. return list;
  1286. }
  1287. function containsImporterId(expr) {
  1288. switch (expr.kind) {
  1289. case "and":
  1290. case "or": return expr.args.some(containsImporterId);
  1291. case "not":
  1292. case "include":
  1293. case "exclude": return containsImporterId(expr.expr);
  1294. case "importerId": return true;
  1295. default: return false;
  1296. }
  1297. }
  1298. function assertNoImporterId(filterExprs, hookName) {
  1299. 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.`);
  1300. }
  1301. function containsStringId(expr) {
  1302. switch (expr.kind) {
  1303. case "and":
  1304. case "or": return expr.args.some(containsStringId);
  1305. case "not":
  1306. case "include":
  1307. case "exclude": return containsStringId(expr.expr);
  1308. case "id": return typeof expr.pattern === "string";
  1309. default: return false;
  1310. }
  1311. }
  1312. function assertNoStringId(filterExprs, hookName) {
  1313. 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.`);
  1314. }
  1315. function bindingifyFilterExprImpl(expr, list) {
  1316. switch (expr.kind) {
  1317. case "and": {
  1318. let args = expr.args;
  1319. for (let i = args.length - 1; i >= 0; i--) bindingifyFilterExprImpl(args[i], list);
  1320. list.push({
  1321. kind: "And",
  1322. payload: args.length
  1323. });
  1324. break;
  1325. }
  1326. case "or": {
  1327. let args = expr.args;
  1328. for (let i = args.length - 1; i >= 0; i--) bindingifyFilterExprImpl(args[i], list);
  1329. list.push({
  1330. kind: "Or",
  1331. payload: args.length
  1332. });
  1333. break;
  1334. }
  1335. case "not":
  1336. bindingifyFilterExprImpl(expr.expr, list);
  1337. list.push({ kind: "Not" });
  1338. break;
  1339. case "id":
  1340. list.push({
  1341. kind: "Id",
  1342. payload: expr.pattern
  1343. });
  1344. if (expr.params.cleanUrl) list.push({ kind: "CleanUrl" });
  1345. break;
  1346. case "importerId":
  1347. list.push({
  1348. kind: "ImporterId",
  1349. payload: expr.pattern
  1350. });
  1351. if (expr.params.cleanUrl) list.push({ kind: "CleanUrl" });
  1352. break;
  1353. case "moduleType":
  1354. list.push({
  1355. kind: "ModuleType",
  1356. payload: expr.pattern
  1357. });
  1358. break;
  1359. case "code":
  1360. list.push({
  1361. kind: "Code",
  1362. payload: expr.pattern
  1363. });
  1364. break;
  1365. case "include":
  1366. bindingifyFilterExprImpl(expr.expr, list);
  1367. list.push({ kind: "Include" });
  1368. break;
  1369. case "exclude":
  1370. bindingifyFilterExprImpl(expr.expr, list);
  1371. list.push({ kind: "Exclude" });
  1372. break;
  1373. case "query":
  1374. list.push({
  1375. kind: "QueryKey",
  1376. payload: expr.key
  1377. });
  1378. list.push({
  1379. kind: "QueryValue",
  1380. payload: expr.pattern
  1381. });
  1382. break;
  1383. default: throw new Error(`Unknown filter expression: ${expr}`);
  1384. }
  1385. }
  1386. function bindingifyResolveIdFilter(filterOption) {
  1387. if (!filterOption) return;
  1388. const filterExprs = Array.isArray(filterOption) ? filterOption : filterOption.id ? generalHookFilterMatcherToFilterExprs(filterOption.id, "id") : void 0;
  1389. assertNoStringId(filterExprs, "resolveId");
  1390. if (!filterExprs) return;
  1391. const value = filterExprs.map(bindingifyFilterExpr);
  1392. return value.length > 0 ? { value } : void 0;
  1393. }
  1394. function bindingifyLoadFilter(filterOption) {
  1395. if (!filterOption) return;
  1396. if (Array.isArray(filterOption)) {
  1397. assertNoImporterId(filterOption, "load");
  1398. return { value: filterOption.map(bindingifyFilterExpr) };
  1399. }
  1400. return filterOption.id ? bindingifyGeneralHookFilter("id", filterOption.id) : void 0;
  1401. }
  1402. function bindingifyTransformFilter(filterOption) {
  1403. if (!filterOption) return;
  1404. let filterExprs = transformFilterMatcherToFilterExprs(filterOption);
  1405. assertNoImporterId(filterExprs, "transform");
  1406. let ret = [];
  1407. if (filterExprs) ret = filterExprs.map(bindingifyFilterExpr);
  1408. return { value: ret.length > 0 ? ret : void 0 };
  1409. }
  1410. function bindingifyRenderChunkFilter(filterOption) {
  1411. if (!filterOption) return;
  1412. if (Array.isArray(filterOption)) {
  1413. assertNoImporterId(filterOption, "renderChunk");
  1414. return { value: filterOption.map(bindingifyFilterExpr) };
  1415. }
  1416. return filterOption.code ? bindingifyGeneralHookFilter("code", filterOption.code) : void 0;
  1417. }
  1418. //#endregion
  1419. //#region src/plugin/bindingify-plugin-hook-meta.ts
  1420. function bindingifyPluginHookMeta(options) {
  1421. return { order: bindingPluginOrder(options.order) };
  1422. }
  1423. function bindingPluginOrder(order) {
  1424. switch (order) {
  1425. case "post": return import_binding.BindingPluginOrder.Post;
  1426. case "pre": return import_binding.BindingPluginOrder.Pre;
  1427. case null:
  1428. case void 0: return;
  1429. default: throw new Error(`Unknown plugin order: ${order}`);
  1430. }
  1431. }
  1432. function bindingifyHook(hook, build) {
  1433. if (!hook) return {};
  1434. const normalized = normalizeHook(hook);
  1435. return {
  1436. ...build(normalized),
  1437. meta: bindingifyPluginHookMeta(normalized.meta)
  1438. };
  1439. }
  1440. //#endregion
  1441. //#region src/plugin/fs.ts
  1442. const fsModule = {
  1443. appendFile: fsp.appendFile,
  1444. copyFile: fsp.copyFile,
  1445. mkdir: fsp.mkdir,
  1446. mkdtemp: fsp.mkdtemp,
  1447. readdir: fsp.readdir,
  1448. readFile: fsp.readFile,
  1449. realpath: fsp.realpath,
  1450. rename: fsp.rename,
  1451. rmdir: fsp.rmdir,
  1452. stat: fsp.stat,
  1453. lstat: fsp.lstat,
  1454. unlink: fsp.unlink,
  1455. writeFile: fsp.writeFile
  1456. };
  1457. //#endregion
  1458. //#region src/plugin/plugin-context.ts
  1459. var PluginContextImpl = class extends MinimalPluginContextImpl {
  1460. outputOptions;
  1461. context;
  1462. data;
  1463. onLog;
  1464. currentLoadingModule;
  1465. fs = fsModule;
  1466. getModuleInfo;
  1467. constructor(outputOptions, context, plugin, data, onLog, logLevel, watchMode, currentLoadingModule) {
  1468. super(onLog, logLevel, plugin.name, watchMode);
  1469. this.outputOptions = outputOptions;
  1470. this.context = context;
  1471. this.data = data;
  1472. this.onLog = onLog;
  1473. this.currentLoadingModule = currentLoadingModule;
  1474. this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
  1475. }
  1476. async load(options) {
  1477. const id = options.id;
  1478. if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
  1479. const moduleInfo = this.data.getModuleInfo(id, this.context);
  1480. if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
  1481. const rawOptions = {
  1482. meta: options.meta || {},
  1483. moduleSideEffects: options.moduleSideEffects || null,
  1484. invalidate: false
  1485. };
  1486. this.data.updateModuleOption(id, rawOptions);
  1487. let loadPromise = this.data.loadModulePromiseMap.get(id);
  1488. if (!loadPromise) {
  1489. loadPromise = this.context.load(id, options.moduleSideEffects ?? void 0, options.packageJsonPath ?? void 0).catch(() => {
  1490. this.data.loadModulePromiseMap.delete(id);
  1491. });
  1492. this.data.loadModulePromiseMap.set(id, loadPromise);
  1493. }
  1494. await loadPromise;
  1495. return this.data.getModuleInfo(id, this.context);
  1496. }
  1497. async resolve(source, importer, options) {
  1498. let receipt = void 0;
  1499. if (options != null) receipt = this.data.saveResolveOptions(options);
  1500. const vitePluginCustom = Object.entries(options?.custom ?? {}).reduce((acc, [key, value]) => {
  1501. if (key.startsWith("vite:")) (acc ??= {})[key] = value;
  1502. return acc;
  1503. }, void 0);
  1504. const res = await this.context.resolve(source, importer, {
  1505. importKind: options?.kind,
  1506. custom: receipt,
  1507. isEntry: options?.isEntry,
  1508. skipSelf: options?.skipSelf,
  1509. vitePluginCustom
  1510. });
  1511. if (receipt != null) this.data.removeSavedResolveOptions(receipt);
  1512. if (res == null) return null;
  1513. const info = this.data.getModuleOption(res.id) || {};
  1514. return {
  1515. ...res,
  1516. external: res.external === "relative" ? unreachable(`The PluginContext resolve result external couldn't be 'relative'`) : res.external,
  1517. ...info,
  1518. moduleSideEffects: info.moduleSideEffects ?? res.moduleSideEffects ?? null,
  1519. packageJsonPath: res.packageJsonPath
  1520. };
  1521. }
  1522. emitFile = (file) => {
  1523. if (file.type === "prebuilt-chunk") {
  1524. if (typeof file.code !== "string") return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${file.code}".`));
  1525. 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}".`));
  1526. return this.context.emitPrebuiltChunk({
  1527. fileName: file.fileName,
  1528. name: file.name,
  1529. code: file.code,
  1530. exports: file.exports,
  1531. map: bindingifySourcemap(file.map),
  1532. sourcemapFileName: file.sourcemapFileName,
  1533. facadeModuleId: file.facadeModuleId,
  1534. isEntry: file.isEntry,
  1535. isDynamicEntry: file.isDynamicEntry
  1536. });
  1537. }
  1538. const validatedName = file.fileName || file.name;
  1539. 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}".`));
  1540. if (file.type === "chunk") return this.context.emitChunk({
  1541. preserveEntrySignatures: bindingifyPreserveEntrySignatures(file.preserveSignature),
  1542. ...file
  1543. });
  1544. const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
  1545. const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
  1546. return this.context.emitFile({
  1547. ...file,
  1548. originalFileName: file.originalFileName || void 0,
  1549. source: bindingAssetSource(file.source)
  1550. }, filename, fnSanitizedFileName);
  1551. };
  1552. getAssetFileNames(file) {
  1553. if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
  1554. type: "asset",
  1555. name: file.name,
  1556. names: file.name ? [file.name] : [],
  1557. originalFileName: file.originalFileName,
  1558. originalFileNames: file.originalFileName ? [file.originalFileName] : [],
  1559. source: file.source
  1560. });
  1561. }
  1562. getFileName(referenceId) {
  1563. return this.context.getFileName(referenceId);
  1564. }
  1565. getModuleIds() {
  1566. return this.data.getModuleIds(this.context);
  1567. }
  1568. addWatchFile(id) {
  1569. this.context.addWatchFile(id);
  1570. }
  1571. parse(input, options) {
  1572. return parseAst(input, options);
  1573. }
  1574. };
  1575. function createPluginContext(args, ctx) {
  1576. return new PluginContextImpl(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, args.watchMode);
  1577. }
  1578. //#endregion
  1579. //#region src/plugin/load-plugin-context.ts
  1580. var LoadPluginContextImpl = class extends PluginContextImpl {
  1581. inner;
  1582. constructor(outputOptions, context, plugin, data, inner, moduleId, onLog, logLevelOption, watchMode) {
  1583. super(outputOptions, context, plugin, data, onLog, logLevelOption, watchMode, moduleId);
  1584. this.inner = inner;
  1585. }
  1586. addWatchFile(id) {
  1587. this.inner.addWatchFile(id);
  1588. }
  1589. };
  1590. //#endregion
  1591. //#region src/plugin/transform-plugin-context.ts
  1592. var TransformPluginContextImpl = class extends PluginContextImpl {
  1593. inner;
  1594. moduleId;
  1595. moduleSource;
  1596. constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption, watchMode) {
  1597. super(outputOptions, context, plugin, data, onLog, LogLevelOption, watchMode, moduleId);
  1598. this.inner = inner;
  1599. this.moduleId = moduleId;
  1600. this.moduleSource = moduleSource;
  1601. const getLogHandler = (handler) => (log, pos) => {
  1602. log = normalizeLog(log);
  1603. if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
  1604. log.id = moduleId;
  1605. log.hook = "transform";
  1606. handler(log);
  1607. };
  1608. this.debug = getLogHandler(this.debug);
  1609. this.warn = getLogHandler(this.warn);
  1610. this.info = getLogHandler(this.info);
  1611. }
  1612. error(e, pos) {
  1613. if (typeof e === "string") e = { message: e };
  1614. if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
  1615. e.id = this.moduleId;
  1616. e.hook = "transform";
  1617. return error(logPluginError(normalizeLog(e), this.pluginName));
  1618. }
  1619. getCombinedSourcemap() {
  1620. return JSON.parse(this.inner.getCombinedSourcemap());
  1621. }
  1622. addWatchFile(id) {
  1623. this.inner.addWatchFile(id);
  1624. }
  1625. sendMagicString(s) {
  1626. this.inner.sendMagicString(s);
  1627. }
  1628. };
  1629. //#endregion
  1630. //#region src/plugin/bindingify-build-hooks.ts
  1631. function bindingifyBuildStart(args) {
  1632. return bindingifyHook(args.plugin.buildStart, ({ handler }) => ({ plugin: async (ctx, opts) => {
  1633. await handler.call(createPluginContext(args, ctx), args.pluginContextData.getInputOptions(opts));
  1634. } }));
  1635. }
  1636. function bindingifyBuildEnd(args) {
  1637. return bindingifyHook(args.plugin.buildEnd, ({ handler }) => ({ plugin: async (ctx, err) => {
  1638. await handler.call(createPluginContext(args, ctx), err ? aggregateBindingErrorsIntoJsError(err) : void 0);
  1639. } }));
  1640. }
  1641. function bindingifyResolveId(args) {
  1642. const hook = args.plugin.resolveId;
  1643. return bindingifyHook(hook, ({ handler, options }) => ({
  1644. plugin: async (ctx, specifier, importer, extraOptions) => {
  1645. const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
  1646. const ret = await handler.call(createPluginContext(args, ctx), specifier, importer ?? void 0, {
  1647. ...extraOptions,
  1648. custom: contextResolveOptions?.custom
  1649. });
  1650. if (ret == null) return;
  1651. if (ret === false) return {
  1652. id: specifier,
  1653. external: true,
  1654. normalizeExternalId: true
  1655. };
  1656. if (typeof ret === "string") return {
  1657. id: ret,
  1658. normalizeExternalId: false
  1659. };
  1660. let exist = args.pluginContextData.updateModuleOption(ret.id, {
  1661. meta: ret.meta || {},
  1662. moduleSideEffects: ret.moduleSideEffects ?? null,
  1663. invalidate: false
  1664. });
  1665. return {
  1666. id: ret.id,
  1667. external: ret.external,
  1668. normalizeExternalId: false,
  1669. moduleSideEffects: exist.moduleSideEffects ?? void 0,
  1670. packageJsonPath: ret.packageJsonPath
  1671. };
  1672. },
  1673. filter: bindingifyResolveIdFilter(options.filter)
  1674. }));
  1675. }
  1676. function bindingifyResolveDynamicImport(args) {
  1677. return bindingifyHook(args.plugin.resolveDynamicImport, ({ handler }) => ({ plugin: async (ctx, specifier, importer) => {
  1678. const ret = await handler.call(createPluginContext(args, ctx), specifier, importer ?? void 0);
  1679. if (ret == null) return;
  1680. if (ret === false) return {
  1681. id: specifier,
  1682. external: true
  1683. };
  1684. if (typeof ret === "string") return { id: ret };
  1685. const result = {
  1686. id: ret.id,
  1687. external: ret.external,
  1688. packageJsonPath: ret.packageJsonPath
  1689. };
  1690. if (ret.moduleSideEffects !== null) result.moduleSideEffects = ret.moduleSideEffects;
  1691. args.pluginContextData.updateModuleOption(ret.id, {
  1692. meta: ret.meta || {},
  1693. moduleSideEffects: ret.moduleSideEffects || null,
  1694. invalidate: false
  1695. });
  1696. return result;
  1697. } }));
  1698. }
  1699. function bindingifyTransform(args) {
  1700. return bindingifyHook(args.plugin.transform, ({ handler, options }) => ({
  1701. plugin: async (ctx, code, id, meta) => {
  1702. let magicStringInstance, astInstance;
  1703. Object.defineProperties(meta, {
  1704. magicString: { get() {
  1705. if (magicStringInstance) return magicStringInstance;
  1706. magicStringInstance = new RolldownMagicString(code);
  1707. return magicStringInstance;
  1708. } },
  1709. ast: { get() {
  1710. if (astInstance) return astInstance;
  1711. let lang = "js";
  1712. switch (meta.moduleType) {
  1713. case "js":
  1714. case "jsx":
  1715. case "ts":
  1716. case "tsx": lang = meta.moduleType;
  1717. }
  1718. astInstance = parseAst(code, {
  1719. astType: meta.moduleType.includes("ts") ? "ts" : "js",
  1720. lang
  1721. });
  1722. return astInstance;
  1723. } }
  1724. });
  1725. const transformCtx = new TransformPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel, args.watchMode);
  1726. const ret = await handler.call(transformCtx, code, id, meta);
  1727. if (ret == null) return;
  1728. if (typeof ret === "string") return { code: ret };
  1729. let moduleOption = args.pluginContextData.updateModuleOption(id, {
  1730. meta: ret.meta ?? {},
  1731. moduleSideEffects: ret.moduleSideEffects ?? null,
  1732. invalidate: false
  1733. });
  1734. let normalizedCode = void 0;
  1735. let map = ret.map;
  1736. let mapHandledByNativeChannel = false;
  1737. if (typeof ret.code === "string") normalizedCode = ret.code;
  1738. else if (ret.code instanceof RolldownMagicString) {
  1739. let magicString = ret.code;
  1740. normalizedCode = magicString.toString();
  1741. let fallbackSourcemap = ctx.sendMagicString(magicString);
  1742. if (fallbackSourcemap != void 0) map = fallbackSourcemap;
  1743. else mapHandledByNativeChannel = true;
  1744. }
  1745. return {
  1746. code: normalizedCode,
  1747. map: bindingifySourcemap(normalizeTransformHookSourcemap(id, code, map)) ?? (mapHandledByNativeChannel || ret.map === null ? null : void 0),
  1748. moduleSideEffects: moduleOption.moduleSideEffects ?? void 0,
  1749. moduleType: ret.moduleType
  1750. };
  1751. },
  1752. filter: bindingifyTransformFilter(options.filter)
  1753. }));
  1754. }
  1755. function bindingifyLoad(args) {
  1756. return bindingifyHook(args.plugin.load, ({ handler, options }) => ({
  1757. plugin: async (ctx, id) => {
  1758. const ret = await handler.call(new LoadPluginContextImpl(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, args.onLog, args.logLevel, args.watchMode), id);
  1759. if (ret == null) return;
  1760. if (typeof ret === "string") return { code: ret };
  1761. let moduleOption = args.pluginContextData.updateModuleOption(id, {
  1762. meta: ret.meta || {},
  1763. moduleSideEffects: ret.moduleSideEffects ?? null,
  1764. invalidate: false
  1765. });
  1766. let map = preProcessSourceMap(ret, id);
  1767. return {
  1768. code: ret.code,
  1769. map: bindingifySourcemap(map),
  1770. moduleType: ret.moduleType,
  1771. moduleSideEffects: moduleOption.moduleSideEffects ?? void 0
  1772. };
  1773. },
  1774. filter: bindingifyLoadFilter(options.filter)
  1775. }));
  1776. }
  1777. function preProcessSourceMap(ret, id) {
  1778. if (!ret.map) return;
  1779. let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
  1780. if (!isEmptySourcemapFiled(map.sources)) {
  1781. const directory = path.dirname(id) || ".";
  1782. const sourceRoot = map.sourceRoot || ".";
  1783. map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
  1784. }
  1785. return map;
  1786. }
  1787. function bindingifyModuleParsed(args) {
  1788. return bindingifyHook(args.plugin.moduleParsed, ({ handler }) => ({ plugin: async (ctx, moduleInfo) => {
  1789. await handler.call(createPluginContext(args, ctx), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
  1790. } }));
  1791. }
  1792. //#endregion
  1793. //#region src/plugin/bindingify-output-hooks.ts
  1794. function bindingifyRenderStart(args) {
  1795. return bindingifyHook(args.plugin.renderStart, ({ handler }) => ({ plugin: async (ctx, opts) => {
  1796. await handler.call(createPluginContext(args, ctx), args.pluginContextData.getOutputOptions(opts), args.pluginContextData.getInputOptions(opts));
  1797. } }));
  1798. }
  1799. function bindingifyRenderChunk(args) {
  1800. return bindingifyHook(args.plugin.renderChunk, ({ handler, options }) => ({
  1801. plugin: async (ctx, code, chunk, opts, meta) => {
  1802. if (args.pluginContextData.getRenderChunkMeta() == null) args.pluginContextData.setRenderChunkMeta({ chunks: Object.fromEntries(Object.entries(meta.chunks).map(([key, value]) => [key, transformRenderedChunk(value)])) });
  1803. const renderChunkMeta = args.pluginContextData.getRenderChunkMeta();
  1804. let magicStringInstance;
  1805. if (args.options.experimental?.nativeMagicString) Object.defineProperty(renderChunkMeta, "magicString", {
  1806. get() {
  1807. if (magicStringInstance) return magicStringInstance;
  1808. magicStringInstance = new RolldownMagicString(code);
  1809. return magicStringInstance;
  1810. },
  1811. configurable: true
  1812. });
  1813. const ret = await handler.call(createPluginContext(args, ctx), code, transformRenderedChunk(chunk), args.pluginContextData.getOutputOptions(opts), renderChunkMeta);
  1814. if (ret == null) return;
  1815. if (ret instanceof RolldownMagicString) {
  1816. const normalizedCode = ret.toString();
  1817. const generatedMap = ret.generateMap();
  1818. return {
  1819. code: normalizedCode,
  1820. map: bindingifySourcemap({
  1821. file: generatedMap.file,
  1822. mappings: generatedMap.mappings,
  1823. names: generatedMap.names,
  1824. sources: generatedMap.sources,
  1825. sourcesContent: generatedMap.sourcesContent.map((s) => s ?? null)
  1826. })
  1827. };
  1828. }
  1829. if (typeof ret === "string") return { code: ret };
  1830. if (ret.code instanceof RolldownMagicString) {
  1831. const magicString = ret.code;
  1832. const normalizedCode = magicString.toString();
  1833. if (ret.map === null) return {
  1834. code: normalizedCode,
  1835. map: null
  1836. };
  1837. if (ret.map === void 0) {
  1838. const generatedMap = magicString.generateMap();
  1839. return {
  1840. code: normalizedCode,
  1841. map: bindingifySourcemap({
  1842. file: generatedMap.file,
  1843. mappings: generatedMap.mappings,
  1844. names: generatedMap.names,
  1845. sources: generatedMap.sources,
  1846. sourcesContent: generatedMap.sourcesContent.map((s) => s ?? null)
  1847. })
  1848. };
  1849. }
  1850. return {
  1851. code: normalizedCode,
  1852. map: bindingifySourcemap(ret.map)
  1853. };
  1854. }
  1855. if (ret.map === null) return {
  1856. code: ret.code,
  1857. map: null
  1858. };
  1859. return {
  1860. code: ret.code,
  1861. map: bindingifySourcemap(ret.map)
  1862. };
  1863. },
  1864. filter: bindingifyRenderChunkFilter(options.filter)
  1865. }));
  1866. }
  1867. function bindingifyAugmentChunkHash(args) {
  1868. return bindingifyHook(args.plugin.augmentChunkHash, ({ handler }) => ({ plugin: async (ctx, chunk) => {
  1869. return handler.call(createPluginContext(args, ctx), transformRenderedChunk(chunk));
  1870. } }));
  1871. }
  1872. function bindingifyResolveFileUrl(args) {
  1873. return bindingifyHook(args.plugin.resolveFileUrl, ({ handler }) => ({ plugin: async (ctx, resolveFileUrlArgs) => {
  1874. return handler.call(createPluginContext(args, ctx), resolveFileUrlArgs);
  1875. } }));
  1876. }
  1877. function bindingifyRenderError(args) {
  1878. return bindingifyHook(args.plugin.renderError, ({ handler }) => ({ plugin: async (ctx, err) => {
  1879. await handler.call(createPluginContext(args, ctx), aggregateBindingErrorsIntoJsError(err));
  1880. } }));
  1881. }
  1882. function createOutputBundle(args, ctx, bundle) {
  1883. const changed = {
  1884. updated: /* @__PURE__ */ new Set(),
  1885. deleted: /* @__PURE__ */ new Set()
  1886. };
  1887. const context = createPluginContext(args, ctx);
  1888. return {
  1889. changed,
  1890. context,
  1891. output: transformToOutputBundle(context, unwrapBindingResult(bundle), changed)
  1892. };
  1893. }
  1894. function bindingifyGenerateBundle(args) {
  1895. return bindingifyHook(args.plugin.generateBundle, ({ handler }) => ({ plugin: async (ctx, bundle, isWrite, opts) => {
  1896. const { changed, context, output } = createOutputBundle(args, ctx, bundle);
  1897. await handler.call(context, args.pluginContextData.getOutputOptions(opts), output, isWrite);
  1898. return collectChangedBundle(changed, output);
  1899. } }));
  1900. }
  1901. function bindingifyWriteBundle(args) {
  1902. return bindingifyHook(args.plugin.writeBundle, ({ handler }) => ({ plugin: async (ctx, bundle, opts) => {
  1903. const { changed, context, output } = createOutputBundle(args, ctx, bundle);
  1904. await handler.call(context, args.pluginContextData.getOutputOptions(opts), output);
  1905. return collectChangedBundle(changed, output);
  1906. } }));
  1907. }
  1908. function bindingifyCloseBundle(args) {
  1909. return bindingifyHook(args.plugin.closeBundle, ({ handler }) => ({ plugin: async (ctx, err) => {
  1910. await handler.call(createPluginContext(args, ctx), err ? aggregateBindingErrorsIntoJsError(err) : void 0);
  1911. } }));
  1912. }
  1913. function bindingifyAddonHook(args, name) {
  1914. return bindingifyHook(args.plugin[name], ({ handler }) => ({ plugin: async (ctx, chunk) => {
  1915. if (typeof handler === "string") return handler;
  1916. return handler.call(createPluginContext(args, ctx), transformRenderedChunk(chunk));
  1917. } }));
  1918. }
  1919. //#endregion
  1920. //#region src/plugin/bindingify-watch-hooks.ts
  1921. function bindingifyHotUpdate(args) {
  1922. return bindingifyHook(args.plugin.hotUpdate, ({ handler }) => ({ plugin: async (ctx, hookArgs) => {
  1923. return await handler.call(createPluginContext(args, ctx), {
  1924. type: hookArgs.kind,
  1925. file: hookArgs.file,
  1926. modules: hookArgs.modules
  1927. }) ?? void 0;
  1928. } }));
  1929. }
  1930. function bindingifyWatchChange(args) {
  1931. return bindingifyHook(args.plugin.watchChange, ({ handler }) => ({ plugin: async (ctx, id, event) => {
  1932. await handler.call(createPluginContext(args, ctx), id, { event });
  1933. } }));
  1934. }
  1935. function bindingifyCloseWatcher(args) {
  1936. return bindingifyHook(args.plugin.closeWatcher, ({ handler }) => ({ plugin: async (ctx) => {
  1937. await handler.call(createPluginContext(args, ctx));
  1938. } }));
  1939. }
  1940. //#endregion
  1941. //#region src/plugin/generated/hook-usage.ts
  1942. var HookUsage = class {
  1943. bitflag = BigInt(0);
  1944. constructor() {}
  1945. union(kind) {
  1946. this.bitflag |= BigInt(kind);
  1947. }
  1948. inner() {
  1949. return Number(this.bitflag);
  1950. }
  1951. };
  1952. function extractHookUsage(plugin) {
  1953. let hookUsage = new HookUsage();
  1954. if (plugin.buildStart) hookUsage.union(1);
  1955. if (plugin.resolveId) hookUsage.union(2);
  1956. if (plugin.resolveDynamicImport) hookUsage.union(4);
  1957. if (plugin.load) hookUsage.union(8);
  1958. if (plugin.transform) hookUsage.union(16);
  1959. if (plugin.moduleParsed) hookUsage.union(32);
  1960. if (plugin.buildEnd) hookUsage.union(64);
  1961. if (plugin.renderStart) hookUsage.union(128);
  1962. if (plugin.renderError) hookUsage.union(256);
  1963. if (plugin.renderChunk) hookUsage.union(512);
  1964. if (plugin.augmentChunkHash) hookUsage.union(1024);
  1965. if (plugin.generateBundle) hookUsage.union(2048);
  1966. if (plugin.writeBundle) hookUsage.union(4096);
  1967. if (plugin.closeBundle) hookUsage.union(8192);
  1968. if (plugin.watchChange) hookUsage.union(16384);
  1969. if (plugin.closeWatcher) hookUsage.union(32768);
  1970. if (plugin.banner) hookUsage.union(131072);
  1971. if (plugin.footer) hookUsage.union(262144);
  1972. if (plugin.intro) hookUsage.union(524288);
  1973. if (plugin.outro) hookUsage.union(1048576);
  1974. if (plugin.resolveFileUrl) hookUsage.union(2097152);
  1975. if (plugin.hotUpdate) hookUsage.union(4194304);
  1976. return hookUsage;
  1977. }
  1978. //#endregion
  1979. //#region src/utils/plugin-timings.ts
  1980. /**
  1981. * Measure what plugin hooks cost, from inside the JavaScript callback.
  1982. *
  1983. * Internal to Rolldown. Nothing here is on a public entry point, and the measurement is not
  1984. * offered as an API — the only consumer is the core, which pulls it while the build closes.
  1985. *
  1986. * The bundler core can only bracket *dispatch* and *completion*. For a hook it invokes
  1987. * concurrently those two points are separated mostly by the queue the call waited in on
  1988. * JavaScript's single thread, and the queue is deepest behind whichever callback is doing
  1989. * the most work — so the hook blocking the thread dilutes its own credit while cheap hooks
  1990. * collect credit for waiting. Ranking from those numbers reliably puts the *cheapest* hook
  1991. * first.
  1992. *
  1993. * The missing quantity is when the callback began running, and that is known here. Starting
  1994. * the clock inside the callback removes the dispatch queue by construction.
  1995. *
  1996. * ## `maxInFlight` decides whether a total means anything
  1997. *
  1998. * Entry-to-exit spans may be summed only if they never overlap. A synchronous callback
  1999. * cannot overlap: it holds the thread until it returns. An `async` one can — it may suspend
  2000. * at an `await` and let another call of the same hook begin, and then both spans cover the
  2001. * same wall clock and the sum counts it twice.
  2002. *
  2003. * Overlap also changes what the span is measuring. A hook that awaits the bundler (say
  2004. * `this.resolve`) spends most of its span waiting for Rust, so the number describes the
  2005. * bundler rather than the plugin. Observed on a real build: one `resolveId` accumulated
  2006. * ~47,000s of span inside a 44s module-loading window.
  2007. *
  2008. * So overlap is measured rather than assumed, per hook: `overlapMs` is the wall time
  2009. * double counted in `ms` because two or more calls were in flight together. A hook is
  2010. * reported with a number when that is a negligible share of its span, and named without one
  2011. * when it is not.
  2012. *
  2013. * The test is deliberately a tolerance rather than "did this ever happen". A peak in-flight
  2014. * count of 2 can mean one incidental overlap in twenty thousand calls, and discarding a
  2015. * twelve-second measurement over that both throws away good data and makes the report
  2016. * depend on scheduling luck — the same hook would appear in one run and vanish in the next.
  2017. *
  2018. * This keeps the rule the core followed — never present a number that cannot be defended —
  2019. * while narrowing "cannot measure" from a property of the *call site* to a property of the
  2020. * *callback*, which is where it actually lives. A hook dispatched concurrently but whose
  2021. * body barely overlaps is measured to within the tolerance.
  2022. *
  2023. * A measured row is still wall time for that callback rather than CPU: a hook that awaits
  2024. * I/O without overlapping another call of itself is charged for the wait. Excluding the
  2025. * dispatch queue is what this buys; it does not distinguish running from awaiting.
  2026. */
  2027. /**
  2028. * How much of a hook's span may be double counted before its total stops being reportable,
  2029. * as a fraction of that span.
  2030. */
  2031. const OVERLAP_TOLERANCE = .01;
  2032. /**
  2033. * One recorder per build, keyed on the object that identifies it.
  2034. *
  2035. * Counters cannot be module-global. A plugin is free to run a nested `rolldown()` build of
  2036. * its own, which finishes first; shared counters would let it flush the outer build's
  2037. * half-accumulated totals and report a window belonging to neither.
  2038. */
  2039. const recorders = /* @__PURE__ */ new WeakMap();
  2040. /** The recorder for one build, created on first use. */
  2041. function pluginTimingsRecorderFor(key) {
  2042. let recorder = recorders.get(key);
  2043. if (recorder === void 0) {
  2044. recorder = {
  2045. costs: /* @__PURE__ */ new Map(),
  2046. warnedMissingGroupLabels: /* @__PURE__ */ new Set(),
  2047. busyMs: 0,
  2048. inFlight: 0,
  2049. busyStart: 0
  2050. };
  2051. recorders.set(key, recorder);
  2052. }
  2053. return recorder;
  2054. }
  2055. function costFor(recorder, owner, hookName) {
  2056. let byHook = recorder.costs.get(owner.key);
  2057. if (byHook === void 0) {
  2058. byHook = /* @__PURE__ */ new Map();
  2059. recorder.costs.set(owner.key, byHook);
  2060. }
  2061. let cost = byHook.get(hookName);
  2062. if (cost === void 0) {
  2063. cost = {
  2064. owner: owner.name,
  2065. kind: owner.kind,
  2066. hookName,
  2067. calls: 0,
  2068. ms: 0,
  2069. inFlight: 0,
  2070. maxInFlight: 0,
  2071. overlapMs: 0,
  2072. lastChange: 0
  2073. };
  2074. byHook.set(hookName, cost);
  2075. }
  2076. return cost;
  2077. }
  2078. /**
  2079. * Fold the interval since the last in-flight change into `overlapMs`, then move the mark.
  2080. * Call immediately before every increment and decrement of `cost.inFlight`.
  2081. */
  2082. function markInFlightChange(cost, at) {
  2083. if (cost.inFlight > 1) cost.overlapMs += (cost.inFlight - 1) * (at - cost.lastChange);
  2084. cost.lastChange = at;
  2085. }
  2086. /**
  2087. * Close out one call. A module-level function rather than a closure per invocation: hooks
  2088. * run hundreds of thousands of times in a large build, and the synchronous path would
  2089. * otherwise allocate one closure per call only to invoke it immediately.
  2090. */
  2091. function settle(recorder, cost, started) {
  2092. const ended = performance.now();
  2093. markInFlightChange(cost, ended);
  2094. cost.inFlight -= 1;
  2095. cost.ms += ended - started;
  2096. recorder.inFlight -= 1;
  2097. if (recorder.inFlight === 0) recorder.busyMs += ended - recorder.busyStart;
  2098. }
  2099. /**
  2100. * Wrap one callback so its execution time is recorded.
  2101. *
  2102. * Returns the callback untouched when there is no recorder, so a build that is not
  2103. * measuring pays nothing beyond one branch at setup.
  2104. */
  2105. function measureHookCost(recorder, owner, hookName, handler) {
  2106. if (recorder === void 0) return handler;
  2107. const cost = costFor(recorder, owner, hookName);
  2108. return function(...args) {
  2109. const started = performance.now();
  2110. markInFlightChange(cost, started);
  2111. cost.calls += 1;
  2112. cost.inFlight += 1;
  2113. if (cost.inFlight > cost.maxInFlight) cost.maxInFlight = cost.inFlight;
  2114. if (recorder.inFlight === 0) recorder.busyStart = started;
  2115. recorder.inFlight += 1;
  2116. let result;
  2117. try {
  2118. result = handler.apply(this, args);
  2119. } catch (error) {
  2120. settle(recorder, cost, started);
  2121. throw error;
  2122. }
  2123. if (typeof result?.then === "function") return result.then((value) => {
  2124. settle(recorder, cost, started);
  2125. return value;
  2126. }, (error) => {
  2127. settle(recorder, cost, started);
  2128. throw error;
  2129. });
  2130. settle(recorder, cost, started);
  2131. return result;
  2132. };
  2133. }
  2134. /**
  2135. * The shared owner for callbacks that users configure directly on the output options.
  2136. * Code-splitting groups use their group objects as owner keys. Each group then has separate
  2137. * timing rows.
  2138. */
  2139. const OUTPUT_OPTIONS_OWNER = {
  2140. key: Symbol("output options"),
  2141. name: "output options",
  2142. kind: "outputOption"
  2143. };
  2144. /** As {@link OUTPUT_OPTIONS_OWNER}, for callbacks configured on the input options. */
  2145. const INPUT_OPTIONS_OWNER = {
  2146. key: Symbol("input options"),
  2147. name: "input options",
  2148. kind: "inputOption"
  2149. };
  2150. /**
  2151. * Wrap `value` when the user supplied a function, and leave every other form alone.
  2152. *
  2153. * Most option callbacks are declared as `string | RegExp | Function | ...`, so this keeps
  2154. * the one cast the wrapping needs in a single place.
  2155. */
  2156. function measureIfFunction(recorder, owner, hookName, value) {
  2157. if (typeof value !== "function") return value;
  2158. return measureHookCost(recorder, owner, hookName, value);
  2159. }
  2160. /**
  2161. * What the build's callbacks have cost so far, leaving the recorder in place.
  2162. *
  2163. * Ungated on purpose: whether a build is worth reporting on is decided from the clocks Rust
  2164. * holds, so the question is not this side's to ask.
  2165. *
  2166. * Rust calls this while the build is closing, so what it gets includes `closeBundle`.
  2167. */
  2168. function summarizePluginTimings(key) {
  2169. const recorder = recorders.get(key);
  2170. if (recorder === void 0) return {
  2171. busyMs: 0,
  2172. rows: []
  2173. };
  2174. const rows = [];
  2175. for (const byHook of recorder.costs.values()) for (const cost of byHook.values()) {
  2176. if (cost.calls === 0) continue;
  2177. rows.push({
  2178. owner: cost.owner,
  2179. kind: cost.kind,
  2180. hook: cost.hookName,
  2181. calls: cost.calls,
  2182. ms: cost.ms,
  2183. maxInFlight: cost.maxInFlight,
  2184. overlapMs: cost.overlapMs,
  2185. rankable: cost.overlapMs <= cost.ms * OVERLAP_TOLERANCE
  2186. });
  2187. }
  2188. return {
  2189. busyMs: recorder.busyMs,
  2190. rows
  2191. };
  2192. }
  2193. //#endregion
  2194. //#region src/plugin/bindingify-plugin.ts
  2195. function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings) {
  2196. const args = {
  2197. plugin,
  2198. options,
  2199. outputOptions,
  2200. pluginContextData,
  2201. onLog,
  2202. logLevel,
  2203. watchMode,
  2204. normalizedOutputPlugins
  2205. };
  2206. const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
  2207. const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
  2208. const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
  2209. const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
  2210. const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
  2211. const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
  2212. const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
  2213. const { plugin: renderChunk, meta: renderChunkMeta, filter: renderChunkFilter } = bindingifyRenderChunk(args);
  2214. const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
  2215. const { plugin: resolveFileUrl, meta: resolveFileUrlMeta } = bindingifyResolveFileUrl(args);
  2216. const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
  2217. const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
  2218. const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
  2219. const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
  2220. const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
  2221. const { plugin: banner, meta: bannerMeta } = bindingifyAddonHook(args, "banner");
  2222. const { plugin: footer, meta: footerMeta } = bindingifyAddonHook(args, "footer");
  2223. const { plugin: intro, meta: introMeta } = bindingifyAddonHook(args, "intro");
  2224. const { plugin: outro, meta: outroMeta } = bindingifyAddonHook(args, "outro");
  2225. const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
  2226. const { plugin: hotUpdate, meta: hotUpdateMeta } = bindingifyHotUpdate(args);
  2227. const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
  2228. let hookUsage = extractHookUsage(plugin).inner();
  2229. const result = {
  2230. name: plugin.name,
  2231. buildStart,
  2232. buildStartMeta,
  2233. resolveId,
  2234. resolveIdMeta,
  2235. resolveIdFilter,
  2236. resolveDynamicImport,
  2237. resolveDynamicImportMeta,
  2238. buildEnd,
  2239. buildEndMeta,
  2240. transform,
  2241. transformMeta,
  2242. transformFilter,
  2243. moduleParsed,
  2244. moduleParsedMeta,
  2245. load,
  2246. loadMeta,
  2247. loadFilter,
  2248. renderChunk,
  2249. renderChunkMeta,
  2250. renderChunkFilter,
  2251. augmentChunkHash,
  2252. augmentChunkHashMeta,
  2253. resolveFileUrl,
  2254. resolveFileUrlMeta,
  2255. renderStart,
  2256. renderStartMeta,
  2257. renderError,
  2258. renderErrorMeta,
  2259. generateBundle,
  2260. generateBundleMeta,
  2261. writeBundle,
  2262. writeBundleMeta,
  2263. closeBundle,
  2264. closeBundleMeta,
  2265. banner,
  2266. bannerMeta,
  2267. footer,
  2268. footerMeta,
  2269. intro,
  2270. introMeta,
  2271. outro,
  2272. outroMeta,
  2273. watchChange,
  2274. watchChangeMeta,
  2275. hotUpdate,
  2276. hotUpdateMeta,
  2277. closeWatcher,
  2278. closeWatcherMeta,
  2279. hookUsage
  2280. };
  2281. return wrapHandlers(result, {
  2282. key: plugin,
  2283. name: result.name,
  2284. kind: "plugin"
  2285. }, timings);
  2286. }
  2287. function wrapHandlers(plugin, owner, timings) {
  2288. for (const hookName of [
  2289. "buildStart",
  2290. "resolveId",
  2291. "resolveDynamicImport",
  2292. "buildEnd",
  2293. "transform",
  2294. "moduleParsed",
  2295. "load",
  2296. "renderChunk",
  2297. "augmentChunkHash",
  2298. "resolveFileUrl",
  2299. "renderStart",
  2300. "renderError",
  2301. "generateBundle",
  2302. "writeBundle",
  2303. "closeBundle",
  2304. "banner",
  2305. "footer",
  2306. "intro",
  2307. "outro",
  2308. "watchChange",
  2309. "hotUpdate",
  2310. "closeWatcher"
  2311. ]) {
  2312. const raw = plugin[hookName];
  2313. const handler = raw && measureHookCost(timings, owner, hookName, raw);
  2314. if (handler) plugin[hookName] = async (...args) => {
  2315. try {
  2316. return await handler(...args);
  2317. } catch (e) {
  2318. return error(logPluginError(e, plugin.name, {
  2319. hook: hookName,
  2320. id: hookName === "transform" ? args[2] : void 0
  2321. }));
  2322. }
  2323. };
  2324. }
  2325. return plugin;
  2326. }
  2327. //#endregion
  2328. //#region src/utils/normalize-transform-options.ts
  2329. /**
  2330. * Normalizes transform options by extracting `define`, `inject`, and `dropLabels` separately from OXC transform options.
  2331. *
  2332. * Prioritizes values from `transform.define`, `transform.inject`, and `transform.dropLabels` over deprecated top-level options.
  2333. */
  2334. function normalizeTransformOptions(inputOptions) {
  2335. const transform = inputOptions.transform;
  2336. const define = transform?.define ? Object.entries(transform.define) : void 0;
  2337. const inject = transform?.inject;
  2338. const dropLabels = transform?.dropLabels;
  2339. let oxcTransformOptions;
  2340. if (transform) {
  2341. const { define: _define, inject: _inject, dropLabels: _dropLabels, ...rest } = transform;
  2342. if (Object.keys(rest).length > 0) {
  2343. if (rest.jsx === false) rest.jsx = "disable";
  2344. oxcTransformOptions = rest;
  2345. }
  2346. }
  2347. return {
  2348. define,
  2349. inject,
  2350. dropLabels,
  2351. oxcTransformOptions
  2352. };
  2353. }
  2354. //#endregion
  2355. //#region src/utils/default-dev-runtime.ts
  2356. function getDefaultDevRuntime(host = "localhost", port = 3e3) {
  2357. 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}`);
  2358. }
  2359. //#endregion
  2360. //#region src/utils/bindingify-input-options.ts
  2361. function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings) {
  2362. const plugins = rawPlugins.map((plugin) => {
  2363. if (getParallelPluginInfo(plugin)) return;
  2364. if (plugin instanceof BuiltinPlugin) switch (plugin.name) {
  2365. case "builtin:vite-manifest": return bindingifyManifestPlugin(plugin, pluginContextData);
  2366. default: return bindingifyBuiltInPlugin(plugin);
  2367. }
  2368. return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel, watchMode, timings);
  2369. });
  2370. const normalizedTransform = normalizeTransformOptions(inputOptions);
  2371. return {
  2372. input: bindingifyInput(inputOptions.input),
  2373. plugins,
  2374. cwd: inputOptions.cwd ?? process.cwd(),
  2375. external: bindingifyExternal(inputOptions.external, timings),
  2376. resolve: bindingifyResolve(inputOptions.resolve),
  2377. platform: inputOptions.platform,
  2378. shimMissingExports: inputOptions.shimMissingExports,
  2379. logLevel: bindingifyLogLevel(logLevel),
  2380. onLog,
  2381. treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake, timings),
  2382. moduleTypes: inputOptions.moduleTypes,
  2383. define: normalizedTransform.define,
  2384. inject: bindingifyInject(normalizedTransform.inject),
  2385. experimental: bindingifyExperimental(inputOptions.experimental),
  2386. profilerNames: outputOptions.generatedCode?.profilerNames,
  2387. transform: normalizedTransform.oxcTransformOptions,
  2388. watch: bindingifyWatch(inputOptions.watch),
  2389. dropLabels: normalizedTransform.dropLabels,
  2390. keepNames: outputOptions.keepNames,
  2391. checks: inputOptions.checks,
  2392. pluginTimings: timings ? () => summarizePluginTimings(inputOptions) : void 0,
  2393. deferSyncScanData: () => {
  2394. let ret = [];
  2395. pluginContextData.moduleOptionMap.forEach((value, key) => {
  2396. if (value.invalidate) ret.push({
  2397. id: key,
  2398. sideEffects: value.moduleSideEffects ?? void 0
  2399. });
  2400. });
  2401. return ret;
  2402. },
  2403. makeAbsoluteExternalsRelative: bindingifyMakeAbsoluteExternalsRelative(inputOptions.makeAbsoluteExternalsRelative),
  2404. devtools: inputOptions.devtools,
  2405. invalidateJsSideCache: pluginContextData.clear.bind(pluginContextData),
  2406. preserveEntrySignatures: bindingifyPreserveEntrySignatures(inputOptions.preserveEntrySignatures),
  2407. optimization: inputOptions.optimization,
  2408. context: inputOptions.context,
  2409. tsconfig: inputOptions.resolve?.tsconfigFilename ?? inputOptions.tsconfig
  2410. };
  2411. }
  2412. function bindingifyDevMode(devMode) {
  2413. if (devMode) {
  2414. if (typeof devMode === "boolean") return devMode ? {
  2415. implement: getDefaultDevRuntime(),
  2416. skipCommonRuntimeInjection: true
  2417. } : void 0;
  2418. const usesDefaultRuntime = devMode.implement == null;
  2419. return {
  2420. ...devMode,
  2421. implement: devMode.implement ?? getDefaultDevRuntime(devMode.host, devMode.port),
  2422. skipCommonRuntimeInjection: usesDefaultRuntime ? true : devMode.skipCommonRuntimeInjection
  2423. };
  2424. }
  2425. }
  2426. function bindingifyAttachDebugInfo(attachDebugInfo) {
  2427. switch (attachDebugInfo) {
  2428. case void 0: return;
  2429. case "full": return import_binding.BindingAttachDebugInfo.Full;
  2430. case "simple": return import_binding.BindingAttachDebugInfo.Simple;
  2431. case "none": return import_binding.BindingAttachDebugInfo.None;
  2432. }
  2433. }
  2434. function bindingifyExternal(external, timings) {
  2435. if (external) {
  2436. if (typeof external === "function") {
  2437. const measured = measureHookCost(timings, INPUT_OPTIONS_OWNER, "external", external);
  2438. return (id, importer, isResolved) => {
  2439. if (id.startsWith("\0")) return false;
  2440. return measured(id, importer, isResolved) ?? false;
  2441. };
  2442. }
  2443. return arraify(external);
  2444. }
  2445. }
  2446. function bindingifyExperimental(experimental) {
  2447. let chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ExecOrder;
  2448. if (experimental?.chunkModulesOrder) switch (experimental.chunkModulesOrder) {
  2449. case "exec-order":
  2450. chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ExecOrder;
  2451. break;
  2452. case "module-id":
  2453. chunkModulesOrder = import_binding.BindingChunkModuleOrderBy.ModuleId;
  2454. break;
  2455. default: throw new Error(`Unexpected chunkModulesOrder: ${experimental.chunkModulesOrder}`);
  2456. }
  2457. return {
  2458. viteMode: experimental?.viteMode,
  2459. resolveNewUrlToAsset: experimental?.resolveNewUrlToAsset,
  2460. devMode: bindingifyDevMode(experimental?.devMode),
  2461. attachDebugInfo: bindingifyAttachDebugInfo(experimental?.attachDebugInfo),
  2462. chunkModulesOrder,
  2463. chunkImportMap: experimental?.chunkImportMap,
  2464. onDemandWrapping: experimental?.onDemandWrapping,
  2465. incrementalBuild: experimental?.incrementalBuild,
  2466. nativeMagicString: experimental?.nativeMagicString,
  2467. chunkOptimization: experimental?.chunkOptimization,
  2468. lazyBarrel: experimental?.lazyBarrel
  2469. };
  2470. }
  2471. function bindingifyResolve(resolve) {
  2472. const yarnPnp = typeof process === "object" && !!process.versions?.pnp;
  2473. if (resolve) {
  2474. const { alias, extensionAlias, ...rest } = resolve;
  2475. return {
  2476. alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
  2477. find: name,
  2478. replacements: replacement === false ? [void 0] : arraify(replacement)
  2479. })) : void 0,
  2480. extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
  2481. target: name,
  2482. replacements: value
  2483. })) : void 0,
  2484. yarnPnp,
  2485. ...rest
  2486. };
  2487. } else return { yarnPnp };
  2488. }
  2489. function bindingifyInject(inject) {
  2490. if (inject) return Object.entries(inject).map(([alias, item]) => {
  2491. if (Array.isArray(item)) {
  2492. if (item[1] === "*") return {
  2493. tagNamespace: true,
  2494. alias,
  2495. from: item[0]
  2496. };
  2497. return {
  2498. tagNamed: true,
  2499. alias,
  2500. from: item[0],
  2501. imported: item[1]
  2502. };
  2503. } else return {
  2504. tagNamed: true,
  2505. imported: "default",
  2506. alias,
  2507. from: item
  2508. };
  2509. });
  2510. }
  2511. function bindingifyLogLevel(logLevel) {
  2512. switch (logLevel) {
  2513. case "silent": return import_binding.BindingLogLevel.Silent;
  2514. case "debug": return import_binding.BindingLogLevel.Debug;
  2515. case "warn": return import_binding.BindingLogLevel.Warn;
  2516. case "info": return import_binding.BindingLogLevel.Info;
  2517. default: throw new Error(`Unexpected log level: ${logLevel}`);
  2518. }
  2519. }
  2520. function bindingifyInput(input) {
  2521. if (input === void 0) return [];
  2522. if (typeof input === "string") return [{ import: input }];
  2523. if (Array.isArray(input)) return input.map((src) => ({ import: src }));
  2524. return Object.entries(input).map(([name, import_path]) => {
  2525. return {
  2526. name,
  2527. import: import_path
  2528. };
  2529. });
  2530. }
  2531. function bindingifyWatch(watch) {
  2532. if (watch) {
  2533. const watcher = watch.watcher ?? {};
  2534. return {
  2535. buildDelay: watch.buildDelay,
  2536. skipWrite: watch.skipWrite,
  2537. usePolling: watcher.usePolling,
  2538. pollInterval: watcher.pollInterval,
  2539. compareContentsForPolling: watcher.compareContentsForPolling,
  2540. useDebounce: watcher.useDebounce,
  2541. debounceDelay: watcher.debounceDelay,
  2542. debounceTickRate: watcher.debounceTickRate,
  2543. include: normalizedStringOrRegex(watch.include),
  2544. exclude: normalizedStringOrRegex(watch.exclude),
  2545. onInvalidate: (...args) => watch.onInvalidate?.(...args)
  2546. };
  2547. }
  2548. }
  2549. function bindingifyTreeshakeOptions(config, timings) {
  2550. if (config === false) return;
  2551. if (config === true || config === void 0) return { moduleSideEffects: true };
  2552. let normalizedConfig = {
  2553. moduleSideEffects: true,
  2554. annotations: config.annotations,
  2555. manualPureFunctions: config.manualPureFunctions,
  2556. unknownGlobalSideEffects: config.unknownGlobalSideEffects,
  2557. invalidImportSideEffects: config.invalidImportSideEffects,
  2558. commonjs: config.commonjs
  2559. };
  2560. switch (config.propertyReadSideEffects) {
  2561. case "always":
  2562. normalizedConfig.propertyReadSideEffects = import_binding.BindingPropertyReadSideEffects.Always;
  2563. break;
  2564. case false: normalizedConfig.propertyReadSideEffects = import_binding.BindingPropertyReadSideEffects.False;
  2565. }
  2566. switch (config.propertyWriteSideEffects) {
  2567. case "always":
  2568. normalizedConfig.propertyWriteSideEffects = import_binding.BindingPropertyWriteSideEffects.Always;
  2569. break;
  2570. case false: normalizedConfig.propertyWriteSideEffects = import_binding.BindingPropertyWriteSideEffects.False;
  2571. }
  2572. if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
  2573. else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
  2574. external: true,
  2575. sideEffects: false
  2576. }, {
  2577. external: false,
  2578. sideEffects: true
  2579. }];
  2580. else normalizedConfig.moduleSideEffects = measureIfFunction(timings, INPUT_OPTIONS_OWNER, "treeshake.moduleSideEffects", config.moduleSideEffects);
  2581. return normalizedConfig;
  2582. }
  2583. function bindingifyMakeAbsoluteExternalsRelative(makeAbsoluteExternalsRelative) {
  2584. if (makeAbsoluteExternalsRelative === "ifRelativeSource") return { type: "IfRelativeSource" };
  2585. if (typeof makeAbsoluteExternalsRelative === "boolean") return {
  2586. type: "Bool",
  2587. field0: makeAbsoluteExternalsRelative
  2588. };
  2589. }
  2590. function bindingifyPreserveEntrySignatures(preserveEntrySignatures) {
  2591. if (preserveEntrySignatures == void 0) return;
  2592. else if (typeof preserveEntrySignatures === "string") return {
  2593. type: "String",
  2594. field0: preserveEntrySignatures
  2595. };
  2596. else return {
  2597. type: "Bool",
  2598. field0: preserveEntrySignatures
  2599. };
  2600. }
  2601. //#endregion
  2602. 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 };