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