rolldown 1.0.0-beta.3-commit.62fba31 → 1.0.0-beta.3-commit.d298c0b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- import { augmentCodeLocation, colors, error, import_binding, logCycleLoading, logInputHookInOutputPlugin, logInvalidLogPosition, logMinifyWarning, logMultiplyNotifyOption, logPluginError, parseAst } from "./parse-ast-index-CSo7-trQ.mjs";
1
+ import { augmentCodeLocation, colors, error, import_binding, logCycleLoading, logInputHookInOutputPlugin, logInvalidLogPosition, logMinifyWarning, logMultiplyNotifyOption, logPluginError, parseAst } from "./parse-ast-index-Aeq00bwr.mjs";
2
2
  import path from "node:path";
3
+ import * as v from "valibot";
4
+ import { toJsonSchema } from "@valibot/to-json-schema";
3
5
  import { Buffer } from "node:buffer";
4
6
  import { Worker } from "node:worker_threads";
5
7
  import { availableParallelism } from "node:os";
6
- import * as v from "valibot";
7
- import { toJsonSchema } from "@valibot/to-json-schema";
8
8
 
9
9
  //#region src/utils/define-config.ts
10
10
  function defineConfig(config) {
@@ -404,2095 +404,2127 @@ function getSortedPlugins(hookName, plugins) {
404
404
  }
405
405
 
406
406
  //#endregion
407
- //#region src/utils/asset-source.ts
408
- function transformAssetSource(bindingAssetSource$1) {
409
- return bindingAssetSource$1.inner;
410
- }
411
- function bindingAssetSource(source) {
412
- return { inner: source };
413
- }
414
-
415
- //#endregion
416
- //#region src/types/sourcemap.ts
417
- function bindingifySourcemap$1(map) {
418
- if (map == null) return;
419
- return { inner: typeof map === "string" ? map : {
420
- file: map.file ?? void 0,
421
- mappings: map.mappings,
422
- sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
423
- sources: map.sources?.map((s) => s ?? void 0),
424
- sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
425
- names: map.names,
426
- x_google_ignoreList: map.x_google_ignoreList,
427
- debugId: "debugId" in map ? map.debugId : void 0
428
- } };
429
- }
430
-
431
- //#endregion
432
- //#region src/utils/error.ts
433
- function normalizeErrors(rawErrors) {
434
- const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
435
- kind: e.kind,
436
- message: e.message,
437
- stack: void 0
438
- }));
439
- let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
440
- for (let i = 0; i < errors.length; i++) {
441
- if (i >= 5) {
442
- summary += "\n...";
443
- break;
444
- }
445
- summary += getErrorMessage(errors[i]) + "\n";
446
- }
447
- const wrapper = new Error(summary);
448
- Object.defineProperty(wrapper, "errors", {
449
- configurable: true,
450
- enumerable: true,
451
- get: () => errors,
452
- set: (value) => Object.defineProperty(wrapper, "errors", {
453
- configurable: true,
454
- enumerable: true,
455
- value
456
- })
457
- });
458
- return wrapper;
459
- }
460
- function getErrorMessage(e) {
461
- let s = "";
462
- if (e.plugin) s += `[plugin ${e.plugin}]`;
463
- const id = e.id ?? e.loc?.file;
464
- if (id) {
465
- s += " " + id;
466
- if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
467
- }
468
- if (s) s += "\n";
469
- const message = `${e.name ?? "Error"}: ${e.message}`;
470
- s += message;
471
- if (e.frame) s = joinNewLine(s, e.frame);
472
- if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
473
- return s;
474
- }
475
- function joinNewLine(s1, s2) {
476
- return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
477
- }
478
-
479
- //#endregion
480
- //#region src/utils/transform-rendered-module.ts
481
- function transformToRenderedModule(bindingRenderedModule) {
482
- return {
483
- get code() {
484
- return bindingRenderedModule.code;
485
- },
486
- get renderedLength() {
487
- return bindingRenderedModule.code?.length || 0;
488
- },
489
- get renderedExports() {
490
- return bindingRenderedModule.renderedExports;
491
- }
492
- };
493
- }
494
-
495
- //#endregion
496
- //#region src/utils/transform-rendered-chunk.ts
497
- function transformRenderedChunk(chunk) {
498
- return {
499
- get name() {
500
- return chunk.name;
501
- },
502
- get isEntry() {
503
- return chunk.isEntry;
504
- },
505
- get isDynamicEntry() {
506
- return chunk.isDynamicEntry;
507
- },
508
- get facadeModuleId() {
509
- return chunk.facadeModuleId;
510
- },
511
- get moduleIds() {
512
- return chunk.moduleIds;
513
- },
514
- get exports() {
515
- return chunk.exports;
516
- },
517
- get fileName() {
518
- return chunk.fileName;
519
- },
520
- get imports() {
521
- return chunk.imports;
522
- },
523
- get dynamicImports() {
524
- return chunk.dynamicImports;
525
- },
526
- get modules() {
527
- return transformChunkModules(chunk.modules);
528
- }
529
- };
530
- }
531
- function transformChunkModules(modules) {
532
- const result = {};
533
- for (let i = 0; i < modules.values.length; i++) {
534
- let key = modules.keys[i];
535
- const mod = modules.values[i];
536
- result[key] = transformToRenderedModule(mod);
537
- }
538
- return result;
539
- }
540
-
541
- //#endregion
542
- //#region src/utils/transform-to-rollup-output.ts
543
- function transformToRollupSourceMap(map) {
544
- const parsed = JSON.parse(map);
545
- const obj = {
546
- ...parsed,
547
- toString() {
548
- return JSON.stringify(obj);
549
- },
550
- toUrl() {
551
- return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
552
- }
553
- };
554
- return obj;
555
- }
556
- function transformToRollupOutputChunk(bindingChunk, changed) {
557
- const chunk = {
558
- type: "chunk",
559
- get code() {
560
- return bindingChunk.code;
561
- },
562
- fileName: bindingChunk.fileName,
563
- name: bindingChunk.name,
564
- get modules() {
565
- return transformChunkModules(bindingChunk.modules);
566
- },
567
- get imports() {
568
- return bindingChunk.imports;
569
- },
570
- get dynamicImports() {
571
- return bindingChunk.dynamicImports;
572
- },
573
- exports: bindingChunk.exports,
574
- isEntry: bindingChunk.isEntry,
575
- facadeModuleId: bindingChunk.facadeModuleId || null,
576
- isDynamicEntry: bindingChunk.isDynamicEntry,
577
- get moduleIds() {
578
- return bindingChunk.moduleIds;
579
- },
580
- get map() {
581
- return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
582
- },
583
- sourcemapFileName: bindingChunk.sourcemapFileName || null,
584
- preliminaryFileName: bindingChunk.preliminaryFileName
585
- };
586
- const cache = {};
587
- return new Proxy(chunk, {
588
- get(target, p) {
589
- if (p in cache) return cache[p];
590
- return target[p];
591
- },
592
- set(target, p, newValue) {
593
- cache[p] = newValue;
594
- changed?.updated.add(bindingChunk.fileName);
595
- return true;
596
- },
597
- has(target, p) {
598
- if (p in cache) return true;
599
- return p in target;
600
- }
601
- });
602
- }
603
- function transformToRollupOutputAsset(bindingAsset, changed) {
604
- const asset = {
605
- type: "asset",
606
- fileName: bindingAsset.fileName,
607
- originalFileName: bindingAsset.originalFileName || null,
608
- originalFileNames: bindingAsset.originalFileNames,
609
- get source() {
610
- return transformAssetSource(bindingAsset.source);
611
- },
612
- name: bindingAsset.name ?? void 0,
613
- names: bindingAsset.names
614
- };
615
- const cache = {};
616
- return new Proxy(asset, {
617
- get(target, p) {
618
- if (p in cache) return cache[p];
619
- return target[p];
620
- },
621
- set(target, p, newValue) {
622
- cache[p] = newValue;
623
- changed?.updated.add(bindingAsset.fileName);
624
- return true;
625
- }
626
- });
627
- }
628
- function transformToRollupOutput(output, changed) {
629
- handleOutputErrors(output);
630
- const { chunks, assets } = output;
631
- return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
632
- }
633
- function handleOutputErrors(output) {
634
- const rawErrors = output.errors;
635
- if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
636
- }
637
- function transformToOutputBundle(output, changed) {
638
- const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
639
- return new Proxy(bundle, { deleteProperty(target, property) {
640
- if (typeof property === "string") changed.deleted.add(property);
641
- return true;
642
- } });
643
- }
644
- function collectChangedBundle(changed, bundle) {
645
- const assets = [];
646
- const chunks = [];
647
- for (const key in bundle) {
648
- if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
649
- const item = bundle[key];
650
- if (item.type === "asset") assets.push({
651
- filename: item.fileName,
652
- originalFileNames: item.originalFileNames,
653
- source: bindingAssetSource(item.source),
654
- names: item.names
655
- });
656
- else chunks.push({
657
- code: item.code,
658
- filename: item.fileName,
659
- name: item.name,
660
- isEntry: item.isEntry,
661
- exports: item.exports,
662
- modules: {},
663
- imports: item.imports,
664
- dynamicImports: item.dynamicImports,
665
- facadeModuleId: item.facadeModuleId || void 0,
666
- isDynamicEntry: item.isDynamicEntry,
667
- moduleIds: item.moduleIds,
668
- map: bindingifySourcemap$1(item.map),
669
- sourcemapFilename: item.sourcemapFileName || void 0,
670
- preliminaryFilename: item.preliminaryFileName
671
- });
672
- }
673
- return {
674
- assets,
675
- chunks,
676
- deleted: Array.from(changed.deleted)
677
- };
678
- }
679
-
680
- //#endregion
681
- //#region src/utils/transform-sourcemap.ts
682
- function isEmptySourcemapFiled(array) {
683
- if (!array) return true;
684
- if (array.length === 0 || !array[0]) return true;
685
- return false;
686
- }
687
- function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
688
- if (!rawMap) return;
689
- let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
690
- if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
691
- if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
692
- return map;
693
- }
694
-
695
- //#endregion
696
- //#region src/utils/transform-module-info.ts
697
- function transformModuleInfo(info, option) {
698
- return {
699
- get ast() {
700
- return unsupported("ModuleInfo#ast");
701
- },
702
- get code() {
703
- return info.code;
704
- },
705
- id: info.id,
706
- importers: info.importers,
707
- dynamicImporters: info.dynamicImporters,
708
- importedIds: info.importedIds,
709
- dynamicallyImportedIds: info.dynamicallyImportedIds,
710
- exports: info.exports,
711
- isEntry: info.isEntry,
712
- ...option
713
- };
714
- }
715
-
716
- //#endregion
717
- //#region src/plugin/minimal-plugin-context.ts
718
- var MinimalPluginContext = class {
719
- info;
720
- warn;
721
- debug;
722
- meta;
723
- constructor(onLog, logLevel, pluginName) {
724
- this.pluginName = pluginName;
725
- this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
726
- this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
727
- this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
728
- this.meta = {
729
- rollupVersion: "4.23.0",
730
- rolldownVersion: VERSION,
731
- watchMode: false
732
- };
733
- }
734
- error(e) {
735
- return error(logPluginError(normalizeLog(e), this.pluginName));
736
- }
737
- };
738
-
739
- //#endregion
740
- //#region src/utils/transform-side-effects.ts
741
- function bindingifySideEffects(sideEffects) {
742
- switch (sideEffects) {
743
- case true: return import_binding.BindingHookSideEffects.True;
744
- case false: return import_binding.BindingHookSideEffects.False;
745
- case "no-treeshake": return import_binding.BindingHookSideEffects.NoTreeshake;
746
- case null:
747
- case void 0: return void 0;
748
- default: throw new Error(`Unexpected side effects: ${sideEffects}`);
749
- }
750
- }
751
-
752
- //#endregion
753
- //#region src/plugin/plugin-context.ts
754
- var PluginContext = class extends MinimalPluginContext {
755
- getModuleInfo;
756
- constructor(outputOptions, context, plugin, data, onLog, logLevel, currentLoadingModule) {
757
- super(onLog, logLevel, plugin.name);
758
- this.outputOptions = outputOptions;
759
- this.context = context;
760
- this.data = data;
761
- this.onLog = onLog;
762
- this.currentLoadingModule = currentLoadingModule;
763
- this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
764
- }
765
- async load(options) {
766
- const id = options.id;
767
- if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
768
- const moduleInfo = this.data.getModuleInfo(id, this.context);
769
- if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
770
- const rawOptions = {
771
- meta: options.meta || {},
772
- moduleSideEffects: options.moduleSideEffects || null,
773
- invalidate: false
774
- };
775
- this.data.updateModuleOption(id, rawOptions);
776
- async function createLoadModulePromise(context, data) {
777
- const loadPromise = data.loadModulePromiseMap.get(id);
778
- if (loadPromise) return loadPromise;
779
- let resolveFn;
780
- const promise = new Promise((resolve, _) => {
781
- resolveFn = resolve;
782
- });
783
- data.loadModulePromiseMap.set(id, promise);
784
- try {
785
- await context.load(id, bindingifySideEffects(options.moduleSideEffects), resolveFn);
786
- } finally {
787
- data.loadModulePromiseMap.delete(id);
788
- }
789
- return promise;
790
- }
791
- await createLoadModulePromise(this.context, this.data);
792
- return this.data.getModuleInfo(id, this.context);
793
- }
794
- async resolve(source, importer, options) {
795
- let receipt = void 0;
796
- if (options != null) receipt = this.data.saveResolveOptions(options);
797
- const res = await this.context.resolve(source, importer, {
798
- custom: receipt,
799
- skipSelf: options?.skipSelf
800
- });
801
- if (receipt != null) this.data.removeSavedResolveOptions(receipt);
802
- if (res == null) return null;
803
- const info = this.data.getModuleOption(res.id) || {};
804
- return {
805
- ...res,
806
- ...info
807
- };
808
- }
809
- emitFile = (file) => {
810
- if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
811
- if (file.type === "chunk") return this.context.emitChunk(file);
812
- const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
813
- const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
814
- return this.context.emitFile({
815
- ...file,
816
- originalFileName: file.originalFileName || void 0,
817
- source: bindingAssetSource(file.source)
818
- }, filename, fnSanitizedFileName);
819
- };
820
- getAssetFileNames(file) {
821
- if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
822
- names: file.name ? [file.name] : [],
823
- originalFileNames: file.originalFileName ? [file.originalFileName] : [],
824
- source: file.source,
825
- type: "asset"
826
- });
827
- }
828
- getFileName(referenceId) {
829
- return this.context.getFileName(referenceId);
830
- }
831
- getModuleIds() {
832
- return this.data.getModuleIds(this.context);
833
- }
834
- addWatchFile(id) {
835
- this.context.addWatchFile(id);
836
- }
837
- parse(input, options) {
838
- return parseAst(input, options);
839
- }
840
- };
841
-
842
- //#endregion
843
- //#region src/plugin/transform-plugin-context.ts
844
- var TransformPluginContext = class extends PluginContext {
845
- constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption) {
846
- super(outputOptions, context, plugin, data, onLog, LogLevelOption, moduleId);
847
- this.inner = inner;
848
- this.moduleId = moduleId;
849
- this.moduleSource = moduleSource;
850
- const getLogHandler$1 = (handler) => (log, pos) => {
851
- log = normalizeLog(log);
852
- if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
853
- log.id = moduleId;
854
- log.hook = "transform";
855
- handler(log);
856
- };
857
- this.debug = getLogHandler$1(this.debug);
858
- this.warn = getLogHandler$1(this.warn);
859
- this.info = getLogHandler$1(this.info);
860
- }
861
- error(e, pos) {
862
- if (typeof e === "string") e = { message: e };
863
- if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
864
- e.id = this.moduleId;
865
- e.hook = "transform";
866
- return error(logPluginError(normalizeLog(e), this.pluginName));
867
- }
868
- getCombinedSourcemap() {
869
- return JSON.parse(this.inner.getCombinedSourcemap());
870
- }
871
- };
872
-
873
- //#endregion
874
- //#region src/plugin/bindingify-plugin-hook-meta.ts
875
- function bindingifyPluginHookMeta(options) {
876
- return { order: bindingPluginOrder(options.order) };
877
- }
878
- function bindingPluginOrder(order) {
879
- switch (order) {
880
- case "post": return import_binding.BindingPluginOrder.Post;
881
- case "pre": return import_binding.BindingPluginOrder.Pre;
882
- case null:
883
- case void 0: return void 0;
884
- default: throw new Error(`Unknown plugin order: ${order}`);
885
- }
886
- }
887
-
888
- //#endregion
889
- //#region src/constants/plugin-context.ts
890
- const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
891
-
892
- //#endregion
893
- //#region src/plugin/bindingify-hook-filter.ts
894
- function bindingifyStringFilter(matcher) {
895
- if (typeof matcher === "string" || matcher instanceof RegExp) return { include: [matcher] };
896
- if (Array.isArray(matcher)) return { include: matcher };
897
- return {
898
- include: matcher.include ? arraify(matcher.include) : void 0,
899
- exclude: matcher.exclude ? arraify(matcher.exclude) : void 0
900
- };
901
- }
902
- function bindingifyResolveIdFilter(filterOption) {
903
- return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
904
- }
905
- function bindingifyLoadFilter(filterOption) {
906
- return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
907
- }
908
- function bindingifyTransformFilter(filterOption) {
909
- if (!filterOption) return void 0;
910
- const { id, code, moduleType } = filterOption;
911
- let moduleTypeRet;
912
- if (moduleType) if (Array.isArray(moduleType)) moduleTypeRet = moduleType;
913
- else moduleTypeRet = moduleType.include;
914
- return {
915
- id: id ? bindingifyStringFilter(id) : void 0,
916
- code: code ? bindingifyStringFilter(code) : void 0,
917
- moduleType: moduleTypeRet
918
- };
919
- }
920
-
921
- //#endregion
922
- //#region src/options/normalized-input-options.ts
923
- var NormalizedInputOptionsImpl = class {
924
- inner;
925
- constructor(inner, onLog) {
926
- this.onLog = onLog;
927
- this.inner = inner;
928
- }
929
- get shimMissingExports() {
930
- return this.inner.shimMissingExports;
931
- }
932
- get input() {
933
- return this.inner.input;
934
- }
935
- get cwd() {
936
- return this.inner.cwd ?? void 0;
937
- }
938
- get platform() {
939
- return this.inner.platform;
940
- }
941
- };
942
-
943
- //#endregion
944
- //#region src/plugin/bindingify-build-hooks.ts
945
- function bindingifyBuildStart(args) {
946
- const hook = args.plugin.buildStart;
947
- if (!hook) return {};
948
- const { handler, meta } = normalizeHook(hook);
949
- return {
950
- plugin: async (ctx, opts) => {
951
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedInputOptionsImpl(opts, args.onLog));
952
- },
953
- meta: bindingifyPluginHookMeta(meta)
954
- };
955
- }
956
- function bindingifyBuildEnd(args) {
957
- const hook = args.plugin.buildEnd;
958
- if (!hook) return {};
959
- const { handler, meta } = normalizeHook(hook);
960
- return {
961
- plugin: async (ctx, err) => {
962
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), err ? normalizeErrors(err) : void 0);
963
- },
964
- meta: bindingifyPluginHookMeta(meta)
965
- };
966
- }
967
- function bindingifyResolveId(args) {
968
- const hook = args.plugin.resolveId;
969
- if (!hook) return {};
970
- const { handler, meta, options } = normalizeHook(hook);
971
- return {
972
- plugin: async (ctx, specifier, importer, extraOptions) => {
973
- const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
974
- const newExtraOptions = {
975
- ...extraOptions,
976
- custom: contextResolveOptions?.custom,
977
- [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
978
- };
979
- const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0, newExtraOptions);
980
- if (ret == null) return;
981
- if (ret === false) return {
982
- id: specifier,
983
- external: true
984
- };
985
- if (typeof ret === "string") return { id: ret };
986
- let exist = args.pluginContextData.updateModuleOption(ret.id, {
987
- meta: ret.meta || {},
988
- moduleSideEffects: ret.moduleSideEffects ?? null,
989
- invalidate: false
990
- });
991
- return {
992
- id: ret.id,
993
- external: ret.external,
994
- sideEffects: bindingifySideEffects(exist.moduleSideEffects)
995
- };
996
- },
997
- meta: bindingifyPluginHookMeta(meta),
998
- filter: bindingifyResolveIdFilter(options.filter)
999
- };
1000
- }
1001
- function bindingifyResolveDynamicImport(args) {
1002
- const hook = args.plugin.resolveDynamicImport;
1003
- if (!hook) return {};
1004
- const { handler, meta } = normalizeHook(hook);
1005
- return {
1006
- plugin: async (ctx, specifier, importer) => {
1007
- const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0);
1008
- if (ret == null) return;
1009
- if (ret === false) return {
1010
- id: specifier,
1011
- external: true
1012
- };
1013
- if (typeof ret === "string") return { id: ret };
1014
- const result = {
1015
- id: ret.id,
1016
- external: ret.external
1017
- };
1018
- if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
1019
- args.pluginContextData.updateModuleOption(ret.id, {
1020
- meta: ret.meta || {},
1021
- moduleSideEffects: ret.moduleSideEffects || null,
1022
- invalidate: false
1023
- });
1024
- return result;
1025
- },
1026
- meta: bindingifyPluginHookMeta(meta)
1027
- };
1028
- }
1029
- function bindingifyTransform(args) {
1030
- const hook = args.plugin.transform;
1031
- if (!hook) return {};
1032
- const { handler, meta, options } = normalizeHook(hook);
1033
- return {
1034
- plugin: async (ctx, code, id, meta$1) => {
1035
- const ret = await handler.call(new TransformPluginContext(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel), code, id, meta$1);
1036
- if (ret == null) return void 0;
1037
- if (typeof ret === "string") return { code: ret };
1038
- let moduleOption = args.pluginContextData.updateModuleOption(id, {
1039
- meta: ret.meta ?? {},
1040
- moduleSideEffects: ret.moduleSideEffects ?? null,
1041
- invalidate: false
1042
- });
1043
- return {
1044
- code: ret.code,
1045
- map: bindingifySourcemap$1(normalizeTransformHookSourcemap(id, code, ret.map)),
1046
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
1047
- moduleType: ret.moduleType
1048
- };
1049
- },
1050
- meta: bindingifyPluginHookMeta(meta),
1051
- filter: bindingifyTransformFilter(options.filter)
1052
- };
1053
- }
1054
- function bindingifyLoad(args) {
1055
- const hook = args.plugin.load;
1056
- if (!hook) return {};
1057
- const { handler, meta, options } = normalizeHook(hook);
1058
- return {
1059
- plugin: async (ctx, id) => {
1060
- const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, id), id);
1061
- if (ret == null) return;
1062
- if (typeof ret === "string") return { code: ret };
1063
- let moduleOption = args.pluginContextData.updateModuleOption(id, {
1064
- meta: ret.meta || {},
1065
- moduleSideEffects: ret.moduleSideEffects ?? null,
1066
- invalidate: false
1067
- });
1068
- let map = preProcessSourceMap(ret, id);
1069
- return {
1070
- code: ret.code,
1071
- map: bindingifySourcemap$1(map),
1072
- moduleType: ret.moduleType,
1073
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
1074
- };
1075
- },
1076
- meta: bindingifyPluginHookMeta(meta),
1077
- filter: bindingifyLoadFilter(options.filter)
1078
- };
1079
- }
1080
- function preProcessSourceMap(ret, id) {
1081
- if (!ret.map) return;
1082
- let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
1083
- if (!isEmptySourcemapFiled(map.sources)) {
1084
- const directory = path.dirname(id) || ".";
1085
- const sourceRoot = map.sourceRoot || ".";
1086
- map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
1087
- }
1088
- return map;
1089
- }
1090
- function bindingifyModuleParsed(args) {
1091
- const hook = args.plugin.moduleParsed;
1092
- if (!hook) return {};
1093
- const { handler, meta } = normalizeHook(hook);
1094
- return {
1095
- plugin: async (ctx, moduleInfo) => {
1096
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
1097
- },
1098
- meta: bindingifyPluginHookMeta(meta)
1099
- };
1100
- }
1101
-
1102
- //#endregion
1103
- //#region src/utils/bindingify-output-options.ts
1104
- function bindingifyOutputOptions(outputOptions) {
1105
- const { dir, format, exports, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName } = outputOptions;
1106
- return {
1107
- dir,
1108
- file: file == null ? void 0 : file,
1109
- format: bindingifyFormat(format),
1110
- exports,
1111
- hashCharacters,
1112
- sourcemap: bindingifySourcemap(sourcemap),
1113
- sourcemapDebugIds,
1114
- sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
1115
- sourcemapPathTransform,
1116
- banner: bindingifyAddon(banner),
1117
- footer: bindingifyAddon(footer),
1118
- intro: bindingifyAddon(intro),
1119
- outro: bindingifyAddon(outro),
1120
- extend: outputOptions.extend,
1121
- globals,
1122
- esModule,
1123
- name,
1124
- assetFileNames: bindingifyAssetFilenames(assetFileNames),
1125
- entryFileNames,
1126
- chunkFileNames,
1127
- cssEntryFileNames,
1128
- cssChunkFileNames,
1129
- plugins: [],
1130
- minify: outputOptions.minify,
1131
- externalLiveBindings: outputOptions.externalLiveBindings,
1132
- inlineDynamicImports: outputOptions.inlineDynamicImports,
1133
- advancedChunks: outputOptions.advancedChunks,
1134
- polyfillRequire: outputOptions.polyfillRequire,
1135
- target: outputOptions.target,
1136
- sanitizeFileName
1137
- };
1138
- }
1139
- function bindingifyAddon(configAddon) {
1140
- return async (chunk) => {
1141
- if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
1142
- return configAddon || "";
1143
- };
1144
- }
1145
- function bindingifyFormat(format) {
1146
- switch (format) {
1147
- case void 0:
1148
- case "es":
1149
- case "esm":
1150
- case "module": return "es";
1151
- case "cjs":
1152
- case "commonjs": return "cjs";
1153
- case "iife": return "iife";
1154
- case "umd": return "umd";
1155
- case "experimental-app": return "app";
1156
- default: unimplemented(`output.format: ${format}`);
1157
- }
407
+ //#region src/utils/validator.ts
408
+ const StringOrRegExpSchema = v.union([v.string(), v.instance(RegExp)]);
409
+ const LogLevelSchema = v.union([
410
+ v.literal("debug"),
411
+ v.literal("info"),
412
+ v.literal("warn")
413
+ ]);
414
+ const LogLevelOptionSchema = v.union([LogLevelSchema, v.literal("silent")]);
415
+ const LogLevelWithErrorSchema = v.union([LogLevelSchema, v.literal("error")]);
416
+ const RollupLogSchema = v.any();
417
+ const RollupLogWithStringSchema = v.union([RollupLogSchema, v.string()]);
418
+ const InputOptionSchema = v.union([
419
+ v.string(),
420
+ v.array(v.string()),
421
+ v.record(v.string(), v.string())
422
+ ]);
423
+ const ExternalSchema = v.union([
424
+ StringOrRegExpSchema,
425
+ v.array(StringOrRegExpSchema),
426
+ v.pipe(v.function(), v.args(v.tuple([
427
+ v.string(),
428
+ v.optional(v.string()),
429
+ v.boolean()
430
+ ])), v.returns(v.nullish(v.boolean())))
431
+ ]);
432
+ const ModuleTypesSchema = v.record(v.string(), v.union([
433
+ v.literal("base64"),
434
+ v.literal("binary"),
435
+ v.literal("css"),
436
+ v.literal("dataurl"),
437
+ v.literal("empty"),
438
+ v.literal("js"),
439
+ v.literal("json"),
440
+ v.literal("jsx"),
441
+ v.literal("text"),
442
+ v.literal("ts"),
443
+ v.literal("tsx")
444
+ ]));
445
+ const JsxOptionsSchema = v.strictObject({
446
+ development: v.pipe(v.optional(v.boolean()), v.description("Development specific information")),
447
+ factory: v.pipe(v.optional(v.string()), v.description("Jsx element transformation")),
448
+ fragment: v.pipe(v.optional(v.string()), v.description("Jsx fragment transformation")),
449
+ importSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is classic")),
450
+ jsxImportSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is automatic")),
451
+ mode: v.pipe(v.optional(v.union([
452
+ v.literal("classic"),
453
+ v.literal("automatic"),
454
+ v.literal("preserve")
455
+ ])), v.description("Jsx transformation mode")),
456
+ refresh: v.pipe(v.optional(v.boolean()), v.description("React refresh transformation"))
457
+ });
458
+ const WatchOptionsSchema = v.strictObject({
459
+ chokidar: v.optional(v.never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)),
460
+ exclude: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
461
+ include: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
462
+ notify: v.pipe(v.optional(v.strictObject({
463
+ compareContents: v.optional(v.boolean()),
464
+ pollInterval: v.optional(v.number())
465
+ })), v.description("Notify options")),
466
+ skipWrite: v.pipe(v.optional(v.boolean()), v.description("Skip the bundle.write() step")),
467
+ buildDelay: v.pipe(v.optional(v.number()), v.description("Throttle watch rebuilds"))
468
+ });
469
+ const ChecksOptionsSchema = v.strictObject({ circularDependency: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warnings when detecting circular dependencies")) });
470
+ const MinifyOptionsSchema = v.strictObject({
471
+ mangle: v.boolean(),
472
+ compress: v.boolean(),
473
+ deadCodeElimination: v.boolean(),
474
+ removeWhitespace: v.boolean()
475
+ });
476
+ const ResolveOptionsSchema = v.strictObject({
477
+ alias: v.optional(v.record(v.string(), v.union([v.string(), v.array(v.string())]))),
478
+ aliasFields: v.optional(v.array(v.array(v.string()))),
479
+ conditionNames: v.optional(v.array(v.string())),
480
+ extensionAlias: v.optional(v.record(v.string(), v.array(v.string()))),
481
+ exportsFields: v.optional(v.array(v.array(v.string()))),
482
+ extensions: v.optional(v.array(v.string())),
483
+ mainFields: v.optional(v.array(v.string())),
484
+ mainFiles: v.optional(v.array(v.string())),
485
+ modules: v.optional(v.array(v.string())),
486
+ symlinks: v.optional(v.boolean()),
487
+ tsconfigFilename: v.optional(v.string())
488
+ });
489
+ const TreeshakingOptionsSchema = v.union([v.boolean(), v.looseObject({ annotations: v.optional(v.boolean()) })]);
490
+ const OnLogSchema = v.pipe(v.function(), v.args(v.tuple([
491
+ LogLevelSchema,
492
+ RollupLogSchema,
493
+ v.pipe(v.function(), v.args(v.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
494
+ ])));
495
+ const OnwarnSchema = v.pipe(v.function(), v.args(v.tuple([RollupLogSchema, v.pipe(v.function(), v.args(v.tuple([v.union([RollupLogWithStringSchema, v.pipe(v.function(), v.returns(RollupLogWithStringSchema))])])))])));
496
+ const InputOptionsSchema = v.strictObject({
497
+ input: v.optional(InputOptionSchema),
498
+ plugins: v.optional(v.custom(() => true)),
499
+ external: v.optional(ExternalSchema),
500
+ resolve: v.optional(ResolveOptionsSchema),
501
+ cwd: v.pipe(v.optional(v.string()), v.description("Current working directory")),
502
+ platform: v.pipe(v.optional(v.union([
503
+ v.literal("browser"),
504
+ v.literal("neutral"),
505
+ v.literal("node")
506
+ ])), v.description(`Platform for which the code should be generated (node, ${colors.underline("browser")}, neutral)`)),
507
+ shimMissingExports: v.pipe(v.optional(v.boolean()), v.description("Create shim variables for missing exports")),
508
+ treeshake: v.optional(TreeshakingOptionsSchema),
509
+ logLevel: v.pipe(v.optional(LogLevelOptionSchema), v.description(`Log level (${colors.dim("silent")}, ${colors.underline(colors.gray("info"))}, debug, ${colors.yellow("warn")})`)),
510
+ onLog: v.optional(OnLogSchema),
511
+ onwarn: v.optional(OnwarnSchema),
512
+ moduleTypes: v.pipe(v.optional(ModuleTypesSchema), v.description("Module types for customized extensions")),
513
+ experimental: v.optional(v.strictObject({
514
+ disableLiveBindings: v.optional(v.boolean()),
515
+ enableComposingJsPlugins: v.optional(v.boolean()),
516
+ resolveNewUrlToAsset: v.optional(v.boolean()),
517
+ strictExecutionOrder: v.optional(v.boolean()),
518
+ hmr: v.optional(v.boolean())
519
+ })),
520
+ define: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Define global variables")),
521
+ inject: v.optional(v.record(v.string(), v.union([v.string(), v.tuple([v.string(), v.string()])]))),
522
+ profilerNames: v.optional(v.boolean()),
523
+ jsx: v.optional(v.union([v.boolean(), JsxOptionsSchema])),
524
+ watch: v.optional(v.union([WatchOptionsSchema, v.literal(false)])),
525
+ dropLabels: v.pipe(v.optional(v.array(v.string())), v.description("Remove labeled statements with these label names")),
526
+ checks: v.optional(ChecksOptionsSchema),
527
+ keepNames: v.pipe(v.optional(v.boolean()), v.description("Keep function/class name"))
528
+ });
529
+ const InputCliOverrideSchema = v.strictObject({
530
+ external: v.pipe(v.optional(v.array(v.string())), v.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
531
+ inject: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Inject import statements on demand")),
532
+ treeshake: v.pipe(v.optional(v.boolean()), v.description("enable treeshaking")),
533
+ jsx: v.pipe(v.optional(JsxOptionsSchema), v.description("enable jsx"))
534
+ });
535
+ const InputCliOptionsSchema = v.omit(v.strictObject({
536
+ ...InputOptionsSchema.entries,
537
+ ...InputCliOverrideSchema.entries
538
+ }), [
539
+ "input",
540
+ "plugins",
541
+ "onwarn",
542
+ "onLog",
543
+ "resolve",
544
+ "experimental",
545
+ "profilerNames",
546
+ "watch"
547
+ ]);
548
+ var ESTarget = function(ESTarget$1) {
549
+ ESTarget$1["ES6"] = "es6";
550
+ ESTarget$1["ES2015"] = "es2015";
551
+ ESTarget$1["ES2016"] = "es2016";
552
+ ESTarget$1["ES2017"] = "es2017";
553
+ ESTarget$1["ES2018"] = "es2018";
554
+ ESTarget$1["ES2019"] = "es2019";
555
+ ESTarget$1["ES2020"] = "es2020";
556
+ ESTarget$1["ES2021"] = "es2021";
557
+ ESTarget$1["ES2022"] = "es2022";
558
+ ESTarget$1["ES2023"] = "es2023";
559
+ ESTarget$1["ES2024"] = "es2024";
560
+ ESTarget$1["ESNext"] = "esnext";
561
+ return ESTarget$1;
562
+ }(ESTarget || {});
563
+ const ModuleFormatSchema = v.union([
564
+ v.literal("es"),
565
+ v.literal("cjs"),
566
+ v.literal("esm"),
567
+ v.literal("module"),
568
+ v.literal("commonjs"),
569
+ v.literal("iife"),
570
+ v.literal("umd")
571
+ ]);
572
+ const AddonFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returnsAsync(v.unionAsync([v.string(), v.pipeAsync(v.promise(), v.awaitAsync(), v.string())])));
573
+ const ChunkFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
574
+ const AssetFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
575
+ const SanitizeFileNameSchema = v.union([v.boolean(), v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()))]);
576
+ const GlobalsFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()));
577
+ const AdvancedChunksSchema = v.strictObject({
578
+ minSize: v.optional(v.number()),
579
+ maxSize: v.optional(v.number()),
580
+ minModuleSize: v.optional(v.number()),
581
+ maxModuleSize: v.optional(v.number()),
582
+ minShareCount: v.optional(v.number()),
583
+ groups: v.optional(v.array(v.strictObject({
584
+ name: v.string(),
585
+ test: v.optional(v.union([v.string(), v.instance(RegExp)])),
586
+ priority: v.optional(v.number()),
587
+ minSize: v.optional(v.number()),
588
+ minShareCount: v.optional(v.number()),
589
+ maxSize: v.optional(v.number()),
590
+ minModuleSize: v.optional(v.number()),
591
+ maxModuleSize: v.optional(v.number())
592
+ })))
593
+ });
594
+ const OutputOptionsSchema = v.strictObject({
595
+ dir: v.pipe(v.optional(v.string()), v.description("Output directory, defaults to `dist` if `file` is not set")),
596
+ file: v.pipe(v.optional(v.string()), v.description("Single output file")),
597
+ exports: v.pipe(v.optional(v.union([
598
+ v.literal("auto"),
599
+ v.literal("named"),
600
+ v.literal("default"),
601
+ v.literal("none")
602
+ ])), v.description(`Specify a export mode (${colors.underline("auto")}, named, default, none)`)),
603
+ hashCharacters: v.pipe(v.optional(v.union([
604
+ v.literal("base64"),
605
+ v.literal("base36"),
606
+ v.literal("hex")
607
+ ])), v.description("Use the specified character set for file hashes")),
608
+ format: v.pipe(v.optional(ModuleFormatSchema), v.description(`Output format of the generated bundle (supports ${colors.underline("esm")}, cjs, and iife)`)),
609
+ sourcemap: v.pipe(v.optional(v.union([
610
+ v.boolean(),
611
+ v.literal("inline"),
612
+ v.literal("hidden")
613
+ ])), v.description(`Generate sourcemap (\`-s inline\` for inline, or ${colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
614
+ sourcemapDebugIds: v.pipe(v.optional(v.boolean()), v.description("Inject sourcemap debug IDs")),
615
+ sourcemapIgnoreList: v.optional(v.union([v.boolean(), v.custom(() => true)])),
616
+ sourcemapPathTransform: v.optional(v.custom(() => true)),
617
+ banner: v.optional(v.union([v.string(), AddonFunctionSchema])),
618
+ footer: v.optional(v.union([v.string(), AddonFunctionSchema])),
619
+ intro: v.optional(v.union([v.string(), AddonFunctionSchema])),
620
+ outro: v.optional(v.union([v.string(), AddonFunctionSchema])),
621
+ extend: v.pipe(v.optional(v.boolean()), v.description("Extend global variable defined by name in IIFE / UMD formats")),
622
+ esModule: v.optional(v.union([v.boolean(), v.literal("if-default-prop")])),
623
+ assetFileNames: v.optional(AssetFileNamesSchema),
624
+ entryFileNames: v.optional(ChunkFileNamesSchema),
625
+ chunkFileNames: v.optional(ChunkFileNamesSchema),
626
+ cssEntryFileNames: v.optional(ChunkFileNamesSchema),
627
+ cssChunkFileNames: v.optional(ChunkFileNamesSchema),
628
+ sanitizeFileName: v.optional(SanitizeFileNameSchema),
629
+ minify: v.pipe(v.optional(v.union([v.boolean(), MinifyOptionsSchema])), v.description("Minify the bundled file")),
630
+ name: v.pipe(v.optional(v.string()), v.description("Name for UMD / IIFE format outputs")),
631
+ globals: v.pipe(v.optional(v.union([v.record(v.string(), v.string()), GlobalsFunctionSchema])), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
632
+ externalLiveBindings: v.pipe(v.optional(v.boolean()), v.description("external live bindings")),
633
+ inlineDynamicImports: v.pipe(v.optional(v.boolean()), v.description("Inline dynamic imports")),
634
+ advancedChunks: v.optional(AdvancedChunksSchema),
635
+ comments: v.pipe(v.optional(v.union([v.literal("none"), v.literal("preserve-legal")])), v.description("Control comments in the output")),
636
+ target: v.pipe(v.optional(v.enum(ESTarget)), v.description("The JavaScript target environment")),
637
+ plugins: v.optional(v.custom(() => true))
638
+ });
639
+ const getAddonDescription = (placement, wrapper) => {
640
+ return `Code to insert the ${colors.bold(placement)} of the bundled file (${colors.bold(wrapper)} the wrapper function)`;
641
+ };
642
+ const OutputCliOverrideSchema = v.strictObject({
643
+ assetFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for asset files")),
644
+ entryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted entry chunks")),
645
+ chunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted secondary chunks")),
646
+ cssEntryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css entry chunks")),
647
+ cssChunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css secondary chunks")),
648
+ sanitizeFileName: v.pipe(v.optional(v.boolean()), v.description("Sanitize file name")),
649
+ banner: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "outside"))),
650
+ footer: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "outside"))),
651
+ intro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "inside"))),
652
+ outro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "inside"))),
653
+ esModule: v.pipe(v.optional(v.boolean()), v.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
654
+ globals: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
655
+ advancedChunks: v.pipe(v.optional(v.strictObject({
656
+ minSize: v.pipe(v.optional(v.number()), v.description("Minimum size of the chunk")),
657
+ minShareCount: v.pipe(v.optional(v.number()), v.description("Minimum share count of the chunk"))
658
+ })), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
659
+ minify: v.pipe(v.optional(v.boolean()), v.description("Minify the bundled file"))
660
+ });
661
+ const OutputCliOptionsSchema = v.omit(v.strictObject({
662
+ ...OutputOptionsSchema.entries,
663
+ ...OutputCliOverrideSchema.entries
664
+ }), [
665
+ "sourcemapIgnoreList",
666
+ "sourcemapPathTransform",
667
+ "plugins"
668
+ ]);
669
+ const CliOptionsSchema = v.strictObject({
670
+ config: v.pipe(v.optional(v.union([v.string(), v.boolean()])), v.description("Path to the config file (default: `rolldown.config.js`)")),
671
+ help: v.pipe(v.optional(v.boolean()), v.description("Show help")),
672
+ version: v.pipe(v.optional(v.boolean()), v.description("Show version number")),
673
+ watch: v.pipe(v.optional(v.boolean()), v.description("Watch files in bundle and rebuild on changes")),
674
+ ...InputCliOptionsSchema.entries,
675
+ ...OutputCliOptionsSchema.entries
676
+ });
677
+ function validateCliOptions(options) {
678
+ let parsed = v.safeParse(CliOptionsSchema, options);
679
+ return [parsed.output, parsed.issues?.map((issue) => issue.path?.join(", ")).filter((v$1) => v$1 !== void 0)];
1158
680
  }
1159
- function bindingifySourcemap(sourcemap) {
1160
- switch (sourcemap) {
1161
- case true: return "file";
1162
- case "inline": return "inline";
1163
- case false:
1164
- case void 0: return void 0;
1165
- case "hidden": return "hidden";
1166
- default: throw new Error(`unknown sourcemap: ${sourcemap}`);
681
+ const inputHelperMsgRecord = { output: { ignored: true } };
682
+ const outputHelperMsgRecord = {};
683
+ function validateOption(key, options) {
684
+ if (process.env.ROLLDOWN_OPTIONS_VALIDATION === "loose") return;
685
+ let parsed = v.safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options);
686
+ if (!parsed.success) {
687
+ const errors = parsed.issues.map((issue) => {
688
+ const issuePaths = issue.path.map((path$1) => path$1.key);
689
+ let issueMsg = issue.message;
690
+ if (issue.type === "union") {
691
+ const subIssue = issue.issues?.find((i) => !(i.type !== issue.received && i.input === issue.input));
692
+ if (subIssue) {
693
+ if (subIssue.path) issuePaths.push(subIssue.path.map((path$1) => path$1.key));
694
+ issueMsg = subIssue.message;
695
+ }
696
+ }
697
+ const stringPath = issuePaths.join(".");
698
+ const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath];
699
+ if (helper && helper.ignored) return "";
700
+ return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`;
701
+ }).filter(Boolean);
702
+ if (errors.length) throw new Error(`Failed validate ${key} options.\n` + errors.join("\n"));
1167
703
  }
1168
704
  }
