rollup
55.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
#!/usr/bin/env node
/*
@license
Rollup.js v1.32.1
Fri, 06 Mar 2020 09:32:39 GMT - commit f458cbf6cb8cfcc1678593d8dc595e4b8757eb6d
https://github.com/rollup/rollup
Released under the MIT License.
*/
'use strict';
var rollup_js = require('../shared/node-entry.js');
require('util');
var path = require('path');
var fs = require('fs');
require('acorn');
require('crypto');
var events = require('events');
require('module');
var assert = require('assert');
var help = "rollup version __VERSION__\n=====================================\n\nUsage: rollup [options] <entry file>\n\nBasic options:\n\n-c, --config <filename> Use this config file (if argument is used but value\n is unspecified, defaults to rollup.config.js)\n-d, --dir <dirname> Directory for chunks (if absent, prints to stdout)\n-e, --external <ids> Comma-separate list of module IDs to exclude\n-f, --format <format> Type of output (amd, cjs, esm, iife, umd)\n-g, --globals <pairs> Comma-separate list of `moduleID:Global` pairs\n-h, --help Show this help message\n-i, --input <filename> Input (alternative to <entry file>)\n-m, --sourcemap Generate sourcemap (`-m inline` for inline map)\n-n, --name <name> Name for UMD export\n-o, --file <output> Single output file (if absent, prints to stdout)\n-p, --plugin <plugin> Use the plugin specified (may be repeated)\n-v, --version Show version number\n-w, --watch Watch files in bundle and rebuild on changes\n--amd.id <id> ID for AMD module (default is anonymous)\n--amd.define <name> Function to use in place of `define`\n--assetFileNames <pattern> Name pattern for emitted assets\n--banner <text> Code to insert at top of bundle (outside wrapper)\n--chunkFileNames <pattern> Name pattern for emitted secondary chunks\n--compact Minify wrapper code\n--context <variable> Specify top-level `this` value\n--dynamicImportFunction <name> Rename the dynamic `import()` function\n--entryFileNames <pattern> Name pattern for emitted entry chunks\n--environment <values> Settings passed to config file (see example)\n--no-esModule Do not add __esModule property\n--exports <mode> Specify export mode (auto, default, named, none)\n--extend Extend global variable defined by --name\n--no-externalLiveBindings Do not generate code to support live bindings\n--footer <text> Code to insert at end of bundle (outside wrapper)\n--no-freeze Do not freeze namespace objects\n--no-hoistTransitiveImports Do not hoist transitive imports into entry chunks\n--no-indent Don't indent result\n--no-interop Do not include interop block\n--inlineDynamicImports Create single bundle when using dynamic imports\n--intro <text> Code to insert at top of bundle (inside wrapper)\n--namespaceToStringTag Create proper `.toString` methods for namespaces\n--noConflict Generate a noConflict method for UMD globals\n--no-strict Don't emit `\"use strict\";` in the generated modules\n--outro <text> Code to insert at end of bundle (inside wrapper)\n--preferConst Use `const` instead of `var` for exports\n--preserveModules Preserve module structure\n--preserveSymlinks Do not follow symlinks when resolving files\n--shimMissingExports Create shim variables for missing exports\n--silent Don't print warnings\n--sourcemapExcludeSources Do not include source code in source maps\n--sourcemapFile <file> Specify bundle position for source maps\n--no-stdin do not read \"-\" from stdin\n--strictDeprecations Throw errors for deprecated features\n--no-treeshake Disable tree-shaking optimisations\n--no-treeshake.annotations Ignore pure call annotations\n--no-treeshake.propertyReadSideEffects Ignore property access side-effects\n--treeshake.pureExternalModules Assume side-effect free externals\n\nExamples:\n\n# use settings in config file\nrollup -c\n\n# in config file, process.env.INCLUDE_DEPS === 'true'\n# and process.env.BUILD === 'production'\nrollup -c --environment INCLUDE_DEPS,BUILD:production\n\n# create CommonJS bundle.js from src/main.js\nrollup --format=cjs --file=bundle.js -- src/main.js\n\n# create self-executing IIFE using `window.jQuery`\n# and `window._` as external globals\nrollup -f iife --globals jquery:jQuery,lodash:_ \\\n -i src/app.js -o build/app.js -m build/app.js.map\n\nNotes:\n\n* When piping to stdout, only inline sourcemaps are permitted\n\nFor more information visit https://rollupjs.org\n";
var minimist = function (args, opts) {
if (!opts)
opts = {};
var flags = { bools: {}, strings: {}, unknownFn: null };
if (typeof opts['unknown'] === 'function') {
flags.unknownFn = opts['unknown'];
}
if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
flags.allBools = true;
}
else {
[].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
flags.bools[key] = true;
});
}
var aliases = {};
Object.keys(opts.alias || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key]);
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y;
}));
});
});
[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true;
if (aliases[key]) {
flags.strings[aliases[key]] = true;
}
});
var defaults = opts['default'] || {};
var argv = { _: [] };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] === undefined ? false : defaults[key]);
});
var notFlags = [];
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--') + 1);
args = args.slice(0, args.indexOf('--'));
}
function argDefined(key, arg) {
return (flags.allBools && /^--[^=]+$/.test(arg)) ||
flags.strings[key] || flags.bools[key] || aliases[key];
}
function setArg(key, val, arg) {
if (arg && flags.unknownFn && !argDefined(key, arg)) {
if (flags.unknownFn(arg) === false)
return;
}
var value = !flags.strings[key] && isNumber(val)
? Number(val) : val;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), value);
});
}
function setKey(obj, keys, value) {
var o = obj;
keys.slice(0, -1).forEach(function (key) {
if (o[key] === undefined)
o[key] = {};
o = o[key];
});
var key = keys[keys.length - 1];
if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [o[key], value];
}
}
function aliasIsBoolean(key) {
return aliases[key].some(function (x) {
return flags.bools[x];
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (/^--.+=/.test(arg)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
var key = m[1];
var value = m[2];
if (flags.bools[key]) {
value = value !== 'false';
}
setArg(key, value, arg);
}
else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false, arg);
}
else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !/^-/.test(next)
&& !flags.bools[key]
&& !flags.allBools
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, next, arg);
i++;
}
else if (/^(true|false)$/.test(next)) {
setArg(key, next === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1, -1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
var next = arg.slice(j + 2);
if (next === '-') {
setArg(letters[j], next, arg);
continue;
}
if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
setArg(letters[j], next.split('=')[1], arg);
broken = true;
break;
}
if (/[A-Za-z]/.test(letters[j])
&& /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next, arg);
broken = true;
break;
}
if (letters[j + 1] && letters[j + 1].match(/\W/)) {
setArg(letters[j], arg.slice(j + 2), arg);
broken = true;
break;
}
else {
setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== '-') {
if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1])
&& !flags.bools[key]
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, args[i + 1], arg);
i++;
}
else if (args[i + 1] && /true|false/.test(args[i + 1])) {
setArg(key, args[i + 1] === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
}
else {
if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
}
if (opts.stopEarly) {
argv._.push.apply(argv._, args.slice(i + 1));
break;
}
}
}
Object.keys(defaults).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) {
setKey(argv, key.split('.'), defaults[key]);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), defaults[key]);
});
}
});
if (opts['--']) {
argv['--'] = new Array();
notFlags.forEach(function (key) {
argv['--'].push(key);
});
}
else {
notFlags.forEach(function (key) {
argv._.push(key);
});
}
return argv;
};
function hasKey(obj, keys) {
var o = obj;
keys.slice(0, -1).forEach(function (key) {
o = (o[key] || {});
});
var key = keys[keys.length - 1];
return key in o;
}
function isNumber(x) {
if (typeof x === 'number')
return true;
if (/^0x[0-9a-f]+$/i.test(x))
return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}
const tc = {
enabled: process.env.FORCE_COLOR ||
process.platform === "win32" ||
(process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb")
};
const Styles = (tc.Styles = {});
const defineProp = Object.defineProperty;
const init = (style, open, close, re) => {
let i, len = 1, seq = [(Styles[style] = { open, close, re })];
const fn = s => {
if (tc.enabled) {
for (i = 0, s += ""; i < len; i++) {
style = seq[i];
s =
(open = style.open) +
(~s.indexOf((close = style.close), 4) // skip first \x1b[
? s.replace(style.re, open)
: s) +
close;
}
len = 1;
}
return s;
};
defineProp(tc, style, {
get: () => {
for (let k in Styles)
defineProp(fn, k, {
get: () => ((seq[len++] = Styles[k]), fn)
});
delete tc[style];
return (tc[style] = fn);
},
configurable: true
});
};
init("reset", "\x1b[0m", "\x1b[0m", /\x1b\[0m/g);
init("bold", "\x1b[1m", "\x1b[22m", /\x1b\[22m/g);
init("dim", "\x1b[2m", "\x1b[22m", /\x1b\[22m/g);
init("italic", "\x1b[3m", "\x1b[23m", /\x1b\[23m/g);
init("underline", "\x1b[4m", "\x1b[24m", /\x1b\[24m/g);
init("inverse", "\x1b[7m", "\x1b[27m", /\x1b\[27m/g);
init("hidden", "\x1b[8m", "\x1b[28m", /\x1b\[28m/g);
init("strikethrough", "\x1b[9m", "\x1b[29m", /\x1b\[29m/g);
init("black", "\x1b[30m", "\x1b[39m", /\x1b\[39m/g);
init("red", "\x1b[31m", "\x1b[39m", /\x1b\[39m/g);
init("green", "\x1b[32m", "\x1b[39m", /\x1b\[39m/g);
init("yellow", "\x1b[33m", "\x1b[39m", /\x1b\[39m/g);
init("blue", "\x1b[34m", "\x1b[39m", /\x1b\[39m/g);
init("magenta", "\x1b[35m", "\x1b[39m", /\x1b\[39m/g);
init("cyan", "\x1b[36m", "\x1b[39m", /\x1b\[39m/g);
init("white", "\x1b[37m", "\x1b[39m", /\x1b\[39m/g);
init("gray", "\x1b[90m", "\x1b[39m", /\x1b\[39m/g);
init("bgBlack", "\x1b[40m", "\x1b[49m", /\x1b\[49m/g);
init("bgRed", "\x1b[41m", "\x1b[49m", /\x1b\[49m/g);
init("bgGreen", "\x1b[42m", "\x1b[49m", /\x1b\[49m/g);
init("bgYellow", "\x1b[43m", "\x1b[49m", /\x1b\[49m/g);
init("bgBlue", "\x1b[44m", "\x1b[49m", /\x1b\[49m/g);
init("bgMagenta", "\x1b[45m", "\x1b[49m", /\x1b\[49m/g);
init("bgCyan", "\x1b[46m", "\x1b[49m", /\x1b\[49m/g);
init("bgWhite", "\x1b[47m", "\x1b[49m", /\x1b\[49m/g);
var turbocolor = tc;
// @see https://no-color.org
// @see https://www.npmjs.com/package/chalk
if (process.env.FORCE_COLOR === '0' || process.env.NO_COLOR) {
turbocolor.enabled = false;
}
// log to stderr to keep `rollup main.js > bundle.js` from breaking
const stderr = console.error.bind(console);
function handleError(err, recover = false) {
let description = err.message || err;
if (err.name)
description = `${err.name}: ${description}`;
const message = (err.plugin
? `(plugin ${(err).plugin}) ${description}`
: description) || err;
stderr(turbocolor.bold.red(`[!] ${turbocolor.bold(message.toString())}`));
if (err.url) {
stderr(turbocolor.cyan(err.url));
}
if (err.loc) {
stderr(`${rollup_js.relativeId((err.loc.file || err.id))} (${err.loc.line}:${err.loc.column})`);
}
else if (err.id) {
stderr(rollup_js.relativeId(err.id));
}
if (err.frame) {
stderr(turbocolor.dim(err.frame));
}
if (err.stack) {
stderr(turbocolor.dim(err.stack));
}
stderr('');
if (!recover)
process.exit(1);
}
function batchWarnings() {
let deferredWarnings = new Map();
let count = 0;
return {
get count() {
return count;
},
add: (warning) => {
count += 1;
if (warning.code in deferredHandlers) {
if (!deferredWarnings.has(warning.code))
deferredWarnings.set(warning.code, []);
deferredWarnings.get(warning.code).push(warning);
}
else if (warning.code in immediateHandlers) {
immediateHandlers[warning.code](warning);
}
else {
title(warning.message);
if (warning.url)
info(warning.url);
const id = (warning.loc && warning.loc.file) || warning.id;
if (id) {
const loc = warning.loc
? `${rollup_js.relativeId(id)}: (${warning.loc.line}:${warning.loc.column})`
: rollup_js.relativeId(id);
stderr(turbocolor.bold(rollup_js.relativeId(loc)));
}
if (warning.frame)
info(warning.frame);
}
},
flush: () => {
if (count === 0)
return;
const codes = Array.from(deferredWarnings.keys()).sort((a, b) => deferredWarnings.get(b).length - deferredWarnings.get(a).length);
for (const code of codes) {
deferredHandlers[code](deferredWarnings.get(code));
}
deferredWarnings = new Map();
count = 0;
}
};
}
const immediateHandlers = {
UNKNOWN_OPTION: warning => {
title(`You have passed an unrecognized option`);
stderr(warning.message);
},
MISSING_NODE_BUILTINS: warning => {
title(`Missing shims for Node.js built-ins`);
const detail = warning.modules.length === 1
? `'${warning.modules[0]}'`
: `${warning
.modules.slice(0, -1)
.map((name) => `'${name}'`)
.join(', ')} and '${warning.modules.slice(-1)}'`;
stderr(`Creating a browser bundle that depends on ${detail}. You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins`);
}
};
const deferredHandlers = {
CIRCULAR_DEPENDENCY(warnings) {
title(`Circular dependenc${warnings.length > 1 ? 'ies' : 'y'}`);
const displayed = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
for (const warning of displayed) {
stderr(warning.cycle.join(' -> '));
}
if (warnings.length > displayed.length) {
stderr(`...and ${warnings.length - displayed.length} more`);
}
},
EMPTY_BUNDLE(warnings) {
title(`Generated${warnings.length === 1 ? ' an' : ''} empty ${warnings.length > 1 ? 'chunks' : 'chunk'}`);
stderr(warnings.map(warning => warning.chunkName).join(', '));
},
EVAL(warnings) {
title('Use of eval is strongly discouraged');
info('https://rollupjs.org/guide/en/#avoiding-eval');
showTruncatedWarnings(warnings);
},
MISSING_EXPORT(warnings) {
title('Missing exports');
info('https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module');
for (const warning of warnings) {
stderr(turbocolor.bold(warning.importer));
stderr(`${warning.missing} is not exported by ${warning.exporter}`);
stderr(turbocolor.gray(warning.frame));
}
},
MISSING_GLOBAL_NAME(warnings) {
title(`Missing global variable ${warnings.length > 1 ? 'names' : 'name'}`);
stderr(`Use output.globals to specify browser global variable names corresponding to external modules`);
for (const warning of warnings) {
stderr(`${turbocolor.bold(warning.source)} (guessing '${warning.guess}')`);
}
},
MIXED_EXPORTS: (warnings) => {
title('Mixing named and default exports');
info(`https://rollupjs.org/guide/en/#output-exports`);
stderr(turbocolor.bold('The following entry modules are using named and default exports together:'));
const displayedWarnings = warnings.length > 5 ? warnings.slice(0, 3) : warnings;
for (const warning of displayedWarnings) {
stderr(rollup_js.relativeId(warning.id));
}
if (displayedWarnings.length < warnings.length) {
stderr(`...and ${warnings.length - displayedWarnings.length} other entry modules`);
}
stderr(`\nConsumers of your bundle will have to use chunk['default'] to access their default export, which may not be what you want. Use \`output.exports: 'named'\` to disable this warning`);
},
NAMESPACE_CONFLICT(warnings) {
title(`Conflicting re-exports`);
for (const warning of warnings) {
stderr(`${turbocolor.bold(rollup_js.relativeId(warning.reexporter))} re-exports '${warning.name}' from both ${rollup_js.relativeId(warning.sources[0])} and ${rollup_js.relativeId(warning.sources[1])} (will be ignored)`);
}
},
NON_EXISTENT_EXPORT(warnings) {
title(`Import of non-existent ${warnings.length > 1 ? 'exports' : 'export'}`);
showTruncatedWarnings(warnings);
},
PLUGIN_WARNING(warnings) {
const nestedByPlugin = nest(warnings, 'plugin');
for (const { key: plugin, items } of nestedByPlugin) {
const nestedByMessage = nest(items, 'message');
let lastUrl = '';
for (const { key: message, items } of nestedByMessage) {
title(`Plugin ${plugin}: ${message}`);
for (const warning of items) {
if (warning.url && warning.url !== lastUrl)
info((lastUrl = warning.url));
if (warning.id) {
let loc = rollup_js.relativeId(warning.id);
if (warning.loc) {
loc += `: (${warning.loc.line}:${warning.loc.column})`;
}
stderr(turbocolor.bold(loc));
}
if (warning.frame)
info(warning.frame);
}
}
}
},
SOURCEMAP_BROKEN(warnings) {
title(`Broken sourcemap`);
info('https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect');
const plugins = Array.from(new Set(warnings.map(w => w.plugin).filter(Boolean)));
const detail = plugins.length > 1
? ` (such as ${plugins
.slice(0, -1)
.map(p => `'${p}'`)
.join(', ')} and '${plugins.slice(-1)}')`
: ` (such as '${plugins[0]}')`;
stderr(`Plugins that transform code${detail} should generate accompanying sourcemaps`);
},
THIS_IS_UNDEFINED(warnings) {
title('`this` has been rewritten to `undefined`');
info('https://rollupjs.org/guide/en/#error-this-is-undefined');
showTruncatedWarnings(warnings);
},
UNRESOLVED_IMPORT(warnings) {
title('Unresolved dependencies');
info('https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency');
const dependencies = new Map();
for (const warning of warnings) {
if (!dependencies.has(warning.source))
dependencies.set(warning.source, []);
dependencies.get(warning.source).push(warning.importer);
}
for (const dependency of dependencies.keys()) {
const importers = dependencies.get(dependency);
stderr(`${turbocolor.bold(dependency)} (imported by ${importers.join(', ')})`);
}
},
UNUSED_EXTERNAL_IMPORT(warnings) {
title('Unused external imports');
for (const warning of warnings) {
stderr(`${warning.names} imported from external module '${warning.source}' but never used`);
}
}
};
function title(str) {
stderr(`${turbocolor.bold.yellow('(!)')} ${turbocolor.bold.yellow(str)}`);
}
function info(url) {
stderr(turbocolor.gray(url));
}
function nest(array, prop) {
const nested = [];
const lookup = new Map();
for (const item of array) {
const key = item[prop];
if (!lookup.has(key)) {
lookup.set(key, {
items: [],
key
});
nested.push(lookup.get(key));
}
lookup.get(key).items.push(item);
}
return nested;
}
function showTruncatedWarnings(warnings) {
const nestedByModule = nest(warnings, 'id');
const displayedByModule = nestedByModule.length > 5 ? nestedByModule.slice(0, 3) : nestedByModule;
for (const { key: id, items } of displayedByModule) {
stderr(turbocolor.bold(rollup_js.relativeId(id)));
stderr(turbocolor.gray(items[0].frame));
if (items.length > 1) {
stderr(`...and ${items.length - 1} other ${items.length > 2 ? 'occurrences' : 'occurrence'}`);
}
}
if (nestedByModule.length > displayedByModule.length) {
stderr(`\n...and ${nestedByModule.length - displayedByModule.length} other files`);
}
}
var parseMs = milliseconds => {
if (typeof milliseconds !== 'number') {
throw new TypeError('Expected a number');
}
const roundTowardsZero = milliseconds > 0 ? Math.floor : Math.ceil;
return {
days: roundTowardsZero(milliseconds / 86400000),
hours: roundTowardsZero(milliseconds / 3600000) % 24,
minutes: roundTowardsZero(milliseconds / 60000) % 60,
seconds: roundTowardsZero(milliseconds / 1000) % 60,
milliseconds: roundTowardsZero(milliseconds) % 1000,
microseconds: roundTowardsZero(milliseconds * 1000) % 1000,
nanoseconds: roundTowardsZero(milliseconds * 1e6) % 1000
};
};
const pluralize = (word, count) => count === 1 ? word : word + 's';
var prettyMs = (milliseconds, options = {}) => {
if (!Number.isFinite(milliseconds)) {
throw new TypeError('Expected a finite number');
}
if (options.colonNotation) {
options.compact = false;
options.formatSubMilliseconds = false;
options.separateMilliseconds = false;
options.verbose = false;
}
if (options.compact) {
options.secondsDecimalDigits = 0;
options.millisecondsDecimalDigits = 0;
}
const result = [];
const add = (value, long, short, valueString) => {
if ((result.length === 0 || !options.colonNotation) && value === 0 && !(options.colonNotation && short === 'm')) {
return;
}
valueString = (valueString || value || '0').toString();
let prefix;
let suffix;
if (options.colonNotation) {
prefix = result.length > 0 ? ':' : '';
suffix = '';
const wholeDigits = valueString.includes('.') ? valueString.split('.')[0].length : valueString.length;
const minLength = result.length > 0 ? 2 : 1;
valueString = '0'.repeat(Math.max(0, minLength - wholeDigits)) + valueString;
}
else {
prefix = '';
suffix = options.verbose ? ' ' + pluralize(long, value) : short;
}
result.push(prefix + valueString + suffix);
};
const secondsDecimalDigits = typeof options.secondsDecimalDigits === 'number' ?
options.secondsDecimalDigits :
1;
if (secondsDecimalDigits < 1) {
const difference = 1000 - (milliseconds % 1000);
if (difference < 500) {
milliseconds += difference;
}
}
const parsed = parseMs(milliseconds);
add(Math.trunc(parsed.days / 365), 'year', 'y');
add(parsed.days % 365, 'day', 'd');
add(parsed.hours, 'hour', 'h');
add(parsed.minutes, 'minute', 'm');
if (options.separateMilliseconds ||
options.formatSubMilliseconds ||
milliseconds < 1000) {
add(parsed.seconds, 'second', 's');
if (options.formatSubMilliseconds) {
add(parsed.milliseconds, 'millisecond', 'ms');
add(parsed.microseconds, 'microsecond', 'µs');
add(parsed.nanoseconds, 'nanosecond', 'ns');
}
else {
const millisecondsAndBelow = parsed.milliseconds +
(parsed.microseconds / 1000) +
(parsed.nanoseconds / 1e6);
const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === 'number' ?
options.millisecondsDecimalDigits :
0;
const millisecondsString = millisecondsDecimalDigits ?
millisecondsAndBelow.toFixed(millisecondsDecimalDigits) :
Math.ceil(millisecondsAndBelow);
add(parseFloat(millisecondsString, 10), 'millisecond', 'ms', millisecondsString);
}
}
else {
const seconds = (milliseconds / 1000) % 60;
const secondsDecimalDigits = typeof options.secondsDecimalDigits === 'number' ?
options.secondsDecimalDigits :
1;
const secondsFixed = seconds.toFixed(secondsDecimalDigits);
const secondsString = options.keepDecimalsOnWholeSeconds ?
secondsFixed :
secondsFixed.replace(/\.0+$/, '');
add(parseFloat(secondsString, 10), 'second', 's', secondsString);
}
if (result.length === 0) {
return '0' + (options.verbose ? ' milliseconds' : 'ms');
}
if (options.compact) {
return '~' + result[0];
}
if (typeof options.unitCount === 'number') {
return '~' + result.slice(0, Math.max(options.unitCount, 1)).join(' ');
}
return options.colonNotation ? result.join('') : result.join(' ');
};
let SOURCEMAPPING_URL = 'sourceMa';
SOURCEMAPPING_URL += 'ppingURL';
var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;
const BYTE_UNITS = [
'B',
'kB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB'
];
const BIT_UNITS = [
'b',
'kbit',
'Mbit',
'Gbit',
'Tbit',
'Pbit',
'Ebit',
'Zbit',
'Ybit'
];
/*
Formats the given number using `Number#toLocaleString`.
- If locale is a string, the value is expected to be a locale-key (for example: `de`).
- If locale is true, the system default locale is used for translation.
- If no value for locale is specified, the number is returned unmodified.
*/
const toLocaleString = (number, locale) => {
let result = number;
if (typeof locale === 'string') {
result = number.toLocaleString(locale);
}
else if (locale === true) {
result = number.toLocaleString();
}
return result;
};
var prettyBytes = (number, options) => {
if (!Number.isFinite(number)) {
throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`);
}
options = Object.assign({ bits: false }, options);
const UNITS = options.bits ? BIT_UNITS : BYTE_UNITS;
if (options.signed && number === 0) {
return ' 0 ' + UNITS[0];
}
const isNegative = number < 0;
const prefix = isNegative ? '-' : (options.signed ? '+' : '');
if (isNegative) {
number = -number;
}
if (number < 1) {
const numberString = toLocaleString(number, options.locale);
return prefix + numberString + ' ' + UNITS[0];
}
const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);
// eslint-disable-next-line unicorn/prefer-exponentiation-operator
number = Number((number / Math.pow(1000, exponent)).toPrecision(3));
const numberString = toLocaleString(number, options.locale);
const unit = UNITS[exponent];
return prefix + numberString + ' ' + unit;
};
function printTimings(timings) {
Object.keys(timings).forEach(label => {
const color = label[0] === '#' ? (label[1] !== '#' ? turbocolor.underline : turbocolor.bold) : (text) => text;
const [time, memory, total] = timings[label];
const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes(memory)} / ${prettyBytes(total)}`;
console.info(color(row));
});
}
function build(inputOptions, outputOptions, warnings, silent = false) {
const useStdout = !outputOptions[0].file && !outputOptions[0].dir;
const start = Date.now();
const files = useStdout ? ['stdout'] : outputOptions.map(t => rollup_js.relativeId(t.file || t.dir));
if (!silent) {
let inputFiles;
if (typeof inputOptions.input === 'string') {
inputFiles = inputOptions.input;
}
else if (inputOptions.input instanceof Array) {
inputFiles = inputOptions.input.join(', ');
}
else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) {
inputFiles = Object.keys(inputOptions.input)
.map(name => inputOptions.input[name])
.join(', ');
}
stderr(turbocolor.cyan(`\n${turbocolor.bold(inputFiles)} → ${turbocolor.bold(files.join(', '))}...`));
}
return rollup_js.rollup(inputOptions)
.then((bundle) => {
if (useStdout) {
const output = outputOptions[0];
if (output.sourcemap && output.sourcemap !== 'inline') {
handleError({
code: 'MISSING_OUTPUT_OPTION',
message: 'You must specify a --file (-o) option when creating a file with a sourcemap'
});
}
return bundle.generate(output).then(({ output: outputs }) => {
for (const file of outputs) {
let source;
if (file.type === 'asset') {
source = file.source;
}
else {
source = file.code;
if (output.sourcemap === 'inline') {
source += `\n//# ${SOURCEMAPPING_URL$1}=${file.map.toUrl()}\n`;
}
}
if (outputs.length > 1)
process.stdout.write('\n' + turbocolor.cyan(turbocolor.bold('//→ ' + file.fileName + ':')) + '\n');
process.stdout.write(source);
}
return null;
});
}
return Promise.all(outputOptions.map(output => bundle.write(output))).then(() => bundle);
})
.then((bundle) => {
if (!silent) {
warnings.flush();
stderr(turbocolor.green(`created ${turbocolor.bold(files.join(', '))} in ${turbocolor.bold(prettyMs(Date.now() - start))}`));
if (bundle && bundle.getTimings) {
printTimings(bundle.getTimings());
}
}
});
}
function loadConfigFile(configFile, commandOptions = {}) {
const silent = commandOptions.silent || false;
const warnings = batchWarnings();
return rollup_js.rollup({
external: (id) => (id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json',
input: configFile,
onwarn: warnings.add,
treeshake: false
})
.then((bundle) => {
if (!silent && warnings.count > 0) {
stderr(turbocolor.bold(`loaded ${rollup_js.relativeId(configFile)} with warnings`));
warnings.flush();
}
return bundle.generate({
exports: 'named',
format: 'cjs'
});
})
.then(({ output: [{ code }] }) => {
// temporarily override require
const extension = path.extname(configFile);
const defaultLoader = require.extensions[extension];
require.extensions[extension] = (module, filename) => {
if (filename === configFile) {
module._compile(code, filename);
}
else {
defaultLoader(module, filename);
}
};
delete require.cache[configFile];
return Promise.resolve(require(configFile))
.then(configFileContent => {
if (configFileContent.default)
configFileContent = configFileContent.default;
if (typeof configFileContent === 'function') {
return configFileContent(commandOptions);
}
return configFileContent;
})
.then(configs => {
if (Object.keys(configs).length === 0) {
handleError({
code: 'MISSING_CONFIG',
message: 'Config file must export an options object, or an array of options objects',
url: 'https://rollupjs.org/guide/en/#configuration-files'
});
}
require.extensions[extension] = defaultLoader;
return Array.isArray(configs) ? configs : [configs];
});
});
}
const stdinName = '-';
let stdinResult = null;
function stdinPlugin() {
return {
name: 'stdin',
resolveId(id) {
if (id === stdinName) {
return id;
}
},
load(id) {
if (id === stdinName) {
return stdinResult || (stdinResult = readStdin());
}
}
};
}
function readStdin() {
return new Promise((resolve, reject) => {
const chunks = [];
process.stdin.setEncoding('utf8');
process.stdin
.on('data', chunk => chunks.push(chunk))
.on('end', () => {
const result = chunks.join('');
resolve(result);
})
.on('error', err => {
reject(err);
});
});
}
var timeZone = date => {
const offset = (date || new Date()).getTimezoneOffset();
const absOffset = Math.abs(offset);
const hours = Math.floor(absOffset / 60);
const minutes = absOffset % 60;
const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';
return (offset < 0 ? '+' : '-') + hours + minutesOut;
};
const dateTime = options => {
options = Object.assign({
date: new Date(),
local: true,
showTimeZone: false,
showMilliseconds: false
}, options);
let { date } = options;
if (options.local) {
// Offset the date so it will return the correct value when getting the ISO string
date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));
}
let end = '';
if (options.showTimeZone) {
end = ' UTC' + (options.local ? timeZone(date) : '');
}
if (options.showMilliseconds && date.getUTCMilliseconds() > 0) {
end = ` ${date.getUTCMilliseconds()}ms${end}`;
}
return date
.toISOString()
.replace(/T/, ' ')
.replace(/\..+/, end);
};
var dateTime_1 = dateTime;
// TODO: Remove this for the next major release
var default_1 = dateTime;
dateTime_1.default = default_1;
var signals = rollup_js.createCommonjsModule(function (module) {
// This is not the set of all possible signals.
//
// It IS, however, the set of all signals that trigger
// an exit on either Linux or BSD systems. Linux is a
// superset of the signal names supported on BSD, and
// the unknown signals just fail to register, so we can
// catch that easily enough.
//
// Don't bother with SIGKILL. It's uncatchable, which
// means that we can't fire any callbacks anyway.
//
// If a user does happen to register a handler on a non-
// fatal signal like SIGWINCH or something, and then
// exit, it'll end up firing `process.emit('exit')`, so
// the handler will be fired anyway.
//
// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
// artificially, inherently leave the process in a
// state from which it is not safe to try and enter JS
// listeners.
module.exports = [
'SIGABRT',
'SIGALRM',
'SIGHUP',
'SIGINT',
'SIGTERM'
];
if (process.platform !== 'win32') {
module.exports.push('SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
);
}
if (process.platform === 'linux') {
module.exports.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED');
}
});
// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.
var signals$1 = signals;
var EE = events;
/* istanbul ignore if */
if (typeof EE !== 'function') {
EE = EE.EventEmitter;
}
var emitter;
if (process.__signal_exit_emitter__) {
emitter = process.__signal_exit_emitter__;
}
else {
emitter = process.__signal_exit_emitter__ = new EE();
emitter.count = 0;
emitter.emitted = {};
}
// Because this emitter is a global, we have to check to see if a
// previous version of this library failed to enable infinite listeners.
// I know what you're about to say. But literally everything about
// signal-exit is a compromise with evil. Get used to it.
if (!emitter.infinite) {
emitter.setMaxListeners(Infinity);
emitter.infinite = true;
}
var signalExit = function (cb, opts) {
assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
if (loaded === false) {
load();
}
var ev = 'exit';
if (opts && opts.alwaysLast) {
ev = 'afterexit';
}
var remove = function () {
emitter.removeListener(ev, cb);
if (emitter.listeners('exit').length === 0 &&
emitter.listeners('afterexit').length === 0) {
unload();
}
};
emitter.on(ev, cb);
return remove;
};
var unload_1 = unload;
function unload() {
if (!loaded) {
return;
}
loaded = false;
signals$1.forEach(function (sig) {
try {
process.removeListener(sig, sigListeners[sig]);
}
catch (er) { }
});
process.emit = originalProcessEmit;
process.reallyExit = originalProcessReallyExit;
emitter.count -= 1;
}
function emit(event, code, signal) {
if (emitter.emitted[event]) {
return;
}
emitter.emitted[event] = true;
emitter.emit(event, code, signal);
}
// { <signal>: <listener fn>, ... }
var sigListeners = {};
signals$1.forEach(function (sig) {
sigListeners[sig] = function listener() {
// If there are no other listeners, an exit is coming!
// Simplest way: remove us and then re-send the signal.
// We know that this will kill the process, so we can
// safely emit now.
var listeners = process.listeners(sig);
if (listeners.length === emitter.count) {
unload();
emit('exit', null, sig);
/* istanbul ignore next */
emit('afterexit', null, sig);
/* istanbul ignore next */
process.kill(process.pid, sig);
}
};
});
var signals_1 = function () {
return signals$1;
};
var load_1 = load;
var loaded = false;
function load() {
if (loaded) {
return;
}
loaded = true;
// This is the number of onSignalExit's that are in play.
// It's important so that we can count the correct number of
// listeners on signals, and don't wait for the other one to
// handle it instead of us.
emitter.count += 1;
signals$1 = signals$1.filter(function (sig) {
try {
process.on(sig, sigListeners[sig]);
return true;
}
catch (er) {
return false;
}
});
process.emit = processEmit;
process.reallyExit = processReallyExit;
}
var originalProcessReallyExit = process.reallyExit;
function processReallyExit(code) {
process.exitCode = code || 0;
emit('exit', process.exitCode, null);
/* istanbul ignore next */
emit('afterexit', process.exitCode, null);
/* istanbul ignore next */
originalProcessReallyExit.call(process, process.exitCode);
}
var originalProcessEmit = process.emit;
function processEmit(ev, arg) {
if (ev === 'exit') {
if (arg !== undefined) {
process.exitCode = arg;
}
var ret = originalProcessEmit.apply(this, arguments);
emit('exit', process.exitCode, null);
/* istanbul ignore next */
emit('afterexit', process.exitCode, null);
return ret;
}
else {
return originalProcessEmit.apply(this, arguments);
}
}
signalExit.unload = unload_1;
signalExit.signals = signals_1;
signalExit.load = load_1;
const CLEAR_SCREEN = '\u001Bc';
function getResetScreen(clearScreen) {
if (clearScreen) {
return (heading) => stderr(CLEAR_SCREEN + heading);
}
let firstRun = true;
return (heading) => {
if (firstRun) {
stderr(heading);
firstRun = false;
}
};
}
function watch(configFile, configs, command, silent = false) {
const isTTY = Boolean(process.stderr.isTTY);
const warnings = batchWarnings();
const initialConfigs = processConfigs(configs);
const clearScreen = initialConfigs.every(config => config.watch.clearScreen !== false);
const resetScreen = getResetScreen(isTTY && clearScreen);
let watcher;
let configWatcher;
function processConfigs(configs) {
return configs.map(options => {
const merged = rollup_js.mergeOptions({
command,
config: options,
defaultOnWarnHandler: warnings.add
});
const result = Object.assign(Object.assign({}, merged.inputOptions), { output: merged.outputOptions });
if (!result.watch)
result.watch = {};
if (merged.optionError)
merged.inputOptions.onwarn({
code: 'UNKNOWN_OPTION',
message: merged.optionError
});
return result;
});
}
function start(configs) {
watcher = rollup_js.watch(configs);
watcher.on('event', event => {
switch (event.code) {
case 'ERROR':
warnings.flush();
handleError(event.error, true);
break;
case 'START':
if (!silent) {
resetScreen(turbocolor.underline(`rollup v${rollup_js.version}`));
}
break;
case 'BUNDLE_START':
if (!silent) {
let input = event.input;
if (typeof input !== 'string') {
input = Array.isArray(input)
? input.join(', ')
: Object.keys(input)
.map(key => input[key])
.join(', ');
}
stderr(turbocolor.cyan(`bundles ${turbocolor.bold(input)} → ${turbocolor.bold(event.output.map(rollup_js.relativeId).join(', '))}...`));
}
break;
case 'BUNDLE_END':
warnings.flush();
if (!silent)
stderr(turbocolor.green(`created ${turbocolor.bold(event.output.map(rollup_js.relativeId).join(', '))} in ${turbocolor.bold(prettyMs(event.duration))}`));
if (event.result && event.result.getTimings) {
printTimings(event.result.getTimings());
}
break;
case 'END':
if (!silent && isTTY) {
stderr(`\n[${dateTime_1()}] waiting for changes...`);
}
}
});
}
// catch ctrl+c, kill, and uncaught errors
const removeOnExit = signalExit(close);
process.on('uncaughtException', close);
// only listen to stdin if it is a pipe
if (!process.stdin.isTTY) {
process.stdin.on('end', close); // in case we ever support stdin!
}
function close(err) {
removeOnExit();
process.removeListener('uncaughtException', close);
// removing a non-existent listener is a no-op
process.stdin.removeListener('end', close);
if (watcher)
watcher.close();
if (configWatcher)
configWatcher.close();
if (err) {
console.error(err);
process.exit(1);
}
}
try {
start(initialConfigs);
}
catch (err) {
close(err);
return;
}
if (configFile && !configFile.startsWith('node:')) {
let restarting = false;
let aborted = false;
let configFileData = fs.readFileSync(configFile, 'utf-8');
const restart = () => {
const newConfigFileData = fs.readFileSync(configFile, 'utf-8');
if (newConfigFileData === configFileData)
return;
configFileData = newConfigFileData;
if (restarting) {
aborted = true;
return;
}
restarting = true;
loadConfigFile(configFile, command)
.then(() => {
restarting = false;
if (aborted) {
aborted = false;
restart();
}
else {
watcher.close();
start(initialConfigs);
}
})
.catch((err) => {
handleError(err, true);
});
};
configWatcher = fs.watch(configFile, (event) => {
if (event === 'change')
restart();
});
}
}
function runRollup(command) {
let inputSource;
if (command._.length > 0) {
if (command.input) {
handleError({
code: 'DUPLICATE_IMPORT_OPTIONS',
message: 'use --input, or pass input path as argument'
});
}
inputSource = command._;
}
else if (typeof command.input === 'string') {
inputSource = [command.input];
}
else {
inputSource = command.input;
}
if (inputSource && inputSource.length > 0) {
if (inputSource.some((input) => input.indexOf('=') !== -1)) {
command.input = {};
inputSource.forEach((input) => {
const equalsIndex = input.indexOf('=');
const value = input.substr(equalsIndex + 1);
let key = input.substr(0, equalsIndex);
if (!key)
key = rollup_js.getAliasName(input);
command.input[key] = value;
});
}
else {
command.input = inputSource;
}
}
if (command.environment) {
const environment = Array.isArray(command.environment)
? command.environment
: [command.environment];
environment.forEach((arg) => {
arg.split(',').forEach((pair) => {
const [key, ...value] = pair.split(':');
if (value.length) {
process.env[key] = value.join(':');
}
else {
process.env[key] = String(true);
}
});
});
}
let configFile = command.config === true ? 'rollup.config.js' : command.config;
if (configFile) {
if (configFile.slice(0, 5) === 'node:') {
const pkgName = configFile.slice(5);
try {
configFile = rollup_js.relative.resolve(`rollup-config-${pkgName}`, process.cwd());
}
catch (err) {
try {
configFile = rollup_js.relative.resolve(pkgName, process.cwd());
}
catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
handleError({
code: 'MISSING_EXTERNAL_CONFIG',
message: `Could not resolve config file ${configFile}`
});
}
throw err;
}
}
}
else {
// find real path of config so it matches what Node provides to callbacks in require.extensions
configFile = fs.realpathSync(configFile);
}
if (command.watch)
process.env.ROLLUP_WATCH = 'true';
return loadConfigFile(configFile, command)
.then(configs => execute(configFile, configs, command))
.catch(handleError);
}
else {
if (!command.input && (command.stdin || !process.stdin.isTTY)) {
command.input = stdinName;
}
return execute(configFile, [{ input: [] }], command);
}
}
function execute(configFile, configs, command) {
return rollup_js.__awaiter(this, void 0, void 0, function* () {
if (command.watch) {
watch(configFile, configs, command, command.silent);
}
else {
for (const config of configs) {
const warnings = batchWarnings();
try {
const { inputOptions, outputOptions, optionError } = rollup_js.mergeOptions({
command,
config,
defaultOnWarnHandler: warnings.add
});
if (optionError) {
inputOptions.onwarn({ code: 'UNKNOWN_OPTION', message: optionError });
}
if (command.stdin !== false) {
inputOptions.plugins.push(stdinPlugin());
}
if (command.plugin) {
const plugins = Array.isArray(command.plugin) ? command.plugin : [command.plugin];
for (const plugin of plugins) {
if (/[={}]/.test(plugin)) {
// -p plugin=value
// -p "{transform(c,i){...}}"
loadAndRegisterPlugin(inputOptions, plugin);
}
else {
// split out plugins joined by commas
// -p node-resolve,commonjs,buble
plugin
.split(',')
.forEach((plugin) => loadAndRegisterPlugin(inputOptions, plugin));
}
}
}
yield build(inputOptions, outputOptions, warnings, command.silent);
}
catch (err) {
warnings.flush();
handleError(err);
}
}
}
});
}
function loadAndRegisterPlugin(inputOptions, pluginText) {
let plugin = null;
let pluginArg = undefined;
if (pluginText[0] === '{') {
// -p "{transform(c,i){...}}"
plugin = new Function('return ' + pluginText);
}
else {
const match = pluginText.match(/^([@.\/\\\w|^{}|-]+)(=(.*))?$/);
if (match) {
// -p plugin
// -p plugin=arg
pluginText = match[1];
pluginArg = new Function('return ' + match[3])();
}
else {
throw new Error(`Invalid --plugin argument format: ${JSON.stringify(pluginText)}`);
}
if (!/^\.|^rollup-plugin-|[@\/\\]/.test(pluginText)) {
// Try using plugin prefix variations first if applicable.
// Prefix order is significant - left has higher precedence.
for (const prefix of ['@rollup/plugin-', 'rollup-plugin-']) {
try {
plugin = require(prefix + pluginText);
break;
}
catch (ex) {
// if this does not work, we try requiring the actual name below
}
}
}
if (!plugin) {
try {
if (pluginText[0] == '.')
pluginText = path.resolve(pluginText);
plugin = require(pluginText);
}
catch (ex) {
throw new Error(`Cannot load plugin "${pluginText}"`);
}
}
}
if (typeof plugin === 'object' && pluginText in plugin) {
// some plugins do not use `export default` for their entry point.
// attempt to use the plugin name as the named import name.
plugin = plugin[pluginText];
}
inputOptions.plugins.push(typeof plugin === 'function' ? plugin.call(plugin, pluginArg) : plugin);
}
const command = minimist(process.argv.slice(2), {
alias: rollup_js.commandAliases
});
if (command.help || (process.argv.length <= 2 && process.stdin.isTTY)) {
console.log(`\n${help.replace('__VERSION__', rollup_js.version)}\n`);
}
else if (command.version) {
console.log(`rollup v${rollup_js.version}`);
}
else {
try {
require('source-map-support').install();
}
catch (err) {
// do nothing
}
runRollup(command);
}
//# sourceMappingURL=rollup.map