1169
- function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
1170
- return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
1171
- }
1172
- function bindingifyAssetFilenames(assetFileNames) {
1173
- if (typeof assetFileNames === "function") return (asset) => {
1174
- return assetFileNames({
1175
- names: asset.names,
1176
- originalFileNames: asset.originalFileNames,
1177
- source: transformAssetSource(asset.source),
1178
- type: "asset"
1179
- });
1180
- };
1181
- return assetFileNames;
705
+ function getInputCliKeys() {
706
+ return v.keyof(InputCliOptionsSchema).options;
1182
707
  }
1183
-
1184
- //#endregion
1185
- //#region src/options/normalized-output-options.ts
1186
- var NormalizedOutputOptionsImpl = class {
1187
- constructor(inner, outputOptions, normalizedOutputPlugins) {
1188
- this.inner = inner;
1189
- this.outputOptions = outputOptions;
1190
- this.normalizedOutputPlugins = normalizedOutputPlugins;
1191
- }
1192
- get dir() {
1193
- return this.inner.dir ?? void 0;
1194
- }
1195
- get entryFileNames() {
1196
- return this.inner.entryFilenames || this.outputOptions.entryFileNames;
1197
- }
1198
- get chunkFileNames() {
1199
- return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
1200
- }
1201
- get assetFileNames() {
1202
- return this.inner.assetFilenames || this.outputOptions.assetFileNames;
1203
- }
1204
- get format() {
1205
- return this.inner.format;
1206
- }
1207
- get exports() {
1208
- return this.inner.exports;
1209
- }
1210
- get sourcemap() {
1211
- return this.inner.sourcemap;
1212
- }
1213
- get cssEntryFileNames() {
1214
- return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
1215
- }
1216
- get cssChunkFileNames() {
1217
- return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
1218
- }
1219
- get shimMissingExports() {
1220
- return this.inner.shimMissingExports;
1221
- }
1222
- get name() {
1223
- return this.inner.name ?? void 0;
1224
- }
1225
- get file() {
1226
- return this.inner.file ?? void 0;
1227
- }
1228
- get inlineDynamicImports() {
1229
- return this.inner.inlineDynamicImports;
1230
- }
1231
- get externalLiveBindings() {
1232
- return this.inner.externalLiveBindings;
1233
- }
1234
- get banner() {
1235
- return normalizeAddon(this.outputOptions.banner);
1236
- }
1237
- get footer() {
1238
- return normalizeAddon(this.outputOptions.footer);
1239
- }
1240
- get intro() {
1241
- return normalizeAddon(this.outputOptions.intro);
1242
- }
1243
- get outro() {
1244
- return normalizeAddon(this.outputOptions.outro);
1245
- }
1246
- get esModule() {
1247
- return this.inner.esModule;
1248
- }
1249
- get extend() {
1250
- return this.inner.extend;
1251
- }
1252
- get globals() {
1253
- return this.inner.globals || this.outputOptions.globals;
1254
- }
1255
- get hashCharacters() {
1256
- return this.inner.hashCharacters;
1257
- }
1258
- get sourcemapDebugIds() {
1259
- return this.inner.sourcemapDebugIds;
1260
- }
1261
- get sourcemapIgnoreList() {
1262
- return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
1263
- }
1264
- get sourcemapPathTransform() {
1265
- return this.outputOptions.sourcemapPathTransform;
1266
- }
1267
- get minify() {
1268
- return this.inner.minify;
1269
- }
1270
- get comments() {
1271
- return this.inner.comments;
1272
- }
1273
- get polyfillRequire() {
1274
- return this.inner.polyfillRequire;
708
+ function getOutputCliKeys() {
709
+ return v.keyof(OutputCliOptionsSchema).options;
710
+ }
711
+ function getJsonSchema() {
712
+ return toJsonSchema(CliOptionsSchema);
713
+ }
714
+
715
+ //#endregion
716
+ //#region src/utils/asset-source.ts
717
+ function transformAssetSource(bindingAssetSource$1) {
718
+ return bindingAssetSource$1.inner;
719
+ }
720
+ function bindingAssetSource(source) {
721
+ return { inner: source };
722
+ }
723
+
724
+ //#endregion
725
+ //#region src/types/sourcemap.ts
726
+ function bindingifySourcemap$1(map) {
727
+ if (map == null) return;
728
+ return { inner: typeof map === "string" ? map : {
729
+ file: map.file ?? void 0,
730
+ mappings: map.mappings,
731
+ sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
732
+ sources: map.sources?.map((s) => s ?? void 0),
733
+ sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
734
+ names: map.names,
735
+ x_google_ignoreList: map.x_google_ignoreList,
736
+ debugId: "debugId" in map ? map.debugId : void 0
737
+ } };
738
+ }
739
+
740
+ //#endregion
741
+ //#region src/utils/error.ts
742
+ function normalizeErrors(rawErrors) {
743
+ const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
744
+ kind: e.kind,
745
+ message: e.message,
746
+ stack: void 0
747
+ }));
748
+ let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
749
+ for (let i = 0; i < errors.length; i++) {
750
+ if (i >= 5) {
751
+ summary += "\n...";
752
+ break;
753
+ }
754
+ summary += getErrorMessage(errors[i]) + "\n";
1275
755
  }
1276
- get plugins() {
1277
- return this.normalizedOutputPlugins;
756
+ const wrapper = new Error(summary);
757
+ Object.defineProperty(wrapper, "errors", {
758
+ configurable: true,
759
+ enumerable: true,
760
+ get: () => errors,
761
+ set: (value) => Object.defineProperty(wrapper, "errors", {
762
+ configurable: true,
763
+ enumerable: true,
764
+ value
765
+ })
766
+ });
767
+ return wrapper;
768
+ }
769
+ function getErrorMessage(e) {
770
+ let s = "";
771
+ if (e.plugin) s += `[plugin ${e.plugin}]`;
772
+ const id = e.id ?? e.loc?.file;
773
+ if (id) {
774
+ s += " " + id;
775
+ if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
1278
776
  }
1279
- };
1280
- function normalizeAddon(value) {
1281
- if (typeof value === "function") return value;
1282
- return () => value || "";
777
+ if (s) s += "\n";
778
+ const message = `${e.name ?? "Error"}: ${e.message}`;
779
+ s += message;
780
+ if (e.frame) s = joinNewLine(s, e.frame);
781
+ if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
782
+ return s;
783
+ }
784
+ function joinNewLine(s1, s2) {
785
+ return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
1283
786
  }
1284
787
 
1285
788
  //#endregion
1286
- //#region src/plugin/bindingify-output-hooks.ts
1287
- function bindingifyRenderStart(args) {
1288
- const hook = args.plugin.renderStart;
1289
- if (!hook) return {};
1290
- const { handler, meta } = normalizeHook(hook);
789
+ //#region src/utils/transform-rendered-module.ts
790
+ function transformToRenderedModule(bindingRenderedModule) {
1291
791
  return {
1292
- plugin: async (ctx, opts) => {
1293
- handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args.onLog));
792
+ get code() {
793
+ return bindingRenderedModule.code;
1294
794
  },
1295
- meta: bindingifyPluginHookMeta(meta)
1296
- };
1297
- }
1298
- function bindingifyRenderChunk(args) {
1299
- const hook = args.plugin.renderChunk;
1300
- if (!hook) return {};
1301
- const { handler, meta } = normalizeHook(hook);
1302
- return {
1303
- plugin: async (ctx, code, chunk, opts) => {
1304
- const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), code, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins));
1305
- if (ret == null) return;
1306
- if (typeof ret === "string") return { code: ret };
1307
- if (!ret.map) return { code: ret.code };
1308
- return {
1309
- code: ret.code,
1310
- map: bindingifySourcemap$1(ret.map)
1311
- };
795
+ get renderedLength() {
796
+ return bindingRenderedModule.code?.length || 0;
1312
797
  },
1313
- meta: bindingifyPluginHookMeta(meta)
798
+ get renderedExports() {
799
+ return bindingRenderedModule.renderedExports;
800
+ }
1314
801
  };
1315
802
  }
1316
- function bindingifyAugmentChunkHash(args) {
1317
- const hook = args.plugin.augmentChunkHash;
1318
- if (!hook) return {};
1319
- const { handler, meta } = normalizeHook(hook);
803
+
804
+ //#endregion
805
+ //#region src/utils/transform-rendered-chunk.ts
806
+ function transformRenderedChunk(chunk) {
1320
807
  return {
1321
- plugin: async (ctx, chunk) => {
1322
- return await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
808
+ get name() {
809
+ return chunk.name;
1323
810
  },
1324
- meta: bindingifyPluginHookMeta(meta)
1325
- };
1326
- }
1327
- function bindingifyRenderError(args) {
1328
- const hook = args.plugin.renderError;
1329
- if (!hook) return {};
1330
- const { handler, meta } = normalizeHook(hook);
1331
- return {
1332
- plugin: async (ctx, err) => {
1333
- handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), normalizeErrors(err));
811
+ get isEntry() {
812
+ return chunk.isEntry;
1334
813
  },
1335
- meta: bindingifyPluginHookMeta(meta)
1336
- };
1337
- }
1338
- function bindingifyGenerateBundle(args) {
1339
- const hook = args.plugin.generateBundle;
1340
- if (!hook) return {};
1341
- const { handler, meta } = normalizeHook(hook);
1342
- return {
1343
- plugin: async (ctx, bundle, isWrite, opts) => {
1344
- const changed = {
1345
- updated: new Set(),
1346
- deleted: new Set()
1347
- };
1348
- const output = transformToOutputBundle(bundle, changed);
1349
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output, isWrite);
1350
- return collectChangedBundle(changed, output);
814
+ get isDynamicEntry() {
815
+ return chunk.isDynamicEntry;
1351
816
  },
1352
- meta: bindingifyPluginHookMeta(meta)
1353
- };
1354
- }
1355
- function bindingifyWriteBundle(args) {
1356
- const hook = args.plugin.writeBundle;
1357
- if (!hook) return {};
1358
- const { handler, meta } = normalizeHook(hook);
1359
- return {
1360
- plugin: async (ctx, bundle, opts) => {
1361
- const changed = {
1362
- updated: new Set(),
1363
- deleted: new Set()
1364
- };
1365
- const output = transformToOutputBundle(bundle, changed);
1366
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output);
1367
- return collectChangedBundle(changed, output);
817
+ get facadeModuleId() {
818
+ return chunk.facadeModuleId;
1368
819
  },
1369
- meta: bindingifyPluginHookMeta(meta)
820
+ get moduleIds() {
821
+ return chunk.moduleIds;
822
+ },
823
+ get exports() {
824
+ return chunk.exports;
825
+ },
826
+ get fileName() {
827
+ return chunk.fileName;
828
+ },
829
+ get imports() {
830
+ return chunk.imports;
831
+ },
832
+ get dynamicImports() {
833
+ return chunk.dynamicImports;
834
+ },
835
+ get modules() {
836
+ return transformChunkModules(chunk.modules);
837
+ }
1370
838
  };
1371
839
  }
1372
- function bindingifyCloseBundle(args) {
1373
- const hook = args.plugin.closeBundle;
1374
- if (!hook) return {};
1375
- const { handler, meta } = normalizeHook(hook);
1376
- return {
1377
- plugin: async (ctx) => {
1378
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
840
+ function transformChunkModules(modules) {
841
+ const result = {};
842
+ for (let i = 0; i < modules.values.length; i++) {
843
+ let key = modules.keys[i];
844
+ const mod = modules.values[i];
845
+ result[key] = transformToRenderedModule(mod);
846
+ }
847
+ return result;
848
+ }
849
+
850
+ //#endregion
851
+ //#region src/utils/transform-to-rollup-output.ts
852
+ function transformToRollupSourceMap(map) {
853
+ const parsed = JSON.parse(map);
854
+ const obj = {
855
+ ...parsed,
856
+ toString() {
857
+ return JSON.stringify(obj);
1379
858
  },
1380
- meta: bindingifyPluginHookMeta(meta)
859
+ toUrl() {
860
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
861
+ }
1381
862
  };
863
+ return obj;
1382
864
  }
1383
- function bindingifyBanner(args) {
1384
- const hook = args.plugin.banner;
1385
- if (!hook) return {};
1386
- const { handler, meta } = normalizeHook(hook);
1387
- return {
1388
- plugin: async (ctx, chunk) => {
1389
- if (typeof handler === "string") return handler;
1390
- return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
865
+ function transformToRollupOutputChunk(bindingChunk, changed) {
866
+ const chunk = {
867
+ type: "chunk",
868
+ get code() {
869
+ return bindingChunk.code;
870
+ },
871
+ fileName: bindingChunk.fileName,
872
+ name: bindingChunk.name,
873
+ get modules() {
874
+ return transformChunkModules(bindingChunk.modules);
875
+ },
876
+ get imports() {
877
+ return bindingChunk.imports;
878
+ },
879
+ get dynamicImports() {
880
+ return bindingChunk.dynamicImports;
881
+ },
882
+ exports: bindingChunk.exports,
883
+ isEntry: bindingChunk.isEntry,
884
+ facadeModuleId: bindingChunk.facadeModuleId || null,
885
+ isDynamicEntry: bindingChunk.isDynamicEntry,
886
+ get moduleIds() {
887
+ return bindingChunk.moduleIds;
1391
888
  },
1392
- meta: bindingifyPluginHookMeta(meta)
1393
- };
1394
- }
1395
- function bindingifyFooter(args) {
1396
- const hook = args.plugin.footer;
1397
- if (!hook) return {};
1398
- const { handler, meta } = normalizeHook(hook);
1399
- return {
1400
- plugin: async (ctx, chunk) => {
1401
- if (typeof handler === "string") return handler;
1402
- return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
889
+ get map() {
890
+ return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
1403
891
  },
1404
- meta: bindingifyPluginHookMeta(meta)
892
+ sourcemapFileName: bindingChunk.sourcemapFileName || null,
893
+ preliminaryFileName: bindingChunk.preliminaryFileName
1405
894
  };
1406
- }
1407
- function bindingifyIntro(args) {
1408
- const hook = args.plugin.intro;
1409
- if (!hook) return {};
1410
- const { handler, meta } = normalizeHook(hook);
1411
- return {
1412
- plugin: async (ctx, chunk) => {
1413
- if (typeof handler === "string") return handler;
1414
- return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
895
+ const cache = {};
896
+ return new Proxy(chunk, {
897
+ get(target, p) {
898
+ if (p in cache) return cache[p];
899
+ return target[p];
1415
900
  },
1416
- meta: bindingifyPluginHookMeta(meta)
1417
- };
1418
- }
1419
- function bindingifyOutro(args) {
1420
- const hook = args.plugin.outro;
1421
- if (!hook) return {};
1422
- const { handler, meta } = normalizeHook(hook);
1423
- return {
1424
- plugin: async (ctx, chunk) => {
1425
- if (typeof handler === "string") return handler;
1426
- return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
901
+ set(target, p, newValue) {
902
+ cache[p] = newValue;
903
+ changed?.updated.add(bindingChunk.fileName);
904
+ return true;
1427
905
  },
1428
- meta: bindingifyPluginHookMeta(meta)
1429
- };
906
+ has(target, p) {
907
+ if (p in cache) return true;
908
+ return p in target;
909
+ }
910
+ });
1430
911
  }
1431
-
1432
- //#endregion
1433
- //#region src/plugin/bindingify-watch-hooks.ts
1434
- function bindingifyWatchChange(args) {
1435
- const hook = args.plugin.watchChange;
1436
- if (!hook) return {};
1437
- const { handler, meta } = normalizeHook(hook);
1438
- return {
1439
- plugin: async (ctx, id, event) => {
1440
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), id, { event });
912
+ function transformToRollupOutputAsset(bindingAsset, changed) {
913
+ const asset = {
914
+ type: "asset",
915
+ fileName: bindingAsset.fileName,
916
+ originalFileName: bindingAsset.originalFileName || null,
917
+ originalFileNames: bindingAsset.originalFileNames,
918
+ get source() {
919
+ return transformAssetSource(bindingAsset.source);
1441
920
  },
1442
- meta: bindingifyPluginHookMeta(meta)
921
+ name: bindingAsset.name ?? void 0,
922
+ names: bindingAsset.names
1443
923
  };
924
+ const cache = {};
925
+ return new Proxy(asset, {
926
+ get(target, p) {
927
+ if (p in cache) return cache[p];
928
+ return target[p];
929
+ },
930
+ set(target, p, newValue) {
931
+ cache[p] = newValue;
932
+ changed?.updated.add(bindingAsset.fileName);
933
+ return true;
934
+ }
935
+ });
1444
936
  }
1445
- function bindingifyCloseWatcher(args) {
1446
- const hook = args.plugin.closeWatcher;
1447
- if (!hook) return {};
1448
- const { handler, meta } = normalizeHook(hook);
937
+ function transformToRollupOutput(output, changed) {
938
+ handleOutputErrors(output);
939
+ const { chunks, assets } = output;
940
+ return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
941
+ }
942
+ function handleOutputErrors(output) {
943
+ const rawErrors = output.errors;
944
+ if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
945
+ }
946
+ function transformToOutputBundle(output, changed) {
947
+ const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
948
+ return new Proxy(bundle, { deleteProperty(target, property) {
949
+ if (typeof property === "string") changed.deleted.add(property);
950
+ return true;
951
+ } });
952
+ }
953
+ function collectChangedBundle(changed, bundle) {
954
+ const assets = [];
955
+ const chunks = [];
956
+ for (const key in bundle) {
957
+ if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
958
+ const item = bundle[key];
959
+ if (item.type === "asset") assets.push({
960
+ filename: item.fileName,
961
+ originalFileNames: item.originalFileNames,
962
+ source: bindingAssetSource(item.source),
963
+ names: item.names
964
+ });
965
+ else chunks.push({
966
+ code: item.code,
967
+ filename: item.fileName,
968
+ name: item.name,
969
+ isEntry: item.isEntry,
970
+ exports: item.exports,
971
+ modules: {},
972
+ imports: item.imports,
973
+ dynamicImports: item.dynamicImports,
974
+ facadeModuleId: item.facadeModuleId || void 0,
975
+ isDynamicEntry: item.isDynamicEntry,
976
+ moduleIds: item.moduleIds,
977
+ map: bindingifySourcemap$1(item.map),
978
+ sourcemapFilename: item.sourcemapFileName || void 0,
979
+ preliminaryFilename: item.preliminaryFileName
980
+ });
981
+ }
1449
982
  return {
1450
- plugin: async (ctx) => {
1451
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
1452
- },
1453
- meta: bindingifyPluginHookMeta(meta)
983
+ assets,
984
+ chunks,
985
+ deleted: Array.from(changed.deleted)
1454
986
  };
1455
987
  }
1456
988
 
1457
989
  //#endregion
1458
- //#region src/plugin/bindingify-plugin.ts
1459
- function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel) {
1460
- const args = {
1461
- plugin,
1462
- options,
1463
- outputOptions,
1464
- pluginContextData,
1465
- onLog,
1466
- logLevel,
1467
- normalizedOutputPlugins
1468
- };
1469
- const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
1470
- const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
1471
- const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
1472
- const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
1473
- const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
1474
- const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
1475
- const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
1476
- const { plugin: renderChunk, meta: renderChunkMeta } = bindingifyRenderChunk(args);
1477
- const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
1478
- const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
1479
- const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
1480
- const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
1481
- const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
1482
- const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
1483
- const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args);
1484
- const { plugin: footer, meta: footerMeta } = bindingifyFooter(args);
1485
- const { plugin: intro, meta: introMeta } = bindingifyIntro(args);
1486
- const { plugin: outro, meta: outroMeta } = bindingifyOutro(args);
1487
- const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
1488
- const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
1489
- const result = {
1490
- name: plugin.name,
1491
- buildStart,
1492
- buildStartMeta,
1493
- resolveId,
1494
- resolveIdMeta,
1495
- resolveIdFilter,
1496
- resolveDynamicImport,
1497
- resolveDynamicImportMeta,
1498
- buildEnd,
1499
- buildEndMeta,
1500
- transform,
1501
- transformMeta,
1502
- transformFilter,
1503
- moduleParsed,
1504
- moduleParsedMeta,
1505
- load,
1506
- loadMeta,
1507
- loadFilter,
1508
- renderChunk,
1509
- renderChunkMeta,
1510
- augmentChunkHash,
1511
- augmentChunkHashMeta,
1512
- renderStart,
1513
- renderStartMeta,
1514
- renderError,
1515
- renderErrorMeta,
1516
- generateBundle,
1517
- generateBundleMeta,
1518
- writeBundle,
1519
- writeBundleMeta,
1520
- closeBundle,
1521
- closeBundleMeta,
1522
- banner,
1523
- bannerMeta,
1524
- footer,
1525
- footerMeta,
1526
- intro,
1527
- introMeta,
1528
- outro,
1529
- outroMeta,
1530
- watchChange,
1531
- watchChangeMeta,
1532
- closeWatcher,
1533
- closeWatcherMeta
1534
- };
1535
- return wrapHandlers(result);
1536
- }
1537
- function wrapHandlers(plugin) {
1538
- for (const hookName of [
1539
- "buildStart",
1540
- "resolveId",
1541
- "resolveDynamicImport",
1542
- "buildEnd",
1543
- "transform",
1544
- "moduleParsed",
1545
- "load",
1546
- "renderChunk",
1547
- "augmentChunkHash",
1548
- "renderStart",
1549
- "renderError",
1550
- "generateBundle",
1551
- "writeBundle",
1552
- "closeBundle",
1553
- "banner",
1554
- "footer",
1555
- "intro",
1556
- "outro",
1557
- "watchChange",
1558
- "closeWatcher"
1559
- ]) {
1560
- const handler = plugin[hookName];
1561
- if (handler) plugin[hookName] = async (...args) => {
1562
- try {
1563
- return await handler(...args);
1564
- } catch (e) {
1565
- return error(logPluginError(e, plugin.name, {
1566
- hook: hookName,
1567
- id: hookName === "transform" ? args[2] : void 0
1568
- }));
1569
- }
990
+ //#region src/utils/transform-sourcemap.ts
991
+ function isEmptySourcemapFiled(array) {
992
+ if (!array) return true;
993
+ if (array.length === 0 || !array[0]) return true;
994
+ return false;
995
+ }
996
+ function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
997
+ if (!rawMap) return;
998
+ let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
999
+ if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
1000
+ if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
1001
+ return map;
1002
+ }
1003
+
1004
+ //#endregion
1005
+ //#region src/utils/transform-module-info.ts
1006
+ function transformModuleInfo(info, option) {
1007
+ return {
1008
+ get ast() {
1009
+ return unsupported("ModuleInfo#ast");
1010
+ },
1011
+ get code() {
1012
+ return info.code;
1013
+ },
1014
+ id: info.id,
1015
+ importers: info.importers,
1016
+ dynamicImporters: info.dynamicImporters,
1017
+ importedIds: info.importedIds,
1018
+ dynamicallyImportedIds: info.dynamicallyImportedIds,
1019
+ exports: info.exports,
1020
+ isEntry: info.isEntry,
1021
+ ...option
1022
+ };
1023
+ }
1024
+
1025
+ //#endregion
1026
+ //#region src/plugin/minimal-plugin-context.ts
1027
+ var MinimalPluginContext = class {
1028
+ info;
1029
+ warn;
1030
+ debug;
1031
+ meta;
1032
+ constructor(onLog, logLevel, pluginName) {
1033
+ this.pluginName = pluginName;
1034
+ this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
1035
+ this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
1036
+ this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
1037
+ this.meta = {
1038
+ rollupVersion: "4.23.0",
1039
+ rolldownVersion: VERSION,
1040
+ watchMode: false
1570
1041
  };
1571
1042
  }
1572
- return plugin;
1043
+ error(e) {
1044
+ return error(logPluginError(normalizeLog(e), this.pluginName));
1045
+ }
1046
+ };
1047
+
1048
+ //#endregion
1049
+ //#region src/utils/transform-side-effects.ts
1050
+ function bindingifySideEffects(sideEffects) {
1051
+ switch (sideEffects) {
1052
+ case true: return import_binding.BindingHookSideEffects.True;
1053
+ case false: return import_binding.BindingHookSideEffects.False;
1054
+ case "no-treeshake": return import_binding.BindingHookSideEffects.NoTreeshake;
1055
+ case null:
1056
+ case void 0: return void 0;
1057
+ default: throw new Error(`Unexpected side effects: ${sideEffects}`);
1058
+ }
1573
1059
  }
1574
1060
 
1575
1061
  //#endregion
1576
- //#region src/plugin/plugin-context-data.ts
1577
- var PluginContextData = class {
1578
- moduleOptionMap = new Map();
1579
- resolveOptionsMap = new Map();
1580
- loadModulePromiseMap = new Map();
1581
- updateModuleOption(id, option) {
1582
- const existing = this.moduleOptionMap.get(id);
1583
- if (existing) {
1584
- if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
1585
- if (option.meta != null) Object.assign(existing.meta, option.meta);
1586
- if (option.invalidate != null) existing.invalidate = option.invalidate;
1587
- } else {
1588
- this.moduleOptionMap.set(id, option);
1589
- return option;
1590
- }
1591
- return existing;
1062
+ //#region src/plugin/plugin-context.ts
1063
+ var PluginContext = class extends MinimalPluginContext {
1064
+ getModuleInfo;
1065
+ constructor(outputOptions, context, plugin, data, onLog, logLevel, currentLoadingModule) {
1066
+ super(onLog, logLevel, plugin.name);
1067
+ this.outputOptions = outputOptions;
1068
+ this.context = context;
1069
+ this.data = data;
1070
+ this.onLog = onLog;
1071
+ this.currentLoadingModule = currentLoadingModule;
1072
+ this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
1592
1073
  }
1593
- getModuleOption(id) {
1594
- const option = this.moduleOptionMap.get(id);
1595
- if (!option) {
1596
- const raw = {
1597
- moduleSideEffects: null,
1598
- meta: {}
1599
- };
1600
- this.moduleOptionMap.set(id, raw);
1601
- return raw;
1074
+ async load(options) {
1075
+ const id = options.id;
1076
+ if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, logCycleLoading(this.pluginName, this.currentLoadingModule));
1077
+ const moduleInfo = this.data.getModuleInfo(id, this.context);
1078
+ if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
1079
+ const rawOptions = {
1080
+ meta: options.meta || {},
1081
+ moduleSideEffects: options.moduleSideEffects || null,
1082
+ invalidate: false
1083
+ };
1084
+ this.data.updateModuleOption(id, rawOptions);
1085
+ async function createLoadModulePromise(context, data) {
1086
+ const loadPromise = data.loadModulePromiseMap.get(id);
1087
+ if (loadPromise) return loadPromise;
1088
+ let resolveFn;
1089
+ const promise = new Promise((resolve, _) => {
1090
+ resolveFn = resolve;
1091
+ });
1092
+ data.loadModulePromiseMap.set(id, promise);
1093
+ try {
1094
+ await context.load(id, bindingifySideEffects(options.moduleSideEffects), resolveFn);
1095
+ } finally {
1096
+ data.loadModulePromiseMap.delete(id);
1097
+ }
1098
+ return promise;
1602
1099
  }
1603
- return option;
1100
+ await createLoadModulePromise(this.context, this.data);
1101
+ return this.data.getModuleInfo(id, this.context);
1604
1102
  }
1605
- getModuleInfo(id, context) {
1606
- const bindingInfo = context.getModuleInfo(id);
1607
- if (bindingInfo) {
1608
- const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
1609
- return this.proxyModuleInfo(id, info);
1610
- }
1611
- return null;
1103
+ async resolve(source, importer, options) {
1104
+ let receipt = void 0;
1105
+ if (options != null) receipt = this.data.saveResolveOptions(options);
1106
+ const res = await this.context.resolve(source, importer, {
1107
+ custom: receipt,
1108
+ skipSelf: options?.skipSelf
1109
+ });
1110
+ if (receipt != null) this.data.removeSavedResolveOptions(receipt);
1111
+ if (res == null) return null;
1112
+ const info = this.data.getModuleOption(res.id) || {};
1113
+ return {
1114
+ ...res,
1115
+ ...info
1116
+ };
1612
1117
  }
1613
- proxyModuleInfo(id, info) {
1614
- let moduleSideEffects = info.moduleSideEffects;
1615
- Object.defineProperty(info, "moduleSideEffects", {
1616
- get() {
1617
- return moduleSideEffects;
1618
- },
1619
- set: (v$1) => {
1620
- this.updateModuleOption(id, {
1621
- moduleSideEffects: v$1,
1622
- meta: info.meta,
1623
- invalidate: true
1624
- });
1625
- moduleSideEffects = v$1;
1626
- }
1118
+ emitFile = (file) => {
1119
+ if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
1120
+ if (file.type === "chunk") return this.context.emitChunk(file);
1121
+ const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
1122
+ const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
1123
+ return this.context.emitFile({
1124
+ ...file,
1125
+ originalFileName: file.originalFileName || void 0,
1126
+ source: bindingAssetSource(file.source)
1127
+ }, filename, fnSanitizedFileName);
1128
+ };
1129
+ getAssetFileNames(file) {
1130
+ if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
1131
+ names: file.name ? [file.name] : [],
1132
+ originalFileNames: file.originalFileName ? [file.originalFileName] : [],
1133
+ source: file.source,
1134
+ type: "asset"
1627
1135
  });
1628
- return info;
1629
1136
  }
1630
- getModuleIds(context) {
1631
- const moduleIds = context.getModuleIds();
1632
- return moduleIds.values();
1137
+ getFileName(referenceId) {
1138
+ return this.context.getFileName(referenceId);
1139
+ }
1140
+ getModuleIds() {
1141
+ return this.data.getModuleIds(this.context);
1142
+ }
1143
+ addWatchFile(id) {
1144
+ this.context.addWatchFile(id);
1145
+ }
1146
+ parse(input, options) {
1147
+ return parseAst(input, options);
1148
+ }
1149
+ };
1150
+
1151
+ //#endregion
1152
+ //#region src/plugin/transform-plugin-context.ts
1153
+ var TransformPluginContext = class extends PluginContext {
1154
+ constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption) {
1155
+ super(outputOptions, context, plugin, data, onLog, LogLevelOption, moduleId);
1156
+ this.inner = inner;
1157
+ this.moduleId = moduleId;
1158
+ this.moduleSource = moduleSource;
1159
+ const getLogHandler$1 = (handler) => (log, pos) => {
1160
+ log = normalizeLog(log);
1161
+ if (pos) augmentCodeLocation(log, pos, moduleSource, moduleId);
1162
+ log.id = moduleId;
1163
+ log.hook = "transform";
1164
+ handler(log);
1165
+ };
1166
+ this.debug = getLogHandler$1(this.debug);
1167
+ this.warn = getLogHandler$1(this.warn);
1168
+ this.info = getLogHandler$1(this.info);
1169
+ }
1170
+ error(e, pos) {
1171
+ if (typeof e === "string") e = { message: e };
1172
+ if (pos) augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
1173
+ e.id = this.moduleId;
1174
+ e.hook = "transform";
1175
+ return error(logPluginError(normalizeLog(e), this.pluginName));
1176
+ }
1177
+ getCombinedSourcemap() {
1178
+ return JSON.parse(this.inner.getCombinedSourcemap());
1179
+ }
1180
+ };
1181
+
1182
+ //#endregion
1183
+ //#region src/plugin/bindingify-plugin-hook-meta.ts
1184
+ function bindingifyPluginHookMeta(options) {
1185
+ return { order: bindingPluginOrder(options.order) };
1186
+ }
1187
+ function bindingPluginOrder(order) {
1188
+ switch (order) {
1189
+ case "post": return import_binding.BindingPluginOrder.Post;
1190
+ case "pre": return import_binding.BindingPluginOrder.Pre;
1191
+ case null:
1192
+ case void 0: return void 0;
1193
+ default: throw new Error(`Unknown plugin order: ${order}`);
1194
+ }
1195
+ }
1196
+
1197
+ //#endregion
1198
+ //#region src/constants/plugin-context.ts
1199
+ const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
1200
+
1201
+ //#endregion
1202
+ //#region src/plugin/bindingify-hook-filter.ts
1203
+ function bindingifyStringFilter(matcher) {
1204
+ if (typeof matcher === "string" || matcher instanceof RegExp) return { include: [matcher] };
1205
+ if (Array.isArray(matcher)) return { include: matcher };
1206
+ return {
1207
+ include: matcher.include ? arraify(matcher.include) : void 0,
1208
+ exclude: matcher.exclude ? arraify(matcher.exclude) : void 0
1209
+ };
1210
+ }
1211
+ function bindingifyResolveIdFilter(filterOption) {
1212
+ return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
1213
+ }
1214
+ function bindingifyLoadFilter(filterOption) {
1215
+ return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
1216
+ }
1217
+ function bindingifyTransformFilter(filterOption) {
1218
+ if (!filterOption) return void 0;
1219
+ const { id, code, moduleType } = filterOption;
1220
+ let moduleTypeRet;
1221
+ if (moduleType) if (Array.isArray(moduleType)) moduleTypeRet = moduleType;
1222
+ else moduleTypeRet = moduleType.include;
1223
+ return {
1224
+ id: id ? bindingifyStringFilter(id) : void 0,
1225
+ code: code ? bindingifyStringFilter(code) : void 0,
1226
+ moduleType: moduleTypeRet
1227
+ };
1228
+ }
1229
+
1230
+ //#endregion
1231
+ //#region src/options/normalized-input-options.ts
1232
+ var NormalizedInputOptionsImpl = class {
1233
+ inner;
1234
+ constructor(inner, onLog) {
1235
+ this.onLog = onLog;
1236
+ this.inner = inner;
1237
+ }
1238
+ get shimMissingExports() {
1239
+ return this.inner.shimMissingExports;
1633
1240
  }
1634
- saveResolveOptions(options) {
1635
- const index = this.resolveOptionsMap.size;
1636
- this.resolveOptionsMap.set(index, options);
1637
- return index;
1241
+ get input() {
1242
+ return this.inner.input;
1638
1243
  }
1639
- getSavedResolveOptions(receipt) {
1640
- return this.resolveOptionsMap.get(receipt);
1244
+ get cwd() {
1245
+ return this.inner.cwd ?? void 0;
1641
1246
  }
1642
- removeSavedResolveOptions(receipt) {
1643
- this.resolveOptionsMap.delete(receipt);
1247
+ get platform() {
1248
+ return this.inner.platform;
1644
1249
  }
1645
1250
  };
1646
1251
 
1647
1252
  //#endregion
1648
- //#region src/utils/normalize-string-or-regex.ts
1649
- function normalizedStringOrRegex(pattern) {
1650
- if (!pattern) return void 0;
1651
- if (!Array.isArray(pattern)) pattern = [pattern];
1652
- return pattern;
1653
- }
1654
-
1655
- //#endregion
1656
- //#region src/utils/bindingify-input-options.ts
1657
- function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel) {
1658
- const pluginContextData = new PluginContextData();
1659
- const plugins = rawPlugins.map((plugin) => {
1660
- if ("_parallel" in plugin) return void 0;
1661
- if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
1662
- return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel);
1663
- });
1253
+ //#region src/plugin/bindingify-build-hooks.ts
1254
+ function bindingifyBuildStart(args) {
1255
+ const hook = args.plugin.buildStart;
1256
+ if (!hook) return {};
1257
+ const { handler, meta } = normalizeHook(hook);
1664
1258
  return {
1665
- input: bindingifyInput(inputOptions.input),
1666
- plugins,
1667
- cwd: inputOptions.cwd ?? process.cwd(),
1668
- external: bindingifyExternal(inputOptions.external),
1669
- resolve: bindingifyResolve(inputOptions.resolve),
1670
- platform: inputOptions.platform,
1671
- shimMissingExports: inputOptions.shimMissingExports,
1672
- logLevel: bindingifyLogLevel(logLevel),
1673
- onLog,
1674
- treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
1675
- moduleTypes: inputOptions.moduleTypes,
1676
- define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
1677
- inject: bindingifyInject(inputOptions.inject),
1678
- experimental: {
1679
- strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
1680
- disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
1681
- viteMode: inputOptions.experimental?.viteMode,
1682
- resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
1683
- hmr: inputOptions.experimental?.hmr
1259
+ plugin: async (ctx, opts) => {
1260
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedInputOptionsImpl(opts, args.onLog));
1684
1261
  },
1685
- profilerNames: inputOptions?.profilerNames,
1686
- jsx: bindingifyJsx(inputOptions.jsx),
1687
- watch: bindingifyWatch(inputOptions.watch),
1688
- dropLabels: inputOptions.dropLabels,
1689
- keepNames: inputOptions.keepNames,
1690
- checks: inputOptions.checks,
1691
- deferSyncScanData: () => {
1692
- let ret = [];
1693
- pluginContextData.moduleOptionMap.forEach((value, key) => {
1694
- if (value.invalidate) ret.push({
1695
- id: key,
1696
- sideEffects: bindingifySideEffects(value.moduleSideEffects)
1697
- });
1698
- });
1699
- return ret;
1700
- }
1262
+ meta: bindingifyPluginHookMeta(meta)
1701
1263
  };
1702
1264
  }
1703
- function bindingifyExternal(external) {
1704
- if (external) {
1705
- if (typeof external === "function") return (id, importer, isResolved) => {
1706
- if (id.startsWith("\0")) return false;
1707
- return external(id, importer, isResolved) ?? false;
1708
- };
1709
- const externalArr = arraify(external);
1710
- return (id, _importer, _isResolved) => {
1711
- return externalArr.some((pat) => {
1712
- if (pat instanceof RegExp) return pat.test(id);
1713
- return id === pat;
1714
- });
1715
- };
1716
- }
1717
- }
1718
- function bindingifyResolve(resolve) {
1719
- if (resolve) {
1720
- const { alias, extensionAlias,...rest } = resolve;
1721
- return {
1722
- alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
1723
- find: name,
1724
- replacements: arraify(replacement)
1725
- })) : void 0,
1726
- extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
1727
- target: name,
1728
- replacements: value
1729
- })) : void 0,
1730
- ...rest
1731
- };
1732
- }
1265
+ function bindingifyBuildEnd(args) {
1266
+ const hook = args.plugin.buildEnd;
1267
+ if (!hook) return {};
1268
+ const { handler, meta } = normalizeHook(hook);
1269
+ return {
1270
+ plugin: async (ctx, err) => {
1271
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), err ? normalizeErrors(err) : void 0);
1272
+ },
1273
+ meta: bindingifyPluginHookMeta(meta)
1274
+ };
1733
1275
  }
1734
- function bindingifyInject(inject) {
1735
- if (inject) return Object.entries(inject).map(([alias, item]) => {
1736
- if (Array.isArray(item)) {
1737
- if (item[1] === "*") return {
1738
- tagNamespace: true,
1739
- alias,
1740
- from: item[0]
1276
+ function bindingifyResolveId(args) {
1277
+ const hook = args.plugin.resolveId;
1278
+ if (!hook) return {};
1279
+ const { handler, meta, options } = normalizeHook(hook);
1280
+ return {
1281
+ plugin: async (ctx, specifier, importer, extraOptions) => {
1282
+ const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
1283
+ const newExtraOptions = {
1284
+ ...extraOptions,
1285
+ custom: contextResolveOptions?.custom,
1286
+ [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
1287
+ };
1288
+ const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0, newExtraOptions);
1289
+ if (ret == null) return;
1290
+ if (ret === false) return {
1291
+ id: specifier,
1292
+ external: true
1741
1293
  };
1294
+ if (typeof ret === "string") return { id: ret };
1295
+ let exist = args.pluginContextData.updateModuleOption(ret.id, {
1296
+ meta: ret.meta || {},
1297
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1298
+ invalidate: false
1299
+ });
1742
1300
  return {
1743
- tagNamed: true,
1744
- alias,
1745
- from: item[0],
1746
- imported: item[1]
1301
+ id: ret.id,
1302
+ external: ret.external,
1303
+ sideEffects: bindingifySideEffects(exist.moduleSideEffects)
1747
1304
  };
1748
- } else return {
1749
- tagNamed: true,
1750
- imported: "default",
1751
- alias,
1752
- from: item
1753
- };
1754
- });
1755
- }
1756
- function bindingifyLogLevel(logLevel) {
1757
- switch (logLevel) {
1758
- case "silent": return import_binding.BindingLogLevel.Silent;
1759
- case "debug": return import_binding.BindingLogLevel.Debug;
1760
- case "warn": return import_binding.BindingLogLevel.Warn;
1761
- case "info": return import_binding.BindingLogLevel.Info;
1762
- default: throw new Error(`Unexpected log level: ${logLevel}`);
1763
- }
1764
- }
1765
- function bindingifyInput(input) {
1766
- if (input === void 0) return [];
1767
- if (typeof input === "string") return [{ import: input }];
1768
- if (Array.isArray(input)) return input.map((src) => ({ import: src }));
1769
- return Object.entries(input).map((value) => {
1770
- return {
1771
- name: value[0],
1772
- import: value[1]
1773
- };
1774
- });
1305
+ },
1306
+ meta: bindingifyPluginHookMeta(meta),
1307
+ filter: bindingifyResolveIdFilter(options.filter)
1308
+ };
1775
1309
  }
1776
- function bindingifyJsx(input) {
1777
- if (input === false) return { type: "Disable" };
1778
- if (input) {
1779
- if (input.mode === "preserve") return { type: "Preserve" };
1780
- const mode = input.mode ?? "automatic";
1781
- return {
1782
- type: "Enable",
1783
- field0: {
1784
- runtime: mode,
1785
- importSource: mode === "classic" ? input.importSource : mode === "automatic" ? input.jsxImportSource : void 0,
1786
- pragma: input.factory,
1787
- pragmaFrag: input.fragment,
1788
- development: input.development,
1789
- refresh: input.refresh
1790
- }
1791
- };
1792
- }
1310
+ function bindingifyResolveDynamicImport(args) {
1311
+ const hook = args.plugin.resolveDynamicImport;
1312
+ if (!hook) return {};
1313
+ const { handler, meta } = normalizeHook(hook);
1314
+ return {
1315
+ plugin: async (ctx, specifier, importer) => {
1316
+ const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0);
1317
+ if (ret == null) return;
1318
+ if (ret === false) return {
1319
+ id: specifier,
1320
+ external: true
1321
+ };
1322
+ if (typeof ret === "string") return { id: ret };
1323
+ const result = {
1324
+ id: ret.id,
1325
+ external: ret.external
1326
+ };
1327
+ if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
1328
+ args.pluginContextData.updateModuleOption(ret.id, {
1329
+ meta: ret.meta || {},
1330
+ moduleSideEffects: ret.moduleSideEffects || null,
1331
+ invalidate: false
1332
+ });
1333
+ return result;
1334
+ },
1335
+ meta: bindingifyPluginHookMeta(meta)
1336
+ };
1793
1337
  }
1794
- function bindingifyWatch(watch$1) {
1795
- if (watch$1) {
1796
- let value = {
1797
- buildDelay: watch$1.buildDelay,
1798
- skipWrite: watch$1.skipWrite,
1799
- include: normalizedStringOrRegex(watch$1.include),
1800
- exclude: normalizedStringOrRegex(watch$1.exclude)
1801
- };
1802
- if (watch$1.chokidar) unsupported("The watch chokidar option is deprecated, please use notify options instead of it.");
1803
- return value;
1804
- }
1338
+ function bindingifyTransform(args) {
1339
+ const hook = args.plugin.transform;
1340
+ if (!hook) return {};
1341
+ const { handler, meta, options } = normalizeHook(hook);
1342
+ return {
1343
+ plugin: async (ctx, code, id, meta$1) => {
1344
+ const ret = await handler.call(new TransformPluginContext(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel), code, id, meta$1);
1345
+ if (ret == null) return void 0;
1346
+ if (typeof ret === "string") return { code: ret };
1347
+ let moduleOption = args.pluginContextData.updateModuleOption(id, {
1348
+ meta: ret.meta ?? {},
1349
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1350
+ invalidate: false
1351
+ });
1352
+ return {
1353
+ code: ret.code,
1354
+ map: bindingifySourcemap$1(normalizeTransformHookSourcemap(id, code, ret.map)),
1355
+ sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
1356
+ moduleType: ret.moduleType
1357
+ };
1358
+ },
1359
+ meta: bindingifyPluginHookMeta(meta),
1360
+ filter: bindingifyTransformFilter(options.filter)
1361
+ };
1805
1362
  }
1806
- function bindingifyTreeshakeOptions(config) {
1807
- if (config === false) return void 0;
1808
- if (config === true || config === void 0) return {
1809
- moduleSideEffects: true,
1810
- annotations: true
1363
+ function bindingifyLoad(args) {
1364
+ const hook = args.plugin.load;
1365
+ if (!hook) return {};
1366
+ const { handler, meta, options } = normalizeHook(hook);
1367
+ return {
1368
+ plugin: async (ctx, id) => {
1369
+ const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, id), id);
1370
+ if (ret == null) return;
1371
+ if (typeof ret === "string") return { code: ret };
1372
+ let moduleOption = args.pluginContextData.updateModuleOption(id, {
1373
+ meta: ret.meta || {},
1374
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1375
+ invalidate: false
1376
+ });
1377
+ let map = preProcessSourceMap(ret, id);
1378
+ return {
1379
+ code: ret.code,
1380
+ map: bindingifySourcemap$1(map),
1381
+ moduleType: ret.moduleType,
1382
+ sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
1383
+ };
1384
+ },
1385
+ meta: bindingifyPluginHookMeta(meta),
1386
+ filter: bindingifyLoadFilter(options.filter)
1811
1387
  };
1812
- let normalizedConfig = { moduleSideEffects: true };
1813
- if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
1814
- else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
1815
- external: true,
1816
- sideEffects: false
1817
- }, {
1818
- external: false,
1819
- sideEffects: true
1820
- }];
1821
- else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
1822
- normalizedConfig.annotations = config.annotations ?? true;
1823
- return normalizedConfig;
1824
1388
  }
1825
-
1826
- //#endregion
1827
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-D6FCK2GA.js
1828
- function u$1(o, n, a) {
1829
- let t$1 = (r) => o(r, ...n);
1830
- return a === void 0 ? t$1 : Object.assign(t$1, {
1831
- lazy: a,
1832
- lazyArgs: n
1833
- });
1389
+ function preProcessSourceMap(ret, id) {
1390
+ if (!ret.map) return;
1391
+ let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
1392
+ if (!isEmptySourcemapFiled(map.sources)) {
1393
+ const directory = path.dirname(id) || ".";
1394
+ const sourceRoot = map.sourceRoot || ".";
1395
+ map.sources = map.sources.map((source) => path.resolve(directory, sourceRoot, source));
1396
+ }
1397
+ return map;
1834
1398
  }
1835
-
1836
- //#endregion
1837
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-WIMGWYZL.js
1838
- function u(r, n, o) {
1839
- let a = r.length - n.length;
1840
- if (a === 0) return r(...n);
1841
- if (a === 1) return u$1(r, n, o);
1842
- throw new Error("Wrong number of arguments");
1399
+ function bindingifyModuleParsed(args) {
1400
+ const hook = args.plugin.moduleParsed;
1401
+ if (!hook) return {};
1402
+ const { handler, meta } = normalizeHook(hook);
1403
+ return {
1404
+ plugin: async (ctx, moduleInfo) => {
1405
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
1406
+ },
1407
+ meta: bindingifyPluginHookMeta(meta)
1408
+ };
1843
1409
  }
1844
1410
 
1845
1411
  //#endregion
1846
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-5NQBDF4H.js
1847
- function t(...n) {
1848
- return u(Object.keys, n);
1412
+ //#region src/utils/bindingify-output-options.ts
1413
+ function bindingifyOutputOptions(outputOptions) {
1414
+ const { dir, format, exports, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName } = outputOptions;
1415
+ return {
1416
+ dir,
1417
+ file: file == null ? void 0 : file,
1418
+ format: bindingifyFormat(format),
1419
+ exports,
1420
+ hashCharacters,
1421
+ sourcemap: bindingifySourcemap(sourcemap),
1422
+ sourcemapDebugIds,
1423
+ sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
1424
+ sourcemapPathTransform,
1425
+ banner: bindingifyAddon(banner),
1426
+ footer: bindingifyAddon(footer),
1427
+ intro: bindingifyAddon(intro),
1428
+ outro: bindingifyAddon(outro),
1429
+ extend: outputOptions.extend,
1430
+ globals,
1431
+ esModule,
1432
+ name,
1433
+ assetFileNames: bindingifyAssetFilenames(assetFileNames),
1434
+ entryFileNames,
1435
+ chunkFileNames,
1436
+ cssEntryFileNames,
1437
+ cssChunkFileNames,
1438
+ plugins: [],
1439
+ minify: outputOptions.minify,
1440
+ externalLiveBindings: outputOptions.externalLiveBindings,
1441
+ inlineDynamicImports: outputOptions.inlineDynamicImports,
1442
+ advancedChunks: outputOptions.advancedChunks,
1443
+ polyfillRequire: outputOptions.polyfillRequire,
1444
+ target: outputOptions.target,
1445
+ sanitizeFileName
1446
+ };
1849
1447
  }
1850
-
1851
- //#endregion
1852
- //#region src/utils/plugin/index.ts
1853
- const isPluginHookName = function() {
1854
- const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
1855
- return function isPluginHookName$1(hookName) {
1856
- return PLUGIN_HOOK_NAMES_SET.has(hookName);
1448
+ function bindingifyAddon(configAddon) {
1449
+ return async (chunk) => {
1450
+ if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
1451
+ return configAddon || "";
1857
1452
  };
1858
- }();
1859
-
1860
- //#endregion
1861
- //#region src/utils/compose-js-plugins.ts
1862
- const unsupportedHookName = [
1863
- "augmentChunkHash",
1864
- "generateBundle",
1865
- "moduleParsed",
1866
- "onLog",
1867
- "options",
1868
- "outputOptions",
1869
- "renderError",
1870
- "renderStart",
1871
- "resolveDynamicImport",
1872
- "writeBundle"
1873
- ];
1874
- const unsupportedHooks = new Set(unsupportedHookName);
1875
- function isUnsupportedHooks(hookName) {
1876
- return unsupportedHooks.has(hookName);
1877
1453
  }
1878
- function createComposedPlugin(plugins) {
1879
- const names = [];
1880
- const batchedHooks = {};
1881
- plugins.forEach((plugin, index) => {
1882
- const pluginName = plugin.name || `Anonymous(index: ${index})`;
1883
- names.push(pluginName);
1884
- t(plugin).forEach((pluginProp) => {
1885
- if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
1886
- if (!isPluginHookName(pluginProp)) return;
1887
- switch (pluginProp) {
1888
- case "buildStart": {
1889
- const handlers = batchedHooks.buildStart ?? [];
1890
- batchedHooks.buildStart = handlers;
1891
- if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
1892
- break;
1893
- }
1894
- case "load": {
1895
- const handlers = batchedHooks.load ?? [];
1896
- batchedHooks.load = handlers;
1897
- if (plugin.load) handlers.push([plugin.load, plugin]);
1898
- break;
1899
- }
1900
- case "transform": {
1901
- const handlers = batchedHooks.transform ?? [];
1902
- batchedHooks.transform = handlers;
1903
- if (plugin.transform) handlers.push([plugin.transform, plugin]);
1904
- break;
1905
- }
1906
- case "resolveId": {
1907
- const handlers = batchedHooks.resolveId ?? [];
1908
- batchedHooks.resolveId = handlers;
1909
- if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
1910
- break;
1911
- }
1912
- case "buildEnd": {
1913
- const handlers = batchedHooks.buildEnd ?? [];
1914
- batchedHooks.buildEnd = handlers;
1915
- if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
1916
- break;
1917
- }
1918
- case "renderChunk": {
1919
- const handlers = batchedHooks.renderChunk ?? [];
1920
- batchedHooks.renderChunk = handlers;
1921
- if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
1922
- break;
1923
- }
1924
- case "banner":
1925
- case "footer":
1926
- case "intro":
1927
- case "outro": {
1928
- const hook = plugin[pluginProp];
1929
- if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
1930
- break;
1931
- }
1932
- case "closeBundle": {
1933
- const handlers = batchedHooks.closeBundle ?? [];
1934
- batchedHooks.closeBundle = handlers;
1935
- if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
1936
- break;
1937
- }
1938
- case "watchChange": {
1939
- const handlers = batchedHooks.watchChange ?? [];
1940
- batchedHooks.watchChange = handlers;
1941
- if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
1942
- break;
1943
- }
1944
- case "closeWatcher": {
1945
- const handlers = batchedHooks.closeWatcher ?? [];
1946
- batchedHooks.closeWatcher = handlers;
1947
- if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
1948
- break;
1949
- }
1950
- default: {}
1951
- }
1454
+ function bindingifyFormat(format) {
1455
+ switch (format) {
1456
+ case void 0:
1457
+ case "es":
1458
+ case "esm":
1459
+ case "module": return "es";
1460
+ case "cjs":
1461
+ case "commonjs": return "cjs";
1462
+ case "iife": return "iife";
1463
+ case "umd": return "umd";
1464
+ case "experimental-app": return "app";
1465
+ default: unimplemented(`output.format: ${format}`);
1466
+ }
1467
+ }
1468
+ function bindingifySourcemap(sourcemap) {
1469
+ switch (sourcemap) {
1470
+ case true: return "file";
1471
+ case "inline": return "inline";
1472
+ case false:
1473
+ case void 0: return void 0;
1474
+ case "hidden": return "hidden";
1475
+ default: throw new Error(`unknown sourcemap: ${sourcemap}`);
1476
+ }
1477
+ }
1478
+ function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
1479
+ return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
1480
+ }
1481
+ function bindingifyAssetFilenames(assetFileNames) {
1482
+ if (typeof assetFileNames === "function") return (asset) => {
1483
+ return assetFileNames({
1484
+ names: asset.names,
1485
+ originalFileNames: asset.originalFileNames,
1486
+ source: transformAssetSource(asset.source),
1487
+ type: "asset"
1952
1488
  });
1953
- });
1954
- const composed = { name: `Composed(${names.join(", ")})` };
1955
- const createFixedPluginResolveFnMap = new Map();
1956
- function applyFixedPluginResolveFn(ctx, plugin) {
1957
- const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
1958
- if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
1959
- return ctx;
1489
+ };
1490
+ return assetFileNames;
1491
+ }
1492
+
1493
+ //#endregion
1494
+ //#region src/options/normalized-output-options.ts
1495
+ var NormalizedOutputOptionsImpl = class {
1496
+ constructor(inner, outputOptions, normalizedOutputPlugins) {
1497
+ this.inner = inner;
1498
+ this.outputOptions = outputOptions;
1499
+ this.normalizedOutputPlugins = normalizedOutputPlugins;
1960
1500
  }
1961
- if (batchedHooks.resolveId) {
1962
- const batchedHandlers = batchedHooks.resolveId;
1963
- const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
1964
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
1965
- const [_handler, plugin] = batchedHandlers[handlerIdx];
1966
- const handlerSymbol = handlerSymbols[handlerIdx];
1967
- const createFixedPluginResolveFn = (ctx, resolve) => {
1968
- return (source, importer, rawContextResolveOptions) => {
1969
- const contextResolveOptions = rawContextResolveOptions ?? {};
1970
- if (contextResolveOptions.skipSelf) {
1971
- contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
1972
- contextResolveOptions.skipSelf = false;
1973
- }
1974
- return resolve(source, importer, contextResolveOptions);
1975
- };
1976
- };
1977
- createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
1978
- }
1979
- composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
1980
- const hookResolveIdOptions = rawHookResolveIdOptions;
1981
- const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
1982
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
1983
- const [handler, plugin] = batchedHandlers[handlerIdx];
1984
- const handlerSymbol = handlerSymbols[handlerIdx];
1985
- if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
1986
- const { handler: handlerFn } = normalizeHook(handler);
1987
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
1988
- if (!isNullish(result)) return result;
1989
- }
1990
- };
1501
+ get dir() {
1502
+ return this.inner.dir ?? void 0;
1991
1503
  }
1992
- t(batchedHooks).forEach((hookName) => {
1993
- switch (hookName) {
1994
- case "resolveId": break;
1995
- case "buildStart": {
1996
- if (batchedHooks.buildStart) {
1997
- const batchedHandlers = batchedHooks.buildStart;
1998
- composed.buildStart = async function(options) {
1999
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2000
- const { handler: handlerFn } = normalizeHook(handler);
2001
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
2002
- }));
2003
- };
2004
- }
2005
- break;
2006
- }
2007
- case "load": {
2008
- if (batchedHooks.load) {
2009
- const batchedHandlers = batchedHooks.load;
2010
- composed.load = async function(id) {
2011
- for (const [handler, plugin] of batchedHandlers) {
2012
- const { handler: handlerFn } = normalizeHook(handler);
2013
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id);
2014
- if (!isNullish(result)) return result;
2015
- }
2016
- };
2017
- }
2018
- break;
2019
- }
2020
- case "transform": {
2021
- if (batchedHooks.transform) {
2022
- const batchedHandlers = batchedHooks.transform;
2023
- composed.transform = async function(initialCode, id, moduleType) {
2024
- let code = initialCode;
2025
- let moduleSideEffects = void 0;
2026
- function updateOutput(newCode, newModuleSideEffects) {
2027
- code = newCode;
2028
- moduleSideEffects = newModuleSideEffects ?? void 0;
2029
- }
2030
- for (const [handler, plugin] of batchedHandlers) {
2031
- const { handler: handlerFn } = normalizeHook(handler);
2032
- this.getCombinedSourcemap = () => {
2033
- throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
2034
- };
2035
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, id, moduleType);
2036
- if (!isNullish(result)) {
2037
- if (typeof result === "string") updateOutput(result);
2038
- else if (result.code) updateOutput(result.code, result.moduleSideEffects);
2039
- }
2040
- }
2041
- return {
2042
- code,
2043
- moduleSideEffects
2044
- };
2045
- };
2046
- }
2047
- break;
2048
- }
2049
- case "buildEnd": {
2050
- if (batchedHooks.buildEnd) {
2051
- const batchedHandlers = batchedHooks.buildEnd;
2052
- composed.buildEnd = async function(err) {
2053
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2054
- const { handler: handlerFn } = normalizeHook(handler);
2055
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
2056
- }));
2057
- };
2058
- }
2059
- break;
2060
- }
2061
- case "renderChunk": {
2062
- if (batchedHooks.renderChunk) {
2063
- const batchedHandlers = batchedHooks.renderChunk;
2064
- composed.renderChunk = async function(code, chunk, options) {
2065
- for (const [handler, plugin] of batchedHandlers) {
2066
- const { handler: handlerFn } = normalizeHook(handler);
2067
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, chunk, options);
2068
- if (!isNullish(result)) return result;
2069
- }
2070
- };
2071
- }
2072
- break;
2073
- }
2074
- case "banner":
2075
- case "footer":
2076
- case "intro":
2077
- case "outro": {
2078
- const hooks = batchedHooks[hookName];
2079
- if (hooks?.length) composed[hookName] = async function(chunk) {
2080
- const ret = [];
2081
- for (const [hook, plugin] of hooks) {
2082
- const { handler } = normalizeHook(hook);
2083
- ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
2084
- }
2085
- return ret.join("\n");
2086
- };
2087
- break;
2088
- }
2089
- case "closeBundle": {
2090
- if (batchedHooks.closeBundle) {
2091
- const batchedHandlers = batchedHooks.closeBundle;
2092
- composed.closeBundle = async function() {
2093
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2094
- const { handler: handlerFn } = normalizeHook(handler);
2095
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2096
- }));
2097
- };
2098
- }
2099
- break;
2100
- }
2101
- case "watchChange": {
2102
- if (batchedHooks.watchChange) {
2103
- const batchedHandlers = batchedHooks.watchChange;
2104
- composed.watchChange = async function(id, event) {
2105
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2106
- const { handler: handlerFn } = normalizeHook(handler);
2107
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id, event);
2108
- }));
2109
- };
2110
- }
2111
- break;
1504
+ get entryFileNames() {
1505
+ return this.inner.entryFilenames || this.outputOptions.entryFileNames;
1506
+ }
1507
+ get chunkFileNames() {
1508
+ return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
1509
+ }
1510
+ get assetFileNames() {
1511
+ return this.inner.assetFilenames || this.outputOptions.assetFileNames;
1512
+ }
1513
+ get format() {
1514
+ return this.inner.format;
1515
+ }
1516
+ get exports() {
1517
+ return this.inner.exports;
1518
+ }
1519
+ get sourcemap() {
1520
+ return this.inner.sourcemap;
1521
+ }
1522
+ get cssEntryFileNames() {
1523
+ return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
1524
+ }
1525
+ get cssChunkFileNames() {
1526
+ return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
1527
+ }
1528
+ get shimMissingExports() {
1529
+ return this.inner.shimMissingExports;
1530
+ }
1531
+ get name() {
1532
+ return this.inner.name ?? void 0;
1533
+ }
1534
+ get file() {
1535
+ return this.inner.file ?? void 0;
1536
+ }
1537
+ get inlineDynamicImports() {
1538
+ return this.inner.inlineDynamicImports;
1539
+ }
1540
+ get externalLiveBindings() {
1541
+ return this.inner.externalLiveBindings;
1542
+ }
1543
+ get banner() {
1544
+ return normalizeAddon(this.outputOptions.banner);
1545
+ }
1546
+ get footer() {
1547
+ return normalizeAddon(this.outputOptions.footer);
1548
+ }
1549
+ get intro() {
1550
+ return normalizeAddon(this.outputOptions.intro);
1551
+ }
1552
+ get outro() {
1553
+ return normalizeAddon(this.outputOptions.outro);
1554
+ }
1555
+ get esModule() {
1556
+ return this.inner.esModule;
1557
+ }
1558
+ get extend() {
1559
+ return this.inner.extend;
1560
+ }
1561
+ get globals() {
1562
+ return this.inner.globals || this.outputOptions.globals;
1563
+ }
1564
+ get hashCharacters() {
1565
+ return this.inner.hashCharacters;
1566
+ }
1567
+ get sourcemapDebugIds() {
1568
+ return this.inner.sourcemapDebugIds;
1569
+ }
1570
+ get sourcemapIgnoreList() {
1571
+ return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
1572
+ }
1573
+ get sourcemapPathTransform() {
1574
+ return this.outputOptions.sourcemapPathTransform;
1575
+ }
1576
+ get minify() {
1577
+ return this.inner.minify;
1578
+ }
1579
+ get comments() {
1580
+ return this.inner.comments;
1581
+ }
1582
+ get polyfillRequire() {
1583
+ return this.inner.polyfillRequire;
1584
+ }
1585
+ get plugins() {
1586
+ return this.normalizedOutputPlugins;
1587
+ }
1588
+ };
1589
+ function normalizeAddon(value) {
1590
+ if (typeof value === "function") return value;
1591
+ return () => value || "";
1592
+ }
1593
+
1594
+ //#endregion
1595
+ //#region src/plugin/bindingify-output-hooks.ts
1596
+ function bindingifyRenderStart(args) {
1597
+ const hook = args.plugin.renderStart;
1598
+ if (!hook) return {};
1599
+ const { handler, meta } = normalizeHook(hook);
1600
+ return {
1601
+ plugin: async (ctx, opts) => {
1602
+ handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args.onLog));
1603
+ },
1604
+ meta: bindingifyPluginHookMeta(meta)
1605
+ };
1606
+ }
1607
+ function bindingifyRenderChunk(args) {
1608
+ const hook = args.plugin.renderChunk;
1609
+ if (!hook) return {};
1610
+ const { handler, meta } = normalizeHook(hook);
1611
+ return {
1612
+ plugin: async (ctx, code, chunk, opts) => {
1613
+ const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), code, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins));
1614
+ if (ret == null) return;
1615
+ if (typeof ret === "string") return { code: ret };
1616
+ if (!ret.map) return { code: ret.code };
1617
+ return {
1618
+ code: ret.code,
1619
+ map: bindingifySourcemap$1(ret.map)
1620
+ };
1621
+ },
1622
+ meta: bindingifyPluginHookMeta(meta)
1623
+ };
1624
+ }
1625
+ function bindingifyAugmentChunkHash(args) {
1626
+ const hook = args.plugin.augmentChunkHash;
1627
+ if (!hook) return {};
1628
+ const { handler, meta } = normalizeHook(hook);
1629
+ return {
1630
+ plugin: async (ctx, chunk) => {
1631
+ return await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1632
+ },
1633
+ meta: bindingifyPluginHookMeta(meta)
1634
+ };
1635
+ }
1636
+ function bindingifyRenderError(args) {
1637
+ const hook = args.plugin.renderError;
1638
+ if (!hook) return {};
1639
+ const { handler, meta } = normalizeHook(hook);
1640
+ return {
1641
+ plugin: async (ctx, err) => {
1642
+ handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), normalizeErrors(err));
1643
+ },
1644
+ meta: bindingifyPluginHookMeta(meta)
1645
+ };
1646
+ }
1647
+ function bindingifyGenerateBundle(args) {
1648
+ const hook = args.plugin.generateBundle;
1649
+ if (!hook) return {};
1650
+ const { handler, meta } = normalizeHook(hook);
1651
+ return {
1652
+ plugin: async (ctx, bundle, isWrite, opts) => {
1653
+ const changed = {
1654
+ updated: new Set(),
1655
+ deleted: new Set()
1656
+ };
1657
+ const output = transformToOutputBundle(bundle, changed);
1658
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output, isWrite);
1659
+ return collectChangedBundle(changed, output);
1660
+ },
1661
+ meta: bindingifyPluginHookMeta(meta)
1662
+ };
1663
+ }
1664
+ function bindingifyWriteBundle(args) {
1665
+ const hook = args.plugin.writeBundle;
1666
+ if (!hook) return {};
1667
+ const { handler, meta } = normalizeHook(hook);
1668
+ return {
1669
+ plugin: async (ctx, bundle, opts) => {
1670
+ const changed = {
1671
+ updated: new Set(),
1672
+ deleted: new Set()
1673
+ };
1674
+ const output = transformToOutputBundle(bundle, changed);
1675
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output);
1676
+ return collectChangedBundle(changed, output);
1677
+ },
1678
+ meta: bindingifyPluginHookMeta(meta)
1679
+ };
1680
+ }
1681
+ function bindingifyCloseBundle(args) {
1682
+ const hook = args.plugin.closeBundle;
1683
+ if (!hook) return {};
1684
+ const { handler, meta } = normalizeHook(hook);
1685
+ return {
1686
+ plugin: async (ctx) => {
1687
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
1688
+ },
1689
+ meta: bindingifyPluginHookMeta(meta)
1690
+ };
1691
+ }
1692
+ function bindingifyBanner(args) {
1693
+ const hook = args.plugin.banner;
1694
+ if (!hook) return {};
1695
+ const { handler, meta } = normalizeHook(hook);
1696
+ return {
1697
+ plugin: async (ctx, chunk) => {
1698
+ if (typeof handler === "string") return handler;
1699
+ return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1700
+ },
1701
+ meta: bindingifyPluginHookMeta(meta)
1702
+ };
1703
+ }
1704
+ function bindingifyFooter(args) {
1705
+ const hook = args.plugin.footer;
1706
+ if (!hook) return {};
1707
+ const { handler, meta } = normalizeHook(hook);
1708
+ return {
1709
+ plugin: async (ctx, chunk) => {
1710
+ if (typeof handler === "string") return handler;
1711
+ return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1712
+ },
1713
+ meta: bindingifyPluginHookMeta(meta)
1714
+ };
1715
+ }
1716
+ function bindingifyIntro(args) {
1717
+ const hook = args.plugin.intro;
1718
+ if (!hook) return {};
1719
+ const { handler, meta } = normalizeHook(hook);
1720
+ return {
1721
+ plugin: async (ctx, chunk) => {
1722
+ if (typeof handler === "string") return handler;
1723
+ return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1724
+ },
1725
+ meta: bindingifyPluginHookMeta(meta)
1726
+ };
1727
+ }
1728
+ function bindingifyOutro(args) {
1729
+ const hook = args.plugin.outro;
1730
+ if (!hook) return {};
1731
+ const { handler, meta } = normalizeHook(hook);
1732
+ return {
1733
+ plugin: async (ctx, chunk) => {
1734
+ if (typeof handler === "string") return handler;
1735
+ return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1736
+ },
1737
+ meta: bindingifyPluginHookMeta(meta)
1738
+ };
1739
+ }
1740
+
1741
+ //#endregion
1742
+ //#region src/plugin/bindingify-watch-hooks.ts
1743
+ function bindingifyWatchChange(args) {
1744
+ const hook = args.plugin.watchChange;
1745
+ if (!hook) return {};
1746
+ const { handler, meta } = normalizeHook(hook);
1747
+ return {
1748
+ plugin: async (ctx, id, event) => {
1749
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), id, { event });
1750
+ },
1751
+ meta: bindingifyPluginHookMeta(meta)
1752
+ };
1753
+ }
1754
+ function bindingifyCloseWatcher(args) {
1755
+ const hook = args.plugin.closeWatcher;
1756
+ if (!hook) return {};
1757
+ const { handler, meta } = normalizeHook(hook);
1758
+ return {
1759
+ plugin: async (ctx) => {
1760
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
1761
+ },
1762
+ meta: bindingifyPluginHookMeta(meta)
1763
+ };
1764
+ }
1765
+
1766
+ //#endregion
1767
+ //#region src/plugin/bindingify-plugin.ts
1768
+ function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel) {
1769
+ const args = {
1770
+ plugin,
1771
+ options,
1772
+ outputOptions,
1773
+ pluginContextData,
1774
+ onLog,
1775
+ logLevel,
1776
+ normalizedOutputPlugins
1777
+ };
1778
+ const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
1779
+ const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
1780
+ const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
1781
+ const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
1782
+ const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
1783
+ const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
1784
+ const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
1785
+ const { plugin: renderChunk, meta: renderChunkMeta } = bindingifyRenderChunk(args);
1786
+ const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
1787
+ const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
1788
+ const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
1789
+ const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
1790
+ const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
1791
+ const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
1792
+ const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args);
1793
+ const { plugin: footer, meta: footerMeta } = bindingifyFooter(args);
1794
+ const { plugin: intro, meta: introMeta } = bindingifyIntro(args);
1795
+ const { plugin: outro, meta: outroMeta } = bindingifyOutro(args);
1796
+ const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
1797
+ const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
1798
+ const result = {
1799
+ name: plugin.name,
1800
+ buildStart,
1801
+ buildStartMeta,
1802
+ resolveId,
1803
+ resolveIdMeta,
1804
+ resolveIdFilter,
1805
+ resolveDynamicImport,
1806
+ resolveDynamicImportMeta,
1807
+ buildEnd,
1808
+ buildEndMeta,
1809
+ transform,
1810
+ transformMeta,
1811
+ transformFilter,
1812
+ moduleParsed,
1813
+ moduleParsedMeta,
1814
+ load,
1815
+ loadMeta,
1816
+ loadFilter,
1817
+ renderChunk,
1818
+ renderChunkMeta,
1819
+ augmentChunkHash,
1820
+ augmentChunkHashMeta,
1821
+ renderStart,
1822
+ renderStartMeta,
1823
+ renderError,
1824
+ renderErrorMeta,
1825
+ generateBundle,
1826
+ generateBundleMeta,
1827
+ writeBundle,
1828
+ writeBundleMeta,
1829
+ closeBundle,
1830
+ closeBundleMeta,
1831
+ banner,
1832
+ bannerMeta,
1833
+ footer,
1834
+ footerMeta,
1835
+ intro,
1836
+ introMeta,
1837
+ outro,
1838
+ outroMeta,
1839
+ watchChange,
1840
+ watchChangeMeta,
1841
+ closeWatcher,
1842
+ closeWatcherMeta
1843
+ };
1844
+ return wrapHandlers(result);
1845
+ }
1846
+ function wrapHandlers(plugin) {
1847
+ for (const hookName of [
1848
+ "buildStart",
1849
+ "resolveId",
1850
+ "resolveDynamicImport",
1851
+ "buildEnd",
1852
+ "transform",
1853
+ "moduleParsed",
1854
+ "load",
1855
+ "renderChunk",
1856
+ "augmentChunkHash",
1857
+ "renderStart",
1858
+ "renderError",
1859
+ "generateBundle",
1860
+ "writeBundle",
1861
+ "closeBundle",
1862
+ "banner",
1863
+ "footer",
1864
+ "intro",
1865
+ "outro",
1866
+ "watchChange",
1867
+ "closeWatcher"
1868
+ ]) {
1869
+ const handler = plugin[hookName];
1870
+ if (handler) plugin[hookName] = async (...args) => {
1871
+ try {
1872
+ return await handler(...args);
1873
+ } catch (e) {
1874
+ return error(logPluginError(e, plugin.name, {
1875
+ hook: hookName,
1876
+ id: hookName === "transform" ? args[2] : void 0
1877
+ }));
2112
1878
  }
2113
- case "closeWatcher": {
2114
- if (batchedHooks.closeWatcher) {
2115
- const batchedHandlers = batchedHooks.closeWatcher;
2116
- composed.closeWatcher = async function() {
2117
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2118
- const { handler: handlerFn } = normalizeHook(handler);
2119
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2120
- }));
2121
- };
2122
- }
2123
- break;
1879
+ };
1880
+ }
1881
+ return plugin;
1882
+ }
1883
+
1884
+ //#endregion
1885
+ //#region src/plugin/plugin-context-data.ts
1886
+ var PluginContextData = class {
1887
+ moduleOptionMap = new Map();
1888
+ resolveOptionsMap = new Map();
1889
+ loadModulePromiseMap = new Map();
1890
+ updateModuleOption(id, option) {
1891
+ const existing = this.moduleOptionMap.get(id);
1892
+ if (existing) {
1893
+ if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
1894
+ if (option.meta != null) Object.assign(existing.meta, option.meta);
1895
+ if (option.invalidate != null) existing.invalidate = option.invalidate;
1896
+ } else {
1897
+ this.moduleOptionMap.set(id, option);
1898
+ return option;
1899
+ }
1900
+ return existing;
1901
+ }
1902
+ getModuleOption(id) {
1903
+ const option = this.moduleOptionMap.get(id);
1904
+ if (!option) {
1905
+ const raw = {
1906
+ moduleSideEffects: null,
1907
+ meta: {}
1908
+ };
1909
+ this.moduleOptionMap.set(id, raw);
1910
+ return raw;
1911
+ }
1912
+ return option;
1913
+ }
1914
+ getModuleInfo(id, context) {
1915
+ const bindingInfo = context.getModuleInfo(id);
1916
+ if (bindingInfo) {
1917
+ const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
1918
+ return this.proxyModuleInfo(id, info);
1919
+ }
1920
+ return null;
1921
+ }
1922
+ proxyModuleInfo(id, info) {
1923
+ let moduleSideEffects = info.moduleSideEffects;
1924
+ Object.defineProperty(info, "moduleSideEffects", {
1925
+ get() {
1926
+ return moduleSideEffects;
1927
+ },
1928
+ set: (v$1) => {
1929
+ this.updateModuleOption(id, {
1930
+ moduleSideEffects: v$1,
1931
+ meta: info.meta,
1932
+ invalidate: true
1933
+ });
1934
+ moduleSideEffects = v$1;
2124
1935
  }
2125
- default: {}
1936
+ });
1937
+ return info;
1938
+ }
1939
+ getModuleIds(context) {
1940
+ const moduleIds = context.getModuleIds();
1941
+ return moduleIds.values();
1942
+ }
1943
+ saveResolveOptions(options) {
1944
+ const index = this.resolveOptionsMap.size;
1945
+ this.resolveOptionsMap.set(index, options);
1946
+ return index;
1947
+ }
1948
+ getSavedResolveOptions(receipt) {
1949
+ return this.resolveOptionsMap.get(receipt);
1950
+ }
1951
+ removeSavedResolveOptions(receipt) {
1952
+ this.resolveOptionsMap.delete(receipt);
1953
+ }
1954
+ };
1955
+
1956
+ //#endregion
1957
+ //#region src/utils/normalize-string-or-regex.ts
1958
+ function normalizedStringOrRegex(pattern) {
1959
+ if (!pattern) return void 0;
1960
+ if (!Array.isArray(pattern)) pattern = [pattern];
1961
+ return pattern;
1962
+ }
1963
+
1964
+ //#endregion
1965
+ //#region src/utils/bindingify-input-options.ts
1966
+ function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel) {
1967
+ const pluginContextData = new PluginContextData();
1968
+ const plugins = rawPlugins.map((plugin) => {
1969
+ if ("_parallel" in plugin) return void 0;
1970
+ if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
1971
+ return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel);
1972
+ });
1973
+ return {
1974
+ input: bindingifyInput(inputOptions.input),
1975
+ plugins,
1976
+ cwd: inputOptions.cwd ?? process.cwd(),
1977
+ external: bindingifyExternal(inputOptions.external),
1978
+ resolve: bindingifyResolve(inputOptions.resolve),
1979
+ platform: inputOptions.platform,
1980
+ shimMissingExports: inputOptions.shimMissingExports,
1981
+ logLevel: bindingifyLogLevel(logLevel),
1982
+ onLog,
1983
+ treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
1984
+ moduleTypes: inputOptions.moduleTypes,
1985
+ define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
1986
+ inject: bindingifyInject(inputOptions.inject),
1987
+ experimental: {
1988
+ strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
1989
+ disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
1990
+ viteMode: inputOptions.experimental?.viteMode,
1991
+ resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
1992
+ hmr: inputOptions.experimental?.hmr
1993
+ },
1994
+ profilerNames: inputOptions?.profilerNames,
1995
+ jsx: bindingifyJsx(inputOptions.jsx),
1996
+ watch: bindingifyWatch(inputOptions.watch),
1997
+ dropLabels: inputOptions.dropLabels,
1998
+ keepNames: inputOptions.keepNames,
1999
+ checks: inputOptions.checks,
2000
+ deferSyncScanData: () => {
2001
+ let ret = [];
2002
+ pluginContextData.moduleOptionMap.forEach((value, key) => {
2003
+ if (value.invalidate) ret.push({
2004
+ id: key,
2005
+ sideEffects: bindingifySideEffects(value.moduleSideEffects)
2006
+ });
2007
+ });
2008
+ return ret;
2126
2009
  }
2010
+ };
2011
+ }
2012
+ function bindingifyExternal(external) {
2013
+ if (external) {
2014
+ if (typeof external === "function") return (id, importer, isResolved) => {
2015
+ if (id.startsWith("\0")) return false;
2016
+ return external(id, importer, isResolved) ?? false;
2017
+ };
2018
+ const externalArr = arraify(external);
2019
+ return (id, _importer, _isResolved) => {
2020
+ return externalArr.some((pat) => {
2021
+ if (pat instanceof RegExp) return pat.test(id);
2022
+ return id === pat;
2023
+ });
2024
+ };
2025
+ }
2026
+ }
2027
+ function bindingifyResolve(resolve) {
2028
+ if (resolve) {
2029
+ const { alias, extensionAlias,...rest } = resolve;
2030
+ return {
2031
+ alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
2032
+ find: name,
2033
+ replacements: arraify(replacement)
2034
+ })) : void 0,
2035
+ extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
2036
+ target: name,
2037
+ replacements: value
2038
+ })) : void 0,
2039
+ ...rest
2040
+ };
2041
+ }
2042
+ }
2043
+ function bindingifyInject(inject) {
2044
+ if (inject) return Object.entries(inject).map(([alias, item]) => {
2045
+ if (Array.isArray(item)) {
2046
+ if (item[1] === "*") return {
2047
+ tagNamespace: true,
2048
+ alias,
2049
+ from: item[0]
2050
+ };
2051
+ return {
2052
+ tagNamed: true,
2053
+ alias,
2054
+ from: item[0],
2055
+ imported: item[1]
2056
+ };
2057
+ } else return {
2058
+ tagNamed: true,
2059
+ imported: "default",
2060
+ alias,
2061
+ from: item
2062
+ };
2127
2063
  });
2128
- return composed;
2129
2064
  }
2130
- function isComposablePlugin(plugin) {
2131
- if (plugin instanceof BuiltinPlugin) return false;
2132
- if ("_parallel" in plugin) return false;
2133
- const hasNotComposablePattern = t(plugin).some((hookName) => {
2134
- if (!isPluginHookName(hookName)) return false;
2135
- const OK_TO_COMPOSE = false;
2136
- if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
2137
- if (plugin[hookName]) {
2138
- const { meta } = normalizeHook(plugin[hookName]);
2139
- if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
2140
- }
2141
- return OK_TO_COMPOSE;
2065
+ function bindingifyLogLevel(logLevel) {
2066
+ switch (logLevel) {
2067
+ case "silent": return import_binding.BindingLogLevel.Silent;
2068
+ case "debug": return import_binding.BindingLogLevel.Debug;
2069
+ case "warn": return import_binding.BindingLogLevel.Warn;
2070
+ case "info": return import_binding.BindingLogLevel.Info;
2071
+ default: throw new Error(`Unexpected log level: ${logLevel}`);
2072
+ }
2073
+ }
2074
+ function bindingifyInput(input) {
2075
+ if (input === void 0) return [];
2076
+ if (typeof input === "string") return [{ import: input }];
2077
+ if (Array.isArray(input)) return input.map((src) => ({ import: src }));
2078
+ return Object.entries(input).map((value) => {
2079
+ return {
2080
+ name: value[0],
2081
+ import: value[1]
2082
+ };
2142
2083
  });
2143
- if (hasNotComposablePattern) return false;
2144
- return true;
2145
2084
  }
2146
- function composeJsPlugins(plugins) {
2147
- const newPlugins = [];
2148
- const toBeComposed = [];
2149
- plugins.forEach((plugin) => {
2150
- if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
2151
- else {
2152
- if (toBeComposed.length > 0) {
2153
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2154
- else newPlugins.push(toBeComposed[0]);
2155
- toBeComposed.length = 0;
2085
+ function bindingifyJsx(input) {
2086
+ if (input === false) return { type: "Disable" };
2087
+ if (input) {
2088
+ if (input.mode === "preserve") return { type: "Preserve" };
2089
+ const mode = input.mode ?? "automatic";
2090
+ return {
2091
+ type: "Enable",
2092
+ field0: {
2093
+ runtime: mode,
2094
+ importSource: mode === "classic" ? input.importSource : mode === "automatic" ? input.jsxImportSource : void 0,
2095
+ pragma: input.factory,
2096
+ pragmaFrag: input.fragment,
2097
+ development: input.development,
2098
+ refresh: input.refresh
2156
2099
  }
2157
- newPlugins.push(plugin);
2158
- }
2159
- });
2160
- if (toBeComposed.length > 0) {
2161
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2162
- else newPlugins.push(toBeComposed[0]);
2163
- toBeComposed.length = 0;
2100
+ };
2164
2101
  }
2165
- return newPlugins;
2166
2102
  }
2167
-
2168
- //#endregion
2169
- //#region src/utils/initialize-parallel-plugins.ts
2170
- async function initializeParallelPlugins(plugins) {
2171
- const pluginInfos = [];
2172
- for (const [index, plugin] of plugins.entries()) if ("_parallel" in plugin) {
2173
- const { fileUrl, options } = plugin._parallel;
2174
- pluginInfos.push({
2175
- index,
2176
- fileUrl,
2177
- options
2178
- });
2179
- }
2180
- if (pluginInfos.length <= 0) return void 0;
2181
- const count = Math.min(availableParallelism(), 8);
2182
- const parallelJsPluginRegistry = new import_binding.ParallelJsPluginRegistry(count);
2183
- const registryId = parallelJsPluginRegistry.id;
2184
- const workers = await initializeWorkers(registryId, count, pluginInfos);
2185
- const stopWorkers = async () => {
2186
- await Promise.all(workers.map((worker) => worker.terminate()));
2187
- };
2188
- return {
2189
- registry: parallelJsPluginRegistry,
2190
- stopWorkers
2103
+ function bindingifyWatch(watch$1) {
2104
+ if (watch$1) return {
2105
+ buildDelay: watch$1.buildDelay,
2106
+ skipWrite: watch$1.skipWrite,
2107
+ include: normalizedStringOrRegex(watch$1.include),
2108
+ exclude: normalizedStringOrRegex(watch$1.exclude)
2191
2109
  };
2192
2110
  }
2193
- function initializeWorkers(registryId, count, pluginInfos) {
2194
- return Promise.all(Array.from({ length: count }, (_, i) => initializeWorker(registryId, pluginInfos, i)));
2195
- }
2196
- async function initializeWorker(registryId, pluginInfos, threadNumber) {
2197
- const urlString = import.meta.resolve("#parallel-plugin-worker");
2198
- const workerData$1 = {
2199
- registryId,
2200
- pluginInfos,
2201
- threadNumber
2111
+ function bindingifyTreeshakeOptions(config) {
2112
+ if (config === false) return void 0;
2113
+ if (config === true || config === void 0) return {
2114
+ moduleSideEffects: true,
2115
+ annotations: true
2202
2116
  };
2203
- let worker;
2204
- try {
2205
- worker = new Worker(new URL(urlString), { workerData: workerData$1 });
2206
- worker.unref();
2207
- await new Promise((resolve, reject) => {
2208
- worker.once("message", async (message) => {
2209
- if (message.type === "error") reject(message.error);
2210
- else resolve();
2211
- });
2212
- });
2213
- return worker;
2214
- } catch (e) {
2215
- worker?.terminate();
2216
- throw e;
2217
- }
2117
+ let normalizedConfig = { moduleSideEffects: true };
2118
+ if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
2119
+ else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
2120
+ external: true,
2121
+ sideEffects: false
2122
+ }, {
2123
+ external: false,
2124
+ sideEffects: true
2125
+ }];
2126
+ else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
2127
+ normalizedConfig.annotations = config.annotations ?? true;
2128
+ return normalizedConfig;
2218
2129
  }
2219
2130
 
2220
2131
  //#endregion
2221
- //#region src/utils/validator.ts
2222
- const StringOrRegExpSchema = v.union([v.string(), v.instance(RegExp)]);
2223
- const LogLevelSchema = v.union([
2224
- v.literal("debug"),
2225
- v.literal("info"),
2226
- v.literal("warn")
2227
- ]);
2228
- const LogLevelOptionSchema = v.union([LogLevelSchema, v.literal("silent")]);
2229
- const LogLevelWithErrorSchema = v.union([LogLevelSchema, v.literal("error")]);
2230
- const RollupLogSchema = v.any();
2231
- const RollupLogWithStringSchema = v.union([RollupLogSchema, v.string()]);
2232
- const InputOptionSchema = v.union([
2233
- v.string(),
2234
- v.array(v.string()),
2235
- v.record(v.string(), v.string())
2236
- ]);
2237
- const ExternalSchema = v.union([
2238
- StringOrRegExpSchema,
2239
- v.array(StringOrRegExpSchema),
2240
- v.pipe(v.function(), v.args(v.tuple([
2241
- v.string(),
2242
- v.optional(v.string()),
2243
- v.boolean()
2244
- ])), v.returns(v.nullish(v.boolean())))
2245
- ]);
2246
- const ModuleTypesSchema = v.record(v.string(), v.union([
2247
- v.literal("base64"),
2248
- v.literal("binary"),
2249
- v.literal("css"),
2250
- v.literal("dataurl"),
2251
- v.literal("empty"),
2252
- v.literal("js"),
2253
- v.literal("json"),
2254
- v.literal("jsx"),
2255
- v.literal("text"),
2256
- v.literal("ts"),
2257
- v.literal("tsx")
2258
- ]));
2259
- const JsxOptionsSchema = v.strictObject({
2260
- development: v.pipe(v.optional(v.boolean()), v.description("Development specific information")),
2261
- factory: v.pipe(v.optional(v.string()), v.description("Jsx element transformation")),
2262
- fragment: v.pipe(v.optional(v.string()), v.description("Jsx fragment transformation")),
2263
- importSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is classic")),
2264
- jsxImportSource: v.pipe(v.optional(v.string()), v.description("Import the factory of element and fragment if mode is automatic")),
2265
- mode: v.pipe(v.optional(v.union([v.literal("classic"), v.literal("automatic")])), v.description("Jsx transformation mode")),
2266
- refresh: v.pipe(v.optional(v.boolean()), v.description("React refresh transformation"))
2267
- });
2268
- const WatchOptionsSchema = v.strictObject({
2269
- chokidar: v.optional(v.any()),
2270
- exclude: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
2271
- include: v.optional(v.union([StringOrRegExpSchema, v.array(StringOrRegExpSchema)])),
2272
- notify: v.pipe(v.optional(v.strictObject({
2273
- compareContents: v.optional(v.boolean()),
2274
- pollInterval: v.optional(v.number())
2275
- })), v.description("Notify options")),
2276
- skipWrite: v.pipe(v.optional(v.boolean()), v.description("Skip the bundle.write() step")),
2277
- buildDelay: v.pipe(v.optional(v.number()), v.description("Throttle watch rebuilds"))
2278
- });
2279
- const ChecksOptionsSchema = v.strictObject({ circularDependency: v.pipe(v.optional(v.boolean()), v.description("Whether to emit warnings when detecting circular dependencies")) });
2280
- const MinifyOptionsSchema = v.strictObject({
2281
- mangle: v.boolean(),
2282
- compress: v.boolean(),
2283
- deadCodeElimination: v.boolean(),
2284
- removeWhitespace: v.boolean()
2285
- });
2286
- const ResolveOptionsSchema = v.strictObject({
2287
- alias: v.optional(v.record(v.string(), v.union([v.string(), v.array(v.string())]))),
2288
- aliasFields: v.optional(v.array(v.array(v.string()))),
2289
- conditionNames: v.optional(v.array(v.string())),
2290
- extensionAlias: v.optional(v.record(v.string(), v.array(v.string()))),
2291
- exportsFields: v.optional(v.array(v.array(v.string()))),
2292
- extensions: v.optional(v.array(v.string())),
2293
- mainFields: v.optional(v.array(v.string())),
2294
- mainFiles: v.optional(v.array(v.string())),
2295
- modules: v.optional(v.array(v.string())),
2296
- symlinks: v.optional(v.boolean()),
2297
- tsconfigFilename: v.optional(v.string())
2298
- });
2299
- const TreeshakingOptionsSchema = v.union([v.boolean(), v.looseObject({ annotations: v.optional(v.boolean()) })]);
2300
- const OnLogSchema = v.pipe(v.function(), v.args(v.tuple([
2301
- LogLevelSchema,
2302
- RollupLogSchema,
2303
- v.pipe(v.function(), v.args(v.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
2304
- ])));
2305
- const OnwarnSchema = v.pipe(v.function(), v.args(v.tuple([RollupLogSchema, v.pipe(v.function(), v.args(v.tuple([v.union([RollupLogWithStringSchema, v.pipe(v.function(), v.returns(RollupLogWithStringSchema))])])))])));
2306
- const InputOptionsSchema = v.strictObject({
2307
- input: v.optional(InputOptionSchema),
2308
- plugins: v.optional(v.custom(() => true)),
2309
- external: v.optional(ExternalSchema),
2310
- resolve: v.optional(ResolveOptionsSchema),
2311
- cwd: v.pipe(v.optional(v.string()), v.description("Current working directory")),
2312
- platform: v.pipe(v.optional(v.union([
2313
- v.literal("browser"),
2314
- v.literal("neutral"),
2315
- v.literal("node")
2316
- ])), v.description(`Platform for which the code should be generated (node, ${colors.underline("browser")}, neutral)`)),
2317
- shimMissingExports: v.pipe(v.optional(v.boolean()), v.description("Create shim variables for missing exports")),
2318
- treeshake: v.optional(TreeshakingOptionsSchema),
2319
- logLevel: v.pipe(v.optional(LogLevelOptionSchema), v.description(`Log level (${colors.dim("silent")}, ${colors.underline(colors.gray("info"))}, debug, ${colors.yellow("warn")})`)),
2320
- onLog: v.optional(OnLogSchema),
2321
- onwarn: v.optional(OnwarnSchema),
2322
- moduleTypes: v.pipe(v.optional(ModuleTypesSchema), v.description("Module types for customized extensions")),
2323
- experimental: v.optional(v.strictObject({
2324
- disableLiveBindings: v.optional(v.boolean()),
2325
- enableComposingJsPlugins: v.optional(v.boolean()),
2326
- resolveNewUrlToAsset: v.optional(v.boolean()),
2327
- strictExecutionOrder: v.optional(v.boolean()),
2328
- hmr: v.optional(v.boolean())
2329
- })),
2330
- define: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Define global variables")),
2331
- inject: v.optional(v.record(v.string(), v.union([v.string(), v.tuple([v.string(), v.string()])]))),
2332
- profilerNames: v.optional(v.boolean()),
2333
- jsx: v.optional(JsxOptionsSchema),
2334
- watch: v.optional(v.union([WatchOptionsSchema, v.literal(false)])),
2335
- dropLabels: v.pipe(v.optional(v.array(v.string())), v.description("Remove labeled statements with these label names")),
2336
- checks: v.optional(ChecksOptionsSchema)
2337
- });
2338
- const InputCliOverrideSchema = v.strictObject({
2339
- external: v.pipe(v.optional(v.array(v.string())), v.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
2340
- inject: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Inject import statements on demand")),
2341
- treeshake: v.pipe(v.optional(v.boolean()), v.description("enable treeshaking"))
2342
- });
2343
- const InputCliOptionsSchema = v.omit(v.strictObject({
2344
- ...InputOptionsSchema.entries,
2345
- ...InputCliOverrideSchema.entries
2346
- }), [
2347
- "input",
2348
- "plugins",
2349
- "onwarn",
2132
+ //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-D6FCK2GA.js
2133
+ function u$1(o, n, a) {
2134
+ let t$1 = (r) => o(r, ...n);
2135
+ return a === void 0 ? t$1 : Object.assign(t$1, {
2136
+ lazy: a,
2137
+ lazyArgs: n
2138
+ });
2139
+ }
2140
+
2141
+ //#endregion
2142
+ //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-WIMGWYZL.js
2143
+ function u(r, n, o) {
2144
+ let a = r.length - n.length;
2145
+ if (a === 0) return r(...n);
2146
+ if (a === 1) return u$1(r, n, o);
2147
+ throw new Error("Wrong number of arguments");
2148
+ }
2149
+
2150
+ //#endregion
2151
+ //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-5NQBDF4H.js
2152
+ function t(...n) {
2153
+ return u(Object.keys, n);
2154
+ }
2155
+
2156
+ //#endregion
2157
+ //#region src/utils/plugin/index.ts
2158
+ const isPluginHookName = function() {
2159
+ const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
2160
+ return function isPluginHookName$1(hookName) {
2161
+ return PLUGIN_HOOK_NAMES_SET.has(hookName);
2162
+ };
2163
+ }();
2164
+
2165
+ //#endregion
2166
+ //#region src/utils/compose-js-plugins.ts
2167
+ const unsupportedHookName = [
2168
+ "augmentChunkHash",
2169
+ "generateBundle",
2170
+ "moduleParsed",
2350
2171
  "onLog",
2351
- "resolve",
2352
- "experimental",
2353
- "profilerNames",
2354
- "watch"
2355
- ]);
2356
- var ESTarget = function(ESTarget$1) {
2357
- ESTarget$1["ES6"] = "es6";
2358
- ESTarget$1["ES2015"] = "es2015";
2359
- ESTarget$1["ES2016"] = "es2016";
2360
- ESTarget$1["ES2017"] = "es2017";
2361
- ESTarget$1["ES2018"] = "es2018";
2362
- ESTarget$1["ES2019"] = "es2019";
2363
- ESTarget$1["ES2020"] = "es2020";
2364
- ESTarget$1["ES2021"] = "es2021";
2365
- ESTarget$1["ES2022"] = "es2022";
2366
- ESTarget$1["ES2023"] = "es2023";
2367
- ESTarget$1["ES2024"] = "es2024";
2368
- ESTarget$1["ESNext"] = "esnext";
2369
- return ESTarget$1;
2370
- }(ESTarget || {});
2371
- const ModuleFormatSchema = v.union([
2372
- v.literal("es"),
2373
- v.literal("cjs"),
2374
- v.literal("esm"),
2375
- v.literal("module"),
2376
- v.literal("commonjs"),
2377
- v.literal("iife"),
2378
- v.literal("umd")
2379
- ]);
2380
- const AddonFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returnsAsync(v.unionAsync([v.string(), v.pipeAsync(v.promise(), v.awaitAsync(), v.string())])));
2381
- const ChunkFileNamesSchema = v.union([v.string(), v.pipe(v.function(), v.args(v.tuple([v.custom(() => true)])), v.returns(v.string()))]);
2382
- const GlobalsFunctionSchema = v.pipe(v.function(), v.args(v.tuple([v.string()])), v.returns(v.string()));
2383
- const AdvancedChunksSchema = v.strictObject({
2384
- minSize: v.optional(v.number()),
2385
- maxSize: v.optional(v.number()),
2386
- minModuleSize: v.optional(v.number()),
2387
- maxModuleSize: v.optional(v.number()),
2388
- minShareCount: v.optional(v.number()),
2389
- groups: v.optional(v.array(v.strictObject({
2390
- name: v.string(),
2391
- test: v.optional(v.union([v.string(), v.instance(RegExp)])),
2392
- priority: v.optional(v.number()),
2393
- minSize: v.optional(v.number()),
2394
- minShareCount: v.optional(v.number()),
2395
- maxSize: v.optional(v.number()),
2396
- minModuleSize: v.optional(v.number()),
2397
- maxModuleSize: v.optional(v.number())
2398
- })))
2399
- });
2400
- const OutputOptionsSchema = v.strictObject({
2401
- dir: v.pipe(v.optional(v.string()), v.description("Output directory, defaults to `dist` if `file` is not set")),
2402
- file: v.pipe(v.optional(v.string()), v.description("Single output file")),
2403
- exports: v.pipe(v.optional(v.union([
2404
- v.literal("auto"),
2405
- v.literal("named"),
2406
- v.literal("default"),
2407
- v.literal("none")
2408
- ])), v.description(`Specify a export mode (${colors.underline("auto")}, named, default, none)`)),
2409
- hashCharacters: v.pipe(v.optional(v.union([
2410
- v.literal("base64"),
2411
- v.literal("base36"),
2412
- v.literal("hex")
2413
- ])), v.description("Use the specified character set for file hashes")),
2414
- format: v.pipe(v.optional(ModuleFormatSchema), v.description(`Output format of the generated bundle (supports ${colors.underline("esm")}, cjs, and iife)`)),
2415
- sourcemap: v.pipe(v.optional(v.union([
2416
- v.boolean(),
2417
- v.literal("inline"),
2418
- v.literal("hidden")
2419
- ])), v.description(`Generate sourcemap (\`-s inline\` for inline, or ${colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
2420
- sourcemapDebugIds: v.pipe(v.optional(v.boolean()), v.description("Inject sourcemap debug IDs")),
2421
- sourcemapIgnoreList: v.optional(v.union([v.boolean(), v.custom(() => true)])),
2422
- sourcemapPathTransform: v.optional(v.custom(() => true)),
2423
- banner: v.optional(v.union([v.string(), AddonFunctionSchema])),
2424
- footer: v.optional(v.union([v.string(), AddonFunctionSchema])),
2425
- intro: v.optional(v.union([v.string(), AddonFunctionSchema])),
2426
- outro: v.optional(v.union([v.string(), AddonFunctionSchema])),
2427
- extend: v.pipe(v.optional(v.boolean()), v.description("Extend global variable defined by name in IIFE / UMD formats")),
2428
- esModule: v.optional(v.union([v.boolean(), v.literal("if-default-prop")])),
2429
- assetFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for asset files")),
2430
- entryFileNames: v.optional(ChunkFileNamesSchema),
2431
- chunkFileNames: v.optional(ChunkFileNamesSchema),
2432
- cssEntryFileNames: v.optional(ChunkFileNamesSchema),
2433
- cssChunkFileNames: v.optional(ChunkFileNamesSchema),
2434
- minify: v.pipe(v.optional(v.union([v.boolean(), MinifyOptionsSchema])), v.description("Minify the bundled file")),
2435
- name: v.pipe(v.optional(v.string()), v.description("Name for UMD / IIFE format outputs")),
2436
- globals: v.pipe(v.optional(v.union([v.record(v.string(), v.string()), GlobalsFunctionSchema])), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2437
- externalLiveBindings: v.pipe(v.optional(v.boolean()), v.description("external live bindings")),
2438
- inlineDynamicImports: v.pipe(v.optional(v.boolean()), v.description("Inline dynamic imports")),
2439
- advancedChunks: v.optional(AdvancedChunksSchema),
2440
- comments: v.pipe(v.optional(v.union([v.literal("none"), v.literal("preserve-legal")])), v.description("Control comments in the output")),
2441
- target: v.pipe(v.optional(v.enum(ESTarget)), v.description("The JavaScript target environment"))
2442
- });
2443
- const getAddonDescription = (placement, wrapper) => {
2444
- return `Code to insert the ${colors.bold(placement)} of the bundled file (${colors.bold(wrapper)} the wrapper function)`;
2445
- };
2446
- const OutputCliOverrideSchema = v.strictObject({
2447
- entryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted entry chunks")),
2448
- chunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted secondary chunks")),
2449
- cssEntryFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css entry chunks")),
2450
- cssChunkFileNames: v.pipe(v.optional(v.string()), v.description("Name pattern for emitted css secondary chunks")),
2451
- banner: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "outside"))),
2452
- footer: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "outside"))),
2453
- intro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("top", "inside"))),
2454
- outro: v.pipe(v.optional(v.string()), v.description(getAddonDescription("bottom", "inside"))),
2455
- esModule: v.pipe(v.optional(v.boolean()), v.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
2456
- globals: v.pipe(v.optional(v.record(v.string(), v.string())), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2457
- advancedChunks: v.pipe(v.optional(v.strictObject({
2458
- minSize: v.pipe(v.optional(v.number()), v.description("Minimum size of the chunk")),
2459
- minShareCount: v.pipe(v.optional(v.number()), v.description("Minimum share count of the chunk"))
2460
- })), v.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2461
- minify: v.pipe(v.optional(v.boolean()), v.description("Minify the bundled file"))
2462
- });
2463
- const OutputCliOptionsSchema = v.omit(v.strictObject({
2464
- ...OutputOptionsSchema.entries,
2465
- ...OutputCliOverrideSchema.entries
2466
- }), ["sourcemapIgnoreList", "sourcemapPathTransform"]);
2467
- const CliOptionsSchema = v.strictObject({
2468
- config: v.pipe(v.optional(v.union([v.string(), v.boolean()])), v.description("Path to the config file (default: `rolldown.config.js`)")),
2469
- help: v.pipe(v.optional(v.boolean()), v.description("Show help")),
2470
- version: v.pipe(v.optional(v.boolean()), v.description("Show version number")),
2471
- watch: v.pipe(v.optional(v.boolean()), v.description("Watch files in bundle and rebuild on changes")),
2472
- ...InputCliOptionsSchema.entries,
2473
- ...OutputCliOptionsSchema.entries
2474
- });
2475
- function validateTreeShakingOptions(options) {
2476
- v.parse(TreeshakingOptionsSchema, options);
2172
+ "options",
2173
+ "outputOptions",
2174
+ "renderError",
2175
+ "renderStart",
2176
+ "resolveDynamicImport",
2177
+ "writeBundle"
2178
+ ];
2179
+ const unsupportedHooks = new Set(unsupportedHookName);
2180
+ function isUnsupportedHooks(hookName) {
2181
+ return unsupportedHooks.has(hookName);
2182
+ }
2183
+ function createComposedPlugin(plugins) {
2184
+ const names = [];
2185
+ const batchedHooks = {};
2186
+ plugins.forEach((plugin, index) => {
2187
+ const pluginName = plugin.name || `Anonymous(index: ${index})`;
2188
+ names.push(pluginName);
2189
+ t(plugin).forEach((pluginProp) => {
2190
+ if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
2191
+ if (!isPluginHookName(pluginProp)) return;
2192
+ switch (pluginProp) {
2193
+ case "buildStart": {
2194
+ const handlers = batchedHooks.buildStart ?? [];
2195
+ batchedHooks.buildStart = handlers;
2196
+ if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
2197
+ break;
2198
+ }
2199
+ case "load": {
2200
+ const handlers = batchedHooks.load ?? [];
2201
+ batchedHooks.load = handlers;
2202
+ if (plugin.load) handlers.push([plugin.load, plugin]);
2203
+ break;
2204
+ }
2205
+ case "transform": {
2206
+ const handlers = batchedHooks.transform ?? [];
2207
+ batchedHooks.transform = handlers;
2208
+ if (plugin.transform) handlers.push([plugin.transform, plugin]);
2209
+ break;
2210
+ }
2211
+ case "resolveId": {
2212
+ const handlers = batchedHooks.resolveId ?? [];
2213
+ batchedHooks.resolveId = handlers;
2214
+ if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
2215
+ break;
2216
+ }
2217
+ case "buildEnd": {
2218
+ const handlers = batchedHooks.buildEnd ?? [];
2219
+ batchedHooks.buildEnd = handlers;
2220
+ if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
2221
+ break;
2222
+ }
2223
+ case "renderChunk": {
2224
+ const handlers = batchedHooks.renderChunk ?? [];
2225
+ batchedHooks.renderChunk = handlers;
2226
+ if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
2227
+ break;
2228
+ }
2229
+ case "banner":
2230
+ case "footer":
2231
+ case "intro":
2232
+ case "outro": {
2233
+ const hook = plugin[pluginProp];
2234
+ if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
2235
+ break;
2236
+ }
2237
+ case "closeBundle": {
2238
+ const handlers = batchedHooks.closeBundle ?? [];
2239
+ batchedHooks.closeBundle = handlers;
2240
+ if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
2241
+ break;
2242
+ }
2243
+ case "watchChange": {
2244
+ const handlers = batchedHooks.watchChange ?? [];
2245
+ batchedHooks.watchChange = handlers;
2246
+ if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
2247
+ break;
2248
+ }
2249
+ case "closeWatcher": {
2250
+ const handlers = batchedHooks.closeWatcher ?? [];
2251
+ batchedHooks.closeWatcher = handlers;
2252
+ if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
2253
+ break;
2254
+ }
2255
+ default: {}
2256
+ }
2257
+ });
2258
+ });
2259
+ const composed = { name: `Composed(${names.join(", ")})` };
2260
+ const createFixedPluginResolveFnMap = new Map();
2261
+ function applyFixedPluginResolveFn(ctx, plugin) {
2262
+ const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
2263
+ if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
2264
+ return ctx;
2265
+ }
2266
+ if (batchedHooks.resolveId) {
2267
+ const batchedHandlers = batchedHooks.resolveId;
2268
+ const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
2269
+ for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
2270
+ const [_handler, plugin] = batchedHandlers[handlerIdx];
2271
+ const handlerSymbol = handlerSymbols[handlerIdx];
2272
+ const createFixedPluginResolveFn = (ctx, resolve) => {
2273
+ return (source, importer, rawContextResolveOptions) => {
2274
+ const contextResolveOptions = rawContextResolveOptions ?? {};
2275
+ if (contextResolveOptions.skipSelf) {
2276
+ contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
2277
+ contextResolveOptions.skipSelf = false;
2278
+ }
2279
+ return resolve(source, importer, contextResolveOptions);
2280
+ };
2281
+ };
2282
+ createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
2283
+ }
2284
+ composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
2285
+ const hookResolveIdOptions = rawHookResolveIdOptions;
2286
+ const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
2287
+ for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
2288
+ const [handler, plugin] = batchedHandlers[handlerIdx];
2289
+ const handlerSymbol = handlerSymbols[handlerIdx];
2290
+ if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
2291
+ const { handler: handlerFn } = normalizeHook(handler);
2292
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
2293
+ if (!isNullish(result)) return result;
2294
+ }
2295
+ };
2296
+ }
2297
+ t(batchedHooks).forEach((hookName) => {
2298
+ switch (hookName) {
2299
+ case "resolveId": break;
2300
+ case "buildStart": {
2301
+ if (batchedHooks.buildStart) {
2302
+ const batchedHandlers = batchedHooks.buildStart;
2303
+ composed.buildStart = async function(options) {
2304
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2305
+ const { handler: handlerFn } = normalizeHook(handler);
2306
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
2307
+ }));
2308
+ };
2309
+ }
2310
+ break;
2311
+ }
2312
+ case "load": {
2313
+ if (batchedHooks.load) {
2314
+ const batchedHandlers = batchedHooks.load;
2315
+ composed.load = async function(id) {
2316
+ for (const [handler, plugin] of batchedHandlers) {
2317
+ const { handler: handlerFn } = normalizeHook(handler);
2318
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id);
2319
+ if (!isNullish(result)) return result;
2320
+ }
2321
+ };
2322
+ }
2323
+ break;
2324
+ }
2325
+ case "transform": {
2326
+ if (batchedHooks.transform) {
2327
+ const batchedHandlers = batchedHooks.transform;
2328
+ composed.transform = async function(initialCode, id, moduleType) {
2329
+ let code = initialCode;
2330
+ let moduleSideEffects = void 0;
2331
+ function updateOutput(newCode, newModuleSideEffects) {
2332
+ code = newCode;
2333
+ moduleSideEffects = newModuleSideEffects ?? void 0;
2334
+ }
2335
+ for (const [handler, plugin] of batchedHandlers) {
2336
+ const { handler: handlerFn } = normalizeHook(handler);
2337
+ this.getCombinedSourcemap = () => {
2338
+ throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
2339
+ };
2340
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, id, moduleType);
2341
+ if (!isNullish(result)) {
2342
+ if (typeof result === "string") updateOutput(result);
2343
+ else if (result.code) updateOutput(result.code, result.moduleSideEffects);
2344
+ }
2345
+ }
2346
+ return {
2347
+ code,
2348
+ moduleSideEffects
2349
+ };
2350
+ };
2351
+ }
2352
+ break;
2353
+ }
2354
+ case "buildEnd": {
2355
+ if (batchedHooks.buildEnd) {
2356
+ const batchedHandlers = batchedHooks.buildEnd;
2357
+ composed.buildEnd = async function(err) {
2358
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2359
+ const { handler: handlerFn } = normalizeHook(handler);
2360
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
2361
+ }));
2362
+ };
2363
+ }
2364
+ break;
2365
+ }
2366
+ case "renderChunk": {
2367
+ if (batchedHooks.renderChunk) {
2368
+ const batchedHandlers = batchedHooks.renderChunk;
2369
+ composed.renderChunk = async function(code, chunk, options) {
2370
+ for (const [handler, plugin] of batchedHandlers) {
2371
+ const { handler: handlerFn } = normalizeHook(handler);
2372
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, chunk, options);
2373
+ if (!isNullish(result)) return result;
2374
+ }
2375
+ };
2376
+ }
2377
+ break;
2378
+ }
2379
+ case "banner":
2380
+ case "footer":
2381
+ case "intro":
2382
+ case "outro": {
2383
+ const hooks = batchedHooks[hookName];
2384
+ if (hooks?.length) composed[hookName] = async function(chunk) {
2385
+ const ret = [];
2386
+ for (const [hook, plugin] of hooks) {
2387
+ const { handler } = normalizeHook(hook);
2388
+ ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
2389
+ }
2390
+ return ret.join("\n");
2391
+ };
2392
+ break;
2393
+ }
2394
+ case "closeBundle": {
2395
+ if (batchedHooks.closeBundle) {
2396
+ const batchedHandlers = batchedHooks.closeBundle;
2397
+ composed.closeBundle = async function() {
2398
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2399
+ const { handler: handlerFn } = normalizeHook(handler);
2400
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2401
+ }));
2402
+ };
2403
+ }
2404
+ break;
2405
+ }
2406
+ case "watchChange": {
2407
+ if (batchedHooks.watchChange) {
2408
+ const batchedHandlers = batchedHooks.watchChange;
2409
+ composed.watchChange = async function(id, event) {
2410
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2411
+ const { handler: handlerFn } = normalizeHook(handler);
2412
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id, event);
2413
+ }));
2414
+ };
2415
+ }
2416
+ break;
2417
+ }
2418
+ case "closeWatcher": {
2419
+ if (batchedHooks.closeWatcher) {
2420
+ const batchedHandlers = batchedHooks.closeWatcher;
2421
+ composed.closeWatcher = async function() {
2422
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2423
+ const { handler: handlerFn } = normalizeHook(handler);
2424
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2425
+ }));
2426
+ };
2427
+ }
2428
+ break;
2429
+ }
2430
+ default: {}
2431
+ }
2432
+ });
2433
+ return composed;
2477
2434
  }
2478
- function validateCliOptions(options) {
2479
- let parsed = v.safeParse(CliOptionsSchema, options);
2480
- return [parsed.output, parsed.issues?.map((issue) => issue.path?.join(", ")).filter((v$1) => v$1 !== void 0)];
2435
+ function isComposablePlugin(plugin) {
2436
+ if (plugin instanceof BuiltinPlugin) return false;
2437
+ if ("_parallel" in plugin) return false;
2438
+ const hasNotComposablePattern = t(plugin).some((hookName) => {
2439
+ if (!isPluginHookName(hookName)) return false;
2440
+ const OK_TO_COMPOSE = false;
2441
+ if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
2442
+ if (plugin[hookName]) {
2443
+ const { meta } = normalizeHook(plugin[hookName]);
2444
+ if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
2445
+ }
2446
+ return OK_TO_COMPOSE;
2447
+ });
2448
+ if (hasNotComposablePattern) return false;
2449
+ return true;
2481
2450
  }
2482
- function getInputCliKeys() {
2483
- return v.keyof(InputCliOptionsSchema).options;
2451
+ function composeJsPlugins(plugins) {
2452
+ const newPlugins = [];
2453
+ const toBeComposed = [];
2454
+ plugins.forEach((plugin) => {
2455
+ if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
2456
+ else {
2457
+ if (toBeComposed.length > 0) {
2458
+ if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2459
+ else newPlugins.push(toBeComposed[0]);
2460
+ toBeComposed.length = 0;
2461
+ }
2462
+ newPlugins.push(plugin);
2463
+ }
2464
+ });
2465
+ if (toBeComposed.length > 0) {
2466
+ if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2467
+ else newPlugins.push(toBeComposed[0]);
2468
+ toBeComposed.length = 0;
2469
+ }
2470
+ return newPlugins;
2484
2471
  }
2485
- function getOutputCliKeys() {
2486
- return v.keyof(OutputCliOptionsSchema).options;
2472
+
2473
+ //#endregion
2474
+ //#region src/utils/initialize-parallel-plugins.ts
2475
+ async function initializeParallelPlugins(plugins) {
2476
+ const pluginInfos = [];
2477
+ for (const [index, plugin] of plugins.entries()) if ("_parallel" in plugin) {
2478
+ const { fileUrl, options } = plugin._parallel;
2479
+ pluginInfos.push({
2480
+ index,
2481
+ fileUrl,
2482
+ options
2483
+ });
2484
+ }
2485
+ if (pluginInfos.length <= 0) return void 0;
2486
+ const count = Math.min(availableParallelism(), 8);
2487
+ const parallelJsPluginRegistry = new import_binding.ParallelJsPluginRegistry(count);
2488
+ const registryId = parallelJsPluginRegistry.id;
2489
+ const workers = await initializeWorkers(registryId, count, pluginInfos);
2490
+ const stopWorkers = async () => {
2491
+ await Promise.all(workers.map((worker) => worker.terminate()));
2492
+ };
2493
+ return {
2494
+ registry: parallelJsPluginRegistry,
2495
+ stopWorkers
2496
+ };
2487
2497
  }
2488
- function getJsonSchema() {
2489
- return toJsonSchema(CliOptionsSchema);
2498
+ function initializeWorkers(registryId, count, pluginInfos) {
2499
+ return Promise.all(Array.from({ length: count }, (_, i) => initializeWorker(registryId, pluginInfos, i)));
2500
+ }
2501
+ async function initializeWorker(registryId, pluginInfos, threadNumber) {
2502
+ const urlString = import.meta.resolve("#parallel-plugin-worker");
2503
+ const workerData$1 = {
2504
+ registryId,
2505
+ pluginInfos,
2506
+ threadNumber
2507
+ };
2508
+ let worker;
2509
+ try {
2510
+ worker = new Worker(new URL(urlString), { workerData: workerData$1 });
2511
+ worker.unref();
2512
+ await new Promise((resolve, reject) => {
2513
+ worker.once("message", async (message) => {
2514
+ if (message.type === "error") reject(message.error);
2515
+ else resolve();
2516
+ });
2517
+ });
2518
+ return worker;
2519
+ } catch (e) {
2520
+ worker?.terminate();
2521
+ throw e;
2522
+ }
2490
2523
  }
2491
2524
 
2492
2525
  //#endregion
2493
2526
  //#region src/utils/create-bundler-option.ts
2494
2527
  async function createBundlerOptions(inputOptions, outputOptions, isClose) {
2495
- if (inputOptions.treeshake !== void 0) validateTreeShakingOptions(inputOptions.treeshake);
2496
2528
  const inputPlugins = await normalizePluginOption(inputOptions.plugins);
2497
2529
  const outputPlugins = await normalizePluginOption(outputOptions.plugins);
2498
2530
  const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
@@ -2554,11 +2586,13 @@ var RolldownBuild = class {
2554
2586
  return this.#bundler = await createBundler(this.#inputOptions, outputOptions, isClose);
2555
2587
  }
2556
2588
  async generate(outputOptions = {}) {
2589
+ validateOption("output", outputOptions);
2557
2590
  const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
2558
2591
  const output = await bundler.generate();
2559
2592
  return transformToRollupOutput(output);
2560
2593
  }
2561
2594
  async write(outputOptions = {}) {
2595
+ validateOption("output", outputOptions);
2562
2596
  const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
2563
2597
  const output = await bundler.write();
2564
2598
  return transformToRollupOutput(output);
@@ -2576,6 +2610,7 @@ var RolldownBuild = class {
2576
2610
  //#endregion
2577
2611
  //#region src/api/rolldown/index.ts
2578
2612
  const rolldown = async (input) => {
2613
+ validateOption("input", input);
2579
2614
  const inputOptions = await PluginDriver.callOptionsHook(input);
2580
2615
  return new RolldownBuild(inputOptions);
2581
2616
  };
@@ -2704,7 +2739,7 @@ const watch = (input) => {
2704
2739
 
2705
2740
  //#endregion
2706
2741
  //#region package.json
2707
- var version = "1.0.0-beta.3-commit.62fba31";
2742
+ var version = "1.0.0-beta.3-commit.d298c0b";
2708
2743
  var description = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.";
2709
2744
 
2710
2745
  //#endregion