UNPKG

167 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var path = require('path');
6var fs = require('fs');
7var url$1 = require('url');
8var util = require('util');
9var https = require('https');
10
11function _typeof(obj) {
12 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
13 _typeof = function (obj) {
14 return typeof obj;
15 };
16 } else {
17 _typeof = function (obj) {
18 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
19 };
20 }
21
22 return _typeof(obj);
23}
24
25function _defineProperty(obj, key, value) {
26 if (key in obj) {
27 Object.defineProperty(obj, key, {
28 value: value,
29 enumerable: true,
30 configurable: true,
31 writable: true
32 });
33 } else {
34 obj[key] = value;
35 }
36
37 return obj;
38}
39
40function ownKeys(object, enumerableOnly) {
41 var keys = Object.keys(object);
42
43 if (Object.getOwnPropertySymbols) {
44 var symbols = Object.getOwnPropertySymbols(object);
45 if (enumerableOnly) symbols = symbols.filter(function (sym) {
46 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
47 });
48 keys.push.apply(keys, symbols);
49 }
50
51 return keys;
52}
53
54function _objectSpread2(target) {
55 for (var i = 1; i < arguments.length; i++) {
56 var source = arguments[i] != null ? arguments[i] : {};
57
58 if (i % 2) {
59 ownKeys(source, true).forEach(function (key) {
60 _defineProperty(target, key, source[key]);
61 });
62 } else if (Object.getOwnPropertyDescriptors) {
63 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
64 } else {
65 ownKeys(source).forEach(function (key) {
66 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
67 });
68 }
69 }
70
71 return target;
72}
73
74function _objectWithoutPropertiesLoose(source, excluded) {
75 if (source == null) return {};
76 var target = {};
77 var sourceKeys = Object.keys(source);
78 var key, i;
79
80 for (i = 0; i < sourceKeys.length; i++) {
81 key = sourceKeys[i];
82 if (excluded.indexOf(key) >= 0) continue;
83 target[key] = source[key];
84 }
85
86 return target;
87}
88
89function _objectWithoutProperties(source, excluded) {
90 if (source == null) return {};
91
92 var target = _objectWithoutPropertiesLoose(source, excluded);
93
94 var key, i;
95
96 if (Object.getOwnPropertySymbols) {
97 var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
98
99 for (i = 0; i < sourceSymbolKeys.length; i++) {
100 key = sourceSymbolKeys[i];
101 if (excluded.indexOf(key) >= 0) continue;
102 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
103 target[key] = source[key];
104 }
105 }
106
107 return target;
108}
109
110function _toConsumableArray(arr) {
111 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
112}
113
114function _arrayWithoutHoles(arr) {
115 if (Array.isArray(arr)) {
116 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
117
118 return arr2;
119 }
120}
121
122function _iterableToArray(iter) {
123 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
124}
125
126function _nonIterableSpread() {
127 throw new TypeError("Invalid attempt to spread non-iterable instance");
128}
129
130// eslint-disable-next-line no-undef
131if ((typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis)) !== "object") {
132 var globalObject;
133
134 if (undefined) {
135 globalObject = undefined;
136 } else {
137 // eslint-disable-next-line no-extend-native
138 Object.defineProperty(Object.prototype, "__global__", {
139 get: function get() {
140 return this;
141 },
142 configurable: true
143 }); // eslint-disable-next-line no-undef
144
145 globalObject = __global__;
146 delete Object.prototype.__global__;
147 }
148
149 globalObject.globalThis = globalObject;
150}
151
152var startsWithWindowsDriveLetter = function startsWithWindowsDriveLetter(string) {
153 var firstChar = string[0];
154 if (!/[a-zA-Z]/.test(firstChar)) return false;
155 var secondChar = string[1];
156 if (secondChar !== ":") return false;
157 return true;
158};
159
160var replaceSlashesWithBackSlashes = function replaceSlashesWithBackSlashes(string) {
161 return string.replace(/\//g, "\\");
162};
163
164var pathnameToOperatingSystemPath = function pathnameToOperatingSystemPath(pathname) {
165 if (pathname[0] !== "/") throw new Error("pathname must start with /, got ".concat(pathname));
166 var pathnameWithoutLeadingSlash = pathname.slice(1);
167
168 if (startsWithWindowsDriveLetter(pathnameWithoutLeadingSlash) && pathnameWithoutLeadingSlash[2] === "/") {
169 return replaceSlashesWithBackSlashes(pathnameWithoutLeadingSlash);
170 } // linux mac pathname === operatingSystemFilename
171
172
173 return pathname;
174};
175
176var isWindowsPath = function isWindowsPath(path) {
177 return startsWithWindowsDriveLetter(path) && path[2] === "\\";
178};
179
180var replaceBackSlashesWithSlashes = function replaceBackSlashesWithSlashes(string) {
181 return string.replace(/\\/g, "/");
182};
183
184var operatingSystemPathToPathname = function operatingSystemPathToPathname(operatingSystemPath) {
185 if (isWindowsPath(operatingSystemPath)) {
186 return "/".concat(replaceBackSlashesWithSlashes(operatingSystemPath));
187 } // linux and mac operatingSystemFilename === pathname
188
189
190 return operatingSystemPath;
191};
192
193var pathnameToRelativePathname = function pathnameToRelativePathname(pathname, otherPathname) {
194 return pathname.slice(otherPathname.length);
195};
196
197// copied from
198// https://github.com/babel/babel/blob/85ea5b0b50bca952b26f895e56bf2165ab9fcc92/packages/babel-preset-env/data/plugins.json#L1
199// Because this is an hidden implementation detail of @babel/preset-env
200// it could be deprecated or moved anytime.
201// For that reason it makes more sens to have it inlined here
202// than importing it from an undocumented location.
203// Ideally it would be documented or a separate module
204var babelCompatMap = {
205 "transform-template-literals": {
206 chrome: "41",
207 edge: "13",
208 firefox: "34",
209 safari: "9",
210 node: "4",
211 ios: "9",
212 opera: "28",
213 electron: "0.24"
214 },
215 "transform-literals": {
216 chrome: "44",
217 edge: "12",
218 firefox: "53",
219 safari: "9",
220 node: "4",
221 ios: "9",
222 opera: "31",
223 electron: "0.31"
224 },
225 "transform-function-name": {
226 chrome: "51",
227 firefox: "53",
228 safari: "10",
229 node: "6.5",
230 ios: "10",
231 opera: "38",
232 electron: "1.2"
233 },
234 "transform-arrow-functions": {
235 chrome: "47",
236 edge: "13",
237 firefox: "45",
238 safari: "10",
239 node: "6",
240 ios: "10",
241 opera: "34",
242 electron: "0.36"
243 },
244 "transform-block-scoped-functions": {
245 chrome: "41",
246 edge: "12",
247 firefox: "46",
248 safari: "10",
249 node: "4",
250 ie: "11",
251 ios: "10",
252 opera: "28",
253 electron: "0.24"
254 },
255 "transform-classes": {
256 chrome: "46",
257 edge: "13",
258 firefox: "45",
259 safari: "10",
260 node: "5",
261 ios: "10",
262 opera: "33",
263 electron: "0.36"
264 },
265 "transform-object-super": {
266 chrome: "46",
267 edge: "13",
268 firefox: "45",
269 safari: "10",
270 node: "5",
271 ios: "10",
272 opera: "33",
273 electron: "0.36"
274 },
275 "transform-shorthand-properties": {
276 chrome: "43",
277 edge: "12",
278 firefox: "33",
279 safari: "9",
280 node: "4",
281 ios: "9",
282 opera: "30",
283 electron: "0.29"
284 },
285 "transform-duplicate-keys": {
286 chrome: "42",
287 edge: "12",
288 firefox: "34",
289 safari: "9",
290 node: "4",
291 ios: "9",
292 opera: "29",
293 electron: "0.27"
294 },
295 "transform-computed-properties": {
296 chrome: "44",
297 edge: "12",
298 firefox: "34",
299 safari: "7.1",
300 node: "4",
301 ios: "8",
302 opera: "31",
303 electron: "0.31"
304 },
305 "transform-for-of": {
306 chrome: "51",
307 edge: "15",
308 firefox: "53",
309 safari: "10",
310 node: "6.5",
311 ios: "10",
312 opera: "38",
313 electron: "1.2"
314 },
315 "transform-sticky-regex": {
316 chrome: "49",
317 edge: "13",
318 firefox: "3",
319 safari: "10",
320 node: "6",
321 ios: "10",
322 opera: "36",
323 electron: "1"
324 },
325 "transform-dotall-regex": {
326 chrome: "62",
327 safari: "11.1",
328 node: "8.10",
329 ios: "11.3",
330 opera: "49",
331 electron: "3"
332 },
333 "transform-unicode-regex": {
334 chrome: "50",
335 edge: "13",
336 firefox: "46",
337 safari: "10",
338 node: "6",
339 ios: "10",
340 opera: "37",
341 electron: "1.1"
342 },
343 "transform-spread": {
344 chrome: "46",
345 edge: "13",
346 firefox: "36",
347 safari: "10",
348 node: "5",
349 ios: "10",
350 opera: "33",
351 electron: "0.36"
352 },
353 "transform-parameters": {
354 chrome: "49",
355 edge: "14",
356 firefox: "53",
357 safari: "10",
358 node: "6",
359 ios: "10",
360 opera: "36",
361 electron: "1"
362 },
363 "transform-destructuring": {
364 chrome: "51",
365 firefox: "53",
366 safari: "10",
367 node: "6.5",
368 ios: "10",
369 opera: "38",
370 electron: "1.2"
371 },
372 "transform-block-scoping": {
373 chrome: "49",
374 edge: "14",
375 firefox: "51",
376 safari: "10",
377 node: "6",
378 ios: "10",
379 opera: "36",
380 electron: "1"
381 },
382 "transform-typeof-symbol": {
383 chrome: "38",
384 edge: "12",
385 firefox: "36",
386 safari: "9",
387 node: "0.12",
388 ios: "9",
389 opera: "25",
390 electron: "0.2"
391 },
392 "transform-new-target": {
393 chrome: "46",
394 edge: "14",
395 firefox: "41",
396 safari: "10",
397 node: "5",
398 ios: "10",
399 opera: "33",
400 electron: "0.36"
401 },
402 "transform-regenerator": {
403 chrome: "50",
404 edge: "13",
405 firefox: "53",
406 safari: "10",
407 node: "6",
408 ios: "10",
409 opera: "37",
410 electron: "1.1"
411 },
412 "transform-exponentiation-operator": {
413 chrome: "52",
414 edge: "14",
415 firefox: "52",
416 safari: "10.1",
417 node: "7",
418 ios: "10.3",
419 opera: "39",
420 electron: "1.3"
421 },
422 "transform-async-to-generator": {
423 chrome: "55",
424 edge: "15",
425 firefox: "52",
426 safari: "10.1",
427 node: "7.6",
428 ios: "10.3",
429 opera: "42",
430 electron: "1.6"
431 },
432 // copy of transform-async-to-generator
433 // this is not in the babel-preset-env repo
434 // but we need this
435 "transform-async-to-promises": {
436 chrome: "55",
437 edge: "15",
438 firefox: "52",
439 safari: "10.1",
440 node: "7.6",
441 ios: "10.3",
442 opera: "42",
443 electron: "1.6"
444 },
445 "proposal-async-generator-functions": {
446 chrome: "63",
447 firefox: "57",
448 safari: "12",
449 opera: "50",
450 electron: "3"
451 },
452 "proposal-object-rest-spread": {
453 chrome: "60",
454 firefox: "55",
455 safari: "11.1",
456 node: "8.3",
457 ios: "11.3",
458 opera: "47",
459 electron: "2"
460 },
461 "proposal-unicode-property-regex": {
462 chrome: "64",
463 safari: "11.1",
464 ios: "11.3",
465 opera: "51",
466 electron: "3"
467 },
468 "proposal-json-strings": {},
469 "proposal-optional-catch-binding": {
470 chrome: "66",
471 firefox: "58",
472 safari: "11.1",
473 ios: "11.3",
474 opera: "53",
475 electron: "3"
476 }
477};
478
479// we could reuse this to get a list of polyfill
480// using https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/built-ins.json#L1
481// adding a featureNameArray to every group
482// and according to that featureNameArray, add these polyfill
483// to the generated bundle
484var polyfillCompatMap = {};
485
486var valueToVersion = function valueToVersion(value) {
487 if (typeof value === "number") {
488 return numberToVersion(value);
489 }
490
491 if (typeof value === "string") {
492 return stringToVersion(value);
493 }
494
495 throw new TypeError(createValueErrorMessage({
496 version: value
497 }));
498};
499
500var numberToVersion = function numberToVersion(number) {
501 return {
502 major: number,
503 minor: 0,
504 patch: 0
505 };
506};
507
508var stringToVersion = function stringToVersion(string) {
509 if (string.indexOf(".") > -1) {
510 var parts = string.split(".");
511 return {
512 major: Number(parts[0]),
513 minor: parts[1] ? Number(parts[1]) : 0,
514 patch: parts[2] ? Number(parts[2]) : 0
515 };
516 }
517
518 if (isNaN(string)) {
519 return {
520 major: 0,
521 minor: 0,
522 patch: 0
523 };
524 }
525
526 return {
527 major: Number(string),
528 minor: 0,
529 patch: 0
530 };
531};
532
533var createValueErrorMessage = function createValueErrorMessage(_ref) {
534 var value = _ref.value;
535 return "value must be a number or a string.\nvalue: ".concat(value);
536};
537
538var versionCompare = function versionCompare(versionA, versionB) {
539 var semanticVersionA = valueToVersion(versionA);
540 var semanticVersionB = valueToVersion(versionB);
541 var majorDiff = semanticVersionA.major - semanticVersionB.major;
542
543 if (majorDiff > 0) {
544 return majorDiff;
545 }
546
547 if (majorDiff < 0) {
548 return majorDiff;
549 }
550
551 var minorDiff = semanticVersionA.minor - semanticVersionB.minor;
552
553 if (minorDiff > 0) {
554 return minorDiff;
555 }
556
557 if (minorDiff < 0) {
558 return minorDiff;
559 }
560
561 var patchDiff = semanticVersionA.patch - semanticVersionB.patch;
562
563 if (patchDiff > 0) {
564 return patchDiff;
565 }
566
567 if (patchDiff < 0) {
568 return patchDiff;
569 }
570
571 return 0;
572};
573
574var versionIsBelow = function versionIsBelow(versionSupposedBelow, versionSupposedAbove) {
575 return versionCompare(versionSupposedBelow, versionSupposedAbove) < 0;
576};
577
578var findHighestVersion = function findHighestVersion() {
579 for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
580 values[_key] = arguments[_key];
581 }
582
583 if (values.length === 0) throw new Error("missing argument");
584 return values.reduce(function (highestVersion, value) {
585 if (versionIsBelow(highestVersion, value)) {
586 return value;
587 }
588
589 return highestVersion;
590 });
591};
592
593var computeIncompatibleNameArray = function computeIncompatibleNameArray(_ref) {
594 var featureCompatMap = _ref.featureCompatMap,
595 platformName = _ref.platformName,
596 platformVersion = _ref.platformVersion;
597 var incompatibleNameArray = [];
598 Object.keys(featureCompatMap).forEach(function (featureName) {
599 var compatible = platformIsCompatibleWithFeature({
600 platformName: platformName,
601 platformVersion: platformVersion,
602 featureCompat: featureName in featureCompatMap ? featureCompatMap[featureName] : {}
603 });
604
605 if (!compatible) {
606 incompatibleNameArray.push(featureName);
607 }
608 });
609 return incompatibleNameArray;
610};
611
612var platformIsCompatibleWithFeature = function platformIsCompatibleWithFeature(_ref2) {
613 var platformName = _ref2.platformName,
614 platformVersion = _ref2.platformVersion,
615 featureCompat = _ref2.featureCompat;
616 var platformCompatibleVersion = computePlatformCompatibleVersion({
617 featureCompat: featureCompat,
618 platformName: platformName
619 });
620 var highestVersion = findHighestVersion(platformVersion, platformCompatibleVersion);
621 return highestVersion === platformVersion;
622};
623
624var computePlatformCompatibleVersion = function computePlatformCompatibleVersion(_ref3) {
625 var featureCompat = _ref3.featureCompat,
626 platformName = _ref3.platformName;
627 return platformName in featureCompat ? featureCompat[platformName] : "Infinity";
628};
629
630var generatePlatformGroupArray = function generatePlatformGroupArray(_ref) {
631 var featureCompatMap = _ref.featureCompatMap,
632 platformName = _ref.platformName;
633 var featureNameArray = Object.keys(featureCompatMap);
634 var featureNameArrayWithCompat = featureNameArray.filter(function (featureName) {
635 return platformName in featureCompatMap[featureName];
636 });
637 var versionArray = featureNameArrayWithCompat // why do I convert them to string, well ok let's keep it like that
638 .map(function (featureName) {
639 return String(featureCompatMap[featureName][platformName]);
640 }).concat("0.0.0") // at least version 0
641 // filter is to have unique version I guess
642 .filter(function (version, index, array) {
643 return array.indexOf(version) === index;
644 }).sort(versionCompare);
645 var platformGroupArray = [];
646 versionArray.forEach(function (version) {
647 var incompatibleNameArray = computeIncompatibleNameArray({
648 featureCompatMap: featureCompatMap,
649 platformName: platformName,
650 platformVersion: version
651 }).sort();
652 var groupWithSameIncompatibleFeatures = platformGroupArray.find(function (platformGroup) {
653 return platformGroup.incompatibleNameArray.join("") === incompatibleNameArray.join("");
654 });
655
656 if (groupWithSameIncompatibleFeatures) {
657 groupWithSameIncompatibleFeatures.platformCompatMap[platformName] = findHighestVersion(groupWithSameIncompatibleFeatures.platformCompatMap[platformName], version);
658 } else {
659 platformGroupArray.push({
660 incompatibleNameArray: incompatibleNameArray.slice(),
661 platformCompatMap: _defineProperty({}, platformName, version)
662 });
663 }
664 });
665 return platformGroupArray;
666};
667
668var composePlatformCompatMap = function composePlatformCompatMap(platformCompatMap, secondPlatformCompatMap) {
669 return objectComposeValue(normalizePlatformCompatMapVersions(platformCompatMap), normalizePlatformCompatMapVersions(secondPlatformCompatMap), function (version, secondVersion) {
670 return findHighestVersion(version, secondVersion);
671 });
672};
673
674var normalizePlatformCompatMapVersions = function normalizePlatformCompatMapVersions(platformCompatibility) {
675 return objectMapValue(platformCompatibility, function (version) {
676 return String(version);
677 });
678};
679
680var objectMapValue = function objectMapValue(object, callback) {
681 var mapped = {};
682 Object.keys(object).forEach(function (key) {
683 mapped[key] = callback(object[key], key, object);
684 });
685 return mapped;
686};
687
688var objectComposeValue = function objectComposeValue(previous, object, callback) {
689 var composed = _objectSpread2({}, previous);
690
691 Object.keys(object).forEach(function (key) {
692 composed[key] = key in composed ? callback(composed[key], object[key]) : object[key];
693 });
694 return composed;
695};
696
697var composeGroupArray = function composeGroupArray() {
698 for (var _len = arguments.length, arrayOfGroupArray = new Array(_len), _key = 0; _key < _len; _key++) {
699 arrayOfGroupArray[_key] = arguments[_key];
700 }
701
702 return arrayOfGroupArray.reduce(groupArrayReducer, []);
703};
704
705var groupArrayReducer = function groupArrayReducer(previousGroupArray, groupArray) {
706 var reducedGroupArray = [];
707 previousGroupArray.forEach(function (group) {
708 reducedGroupArray.push({
709 incompatibleNameArray: group.incompatibleNameArray.slice(),
710 platformCompatMap: _objectSpread2({}, group.platformCompatMap)
711 });
712 });
713 groupArray.forEach(function (group) {
714 var groupWithSameIncompatibleFeature = reducedGroupArray.find(function (existingGroupCandidate) {
715 return groupHaveSameIncompatibleFeatures(group, existingGroupCandidate);
716 });
717
718 if (groupWithSameIncompatibleFeature) {
719 groupWithSameIncompatibleFeature.platformCompatMap = composePlatformCompatMap(groupWithSameIncompatibleFeature.platformCompatMap, group.platformCompatMap);
720 } else {
721 reducedGroupArray.push({
722 incompatibleNameArray: group.incompatibleNameArray.slice(),
723 platformCompatMap: _objectSpread2({}, group.platformCompatMap)
724 });
725 }
726 });
727 return reducedGroupArray;
728};
729
730var groupHaveSameIncompatibleFeatures = function groupHaveSameIncompatibleFeatures(groupA, groupB) {
731 return groupA.incompatibleNameArray.join("") === groupB.incompatibleNameArray.join("");
732};
733
734var generateAllPlatformGroupArray = function generateAllPlatformGroupArray(_ref) {
735 var featureCompatMap = _ref.featureCompatMap,
736 platformNames = _ref.platformNames;
737 var arrayOfGroupArray = platformNames.map(function (platformName) {
738 return generatePlatformGroupArray({
739 featureCompatMap: featureCompatMap,
740 platformName: platformName
741 });
742 });
743 var groupArray = composeGroupArray.apply(void 0, _toConsumableArray(arrayOfGroupArray));
744 return groupArray;
745};
746
747var platformCompatMapToScore = function platformCompatMapToScore(platformCompatMap, platformScoreMap) {
748 return Object.keys(platformCompatMap).reduce(function (previous, platformName) {
749 var platformVersion = platformCompatMap[platformName];
750 return previous + platformToScore(platformName, platformVersion, platformScoreMap);
751 }, 0);
752};
753
754var platformToScore = function platformToScore(platformName, platformVersion, platformScoreMap) {
755 if (platformName in platformScoreMap === false) return platformScoreMap.other || 0;
756 var versionUsageMap = platformScoreMap[platformName];
757 var versionArray = Object.keys(versionUsageMap);
758 if (versionArray.length === 0) return platformScoreMap.other || 0;
759 var versionArrayAscending = versionArray.sort(versionCompare);
760 var highestVersion = versionArrayAscending[versionArray.length - 1];
761 if (findHighestVersion(platformVersion, highestVersion) === platformVersion) return versionUsageMap[highestVersion];
762 var closestVersion = versionArrayAscending.reverse().find(function (version) {
763 return findHighestVersion(platformVersion, version) === platformVersion;
764 });
765 if (!closestVersion) return platformScoreMap.other || 0;
766 return versionUsageMap[closestVersion];
767};
768
769var BEST_ID = "best";
770var OTHERWISE_ID = "otherwise";
771
772var generateGroupMap = function generateGroupMap(_ref) {
773 var babelPluginMap = _ref.babelPluginMap,
774 _ref$babelCompatMap = _ref.babelCompatMap,
775 babelCompatMap$1 = _ref$babelCompatMap === void 0 ? babelCompatMap : _ref$babelCompatMap,
776 _ref$polyfillConfigMa = _ref.polyfillConfigMap,
777 polyfillConfigMap = _ref$polyfillConfigMa === void 0 ? {} : _ref$polyfillConfigMa,
778 _ref$polyfillCompatMa = _ref.polyfillCompatMap,
779 polyfillCompatMap$1 = _ref$polyfillCompatMa === void 0 ? polyfillCompatMap : _ref$polyfillCompatMa,
780 platformScoreMap = _ref.platformScoreMap,
781 _ref$groupCount = _ref.groupCount,
782 groupCount = _ref$groupCount === void 0 ? 1 : _ref$groupCount,
783 _ref$platformAlwaysIn = _ref.platformAlwaysInsidePlatformScoreMap,
784 platformAlwaysInsidePlatformScoreMap = _ref$platformAlwaysIn === void 0 ? false : _ref$platformAlwaysIn,
785 _ref$platformWillAlwa = _ref.platformWillAlwaysBeKnown,
786 platformWillAlwaysBeKnown = _ref$platformWillAlwa === void 0 ? false : _ref$platformWillAlwa;
787 var groupMap = generateFeatureGroupMap({
788 // here we should throw if key conflict between babelPluginMap/polyfillConfigMap
789 featureConfigMap: _objectSpread2({}, babelPluginMap, {}, polyfillConfigMap),
790 // here we should throw if key conflict on babelCompatMap/polyfillCompatMap
791 featureCompatMap: _objectSpread2({}, babelCompatMap$1, {}, polyfillCompatMap$1),
792 platformScoreMap: platformScoreMap,
793 groupCount: groupCount,
794 platformAlwaysInsidePlatformScoreMap: platformAlwaysInsidePlatformScoreMap,
795 platformWillAlwaysBeKnown: platformWillAlwaysBeKnown
796 });
797 return groupMap;
798};
799
800var generateFeatureGroupMap = function generateFeatureGroupMap(_ref2) {
801 var featureConfigMap = _ref2.featureConfigMap,
802 featureCompatMap = _ref2.featureCompatMap,
803 platformScoreMap = _ref2.platformScoreMap,
804 groupCount = _ref2.groupCount,
805 platformAlwaysInsidePlatformScoreMap = _ref2.platformAlwaysInsidePlatformScoreMap,
806 platformWillAlwaysBeKnown = _ref2.platformWillAlwaysBeKnown;
807 if (_typeof(featureConfigMap) !== "object") throw new TypeError("featureConfigMap must be an object, got ".concat(featureConfigMap));
808 if (_typeof(featureCompatMap) !== "object") throw new TypeError("featureCompatMap must be an object, got ".concat(featureCompatMap));
809 if (_typeof(platformScoreMap) !== "object") throw new TypeError("platformScoreMap must be an object, got ".concat(platformScoreMap));
810 if (_typeof(groupCount) < 1) throw new TypeError("groupCount must be above 1, got ".concat(groupCount));
811 var featureNameArray = Object.keys(featureConfigMap);
812 var groupWithoutFeature = {
813 incompatibleNameArray: featureNameArray,
814 platformCompatMap: {} // when we create one group and we cannot ensure
815 // code will be runned on a platform inside platformScoreMap
816 // then we return otherwise group to be safe
817
818 };
819
820 if (groupCount === 1 && !platformAlwaysInsidePlatformScoreMap) {
821 return _defineProperty({}, OTHERWISE_ID, groupWithoutFeature);
822 }
823
824 var featureCompatMapWithoutHole = {};
825 featureNameArray.forEach(function (featureName) {
826 featureCompatMapWithoutHole[featureName] = featureName in featureCompatMap ? featureCompatMap[featureName] : {};
827 });
828 var allPlatformGroupArray = generateAllPlatformGroupArray({
829 featureCompatMap: featureCompatMapWithoutHole,
830 platformNames: arrayWithoutValue(Object.keys(platformScoreMap), "other")
831 });
832
833 if (allPlatformGroupArray.length === 0) {
834 return _defineProperty({}, OTHERWISE_ID, groupWithoutFeature);
835 }
836
837 var groupToScore = function groupToScore(_ref5) {
838 var platformCompatMap = _ref5.platformCompatMap;
839 return platformCompatMapToScore(platformCompatMap, platformScoreMap);
840 };
841
842 var allPlatformGroupArraySortedByScore = allPlatformGroupArray.sort(function (a, b) {
843 return groupToScore(b) - groupToScore(a);
844 });
845 var length = allPlatformGroupArraySortedByScore.length; // if we arrive here and want a single group
846 // we take the worst group and consider it's our best group
847 // because it's the lowest platform we want to support
848
849 if (groupCount === 1) {
850 return _defineProperty({}, BEST_ID, allPlatformGroupArraySortedByScore[length - 1]);
851 }
852
853 var addOtherwiseToBeSafe = !platformAlwaysInsidePlatformScoreMap || !platformWillAlwaysBeKnown;
854 var lastGroupIndex = addOtherwiseToBeSafe ? groupCount - 1 : groupCount;
855 var groupArray = length + 1 > groupCount ? allPlatformGroupArraySortedByScore.slice(0, lastGroupIndex) : allPlatformGroupArraySortedByScore;
856 var groupMap = {};
857 groupArray.forEach(function (group, index) {
858 if (index === 0) {
859 groupMap[BEST_ID] = group;
860 } else {
861 groupMap["intermediate-".concat(index + 1)] = group;
862 }
863 });
864
865 if (addOtherwiseToBeSafe) {
866 groupMap[OTHERWISE_ID] = groupWithoutFeature;
867 }
868
869 return groupMap;
870};
871
872var arrayWithoutValue = function arrayWithoutValue(array, value) {
873 return array.filter(function (valueCandidate) {
874 return valueCandidate !== value;
875 });
876};
877
878var browserScoreMap = {
879 // https://www.statista.com/statistics/268299/most-popular-internet-browsers/
880 // this source of stat is what I found in 5min
881 // we could improve these default usage score using better stats
882 // and keep in mind this should be updated time to time or even better
883 // come from your specific audience
884 android: 0.001,
885 chrome: {
886 "71": 0.3,
887 "69": 0.19,
888 "0": 0.01 // it means oldest version of chrome will get a score of 0.01
889
890 },
891 firefox: {
892 "61": 0.3
893 },
894 edge: {
895 "12": 0.1
896 },
897 electron: 0.001,
898 ios: 0.001,
899 opera: 0.001,
900 other: 0.001,
901 safari: {
902 "10": 0.1
903 }
904};
905
906// https://nodejs.org/metrics/summaries/version/nodejs.org-access.log.csv
907var nodeVersionScoreMap = {
908 "0.10": 0.02,
909 "0.12": 0.01,
910 4: 0.1,
911 6: 0.25,
912 7: 0.1,
913 8: 1,
914 9: 0.1,
915 10: 0.5,
916 11: 0.25
917};
918
919// TODO: externalize this into '@dmail/helper'
920// import { arrayWithout } from '@dmail/helper'
921var arrayWithout = function arrayWithout(array, item) {
922 var arrayWithoutItem = [];
923 var i = 0;
924
925 while (i < array.length) {
926 var value = array[i];
927 i++;
928
929 if (value === item) {
930 continue;
931 }
932
933 arrayWithoutItem.push(value);
934 }
935
936 return arrayWithoutItem;
937};
938
939var createCancelError = function createCancelError(reason) {
940 var cancelError = new Error("canceled because ".concat(reason));
941 cancelError.name = "CANCEL_ERROR";
942 cancelError.reason = reason;
943 return cancelError;
944};
945var isCancelError = function isCancelError(value) {
946 return value && _typeof(value) === "object" && value.name === "CANCEL_ERROR";
947};
948var createCancellationSource = function createCancellationSource() {
949 var requested = false;
950 var cancelError;
951 var registrationArray = [];
952
953 var cancel = function cancel(reason) {
954 if (requested) return;
955 requested = true;
956 cancelError = createCancelError(reason);
957 var registrationArrayCopy = registrationArray.slice();
958 registrationArray.length = 0;
959 registrationArrayCopy.forEach(function (registration) {
960 registration.callback(cancelError); // const removedDuringCall = registrationArray.indexOf(registration) === -1
961 });
962 };
963
964 var register = function register(callback) {
965 if (typeof callback !== "function") {
966 throw new Error("callback must be a function, got ".concat(callback));
967 }
968
969 var existingRegistration = registrationArray.find(function (registration) {
970 return registration.callback === callback;
971 }); // don't register twice
972
973 if (existingRegistration) {
974 return existingRegistration;
975 }
976
977 var registration = {
978 callback: callback,
979 unregister: function unregister() {
980 registrationArray = arrayWithout(registrationArray, registration);
981 }
982 };
983 registrationArray = [registration].concat(_toConsumableArray(registrationArray));
984 return registration;
985 };
986
987 var throwIfRequested = function throwIfRequested() {
988 if (requested) {
989 throw cancelError;
990 }
991 };
992
993 return {
994 token: {
995 register: register,
996
997 get cancellationRequested() {
998 return requested;
999 },
1000
1001 throwIfRequested: throwIfRequested
1002 },
1003 cancel: cancel
1004 };
1005};
1006var createCancellationToken = function createCancellationToken() {
1007 var register = function register(callback) {
1008 if (typeof callback !== "function") {
1009 throw new Error("callback must be a function, got ".concat(callback));
1010 }
1011
1012 return {
1013 callback: callback,
1014 unregister: function unregister() {}
1015 };
1016 };
1017
1018 var throwIfRequested = function throwIfRequested() {
1019 return undefined;
1020 };
1021
1022 return {
1023 register: register,
1024 cancellationRequested: false,
1025 throwIfRequested: throwIfRequested
1026 };
1027};
1028
1029var createOperation = function createOperation(_ref) {
1030 var _ref$cancellationToke = _ref.cancellationToken,
1031 cancellationToken = _ref$cancellationToke === void 0 ? createCancellationToken() : _ref$cancellationToke,
1032 start = _ref.start,
1033 rest = _objectWithoutProperties(_ref, ["cancellationToken", "start"]);
1034
1035 ensureExactParameters(rest);
1036 cancellationToken.throwIfRequested();
1037 var promise = new Promise(function (resolve) {
1038 resolve(start());
1039 });
1040 var cancelPromise = new Promise(function (resolve, reject) {
1041 var cancelRegistration = cancellationToken.register(function (cancelError) {
1042 cancelRegistration.unregister();
1043 reject(cancelError);
1044 });
1045 promise.then(cancelRegistration.unregister, function () {});
1046 });
1047 var operationPromise = Promise.race([promise, cancelPromise]);
1048 return operationPromise;
1049};
1050
1051var ensureExactParameters = function ensureExactParameters(extraParameters) {
1052 var extraParamNames = Object.keys(extraParameters);
1053 if (extraParamNames.length) throw new Error("createOperation expect only cancellationToken, start. Got ".concat(extraParamNames));
1054};
1055
1056var catchAsyncFunctionCancellation = function catchAsyncFunctionCancellation(asyncFunction) {
1057 return asyncFunction().catch(function (error) {
1058 if (isCancelError(error)) return;
1059 throw error;
1060 });
1061};
1062var createProcessInterruptionCancellationToken = function createProcessInterruptionCancellationToken() {
1063 var SIGINTCancelSource = createCancellationSource();
1064 process.on("SIGINT", function () {
1065 return SIGINTCancelSource.cancel("process interruption");
1066 });
1067 return SIGINTCancelSource.token;
1068};
1069
1070var hrefToScheme = function hrefToScheme(href) {
1071 var colonIndex = href.indexOf(":");
1072 if (colonIndex === -1) return "";
1073 return href.slice(0, colonIndex);
1074};
1075
1076var hrefToOrigin = function hrefToOrigin(href) {
1077 var scheme = hrefToScheme(href);
1078
1079 if (scheme === "file") {
1080 return "file://";
1081 }
1082
1083 if (scheme === "http" || scheme === "https") {
1084 var secondProtocolSlashIndex = scheme.length + "://".length;
1085 var pathnameSlashIndex = href.indexOf("/", secondProtocolSlashIndex);
1086 if (pathnameSlashIndex === -1) return href;
1087 return href.slice(0, pathnameSlashIndex);
1088 }
1089
1090 return href.slice(0, scheme.length + 1);
1091};
1092
1093var hrefToPathname = function hrefToPathname(href) {
1094 return ressourceToPathname(hrefToRessource(href));
1095};
1096
1097var hrefToRessource = function hrefToRessource(href) {
1098 var scheme = hrefToScheme(href);
1099
1100 if (scheme === "file") {
1101 return href.slice("file://".length);
1102 }
1103
1104 if (scheme === "https" || scheme === "http") {
1105 // remove origin
1106 var afterProtocol = href.slice(scheme.length + "://".length);
1107 var pathnameSlashIndex = afterProtocol.indexOf("/", "://".length);
1108 return afterProtocol.slice(pathnameSlashIndex);
1109 }
1110
1111 return href.slice(scheme.length + 1);
1112};
1113
1114var ressourceToPathname = function ressourceToPathname(ressource) {
1115 var searchSeparatorIndex = ressource.indexOf("?");
1116 return searchSeparatorIndex === -1 ? ressource : ressource.slice(0, searchSeparatorIndex);
1117};
1118
1119var pathnameIsInside = function pathnameIsInside(pathname, otherPathname) {
1120 return pathname.startsWith("".concat(otherPathname, "/"));
1121};
1122
1123var pathnameToDirname = function pathnameToDirname(pathname) {
1124 var slashLastIndex = pathname.lastIndexOf("/");
1125 if (slashLastIndex === -1) return "";
1126 return pathname.slice(0, slashLastIndex);
1127};
1128
1129var pathnameToExtension = function pathnameToExtension(pathname) {
1130 var slashLastIndex = pathname.lastIndexOf("/");
1131
1132 if (slashLastIndex !== -1) {
1133 pathname = pathname.slice(slashLastIndex + 1);
1134 }
1135
1136 var dotLastIndex = pathname.lastIndexOf(".");
1137 if (dotLastIndex === -1) return ""; // if (dotLastIndex === pathname.length - 1) return ""
1138
1139 return pathname.slice(dotLastIndex);
1140};
1141
1142var pathnameToRelativePath = function pathnameToRelativePath(pathname, otherPathname) {
1143 return pathname.slice(otherPathname.length);
1144};
1145
1146var assertImportMap = function assertImportMap(value) {
1147 if (value === null) {
1148 throw new TypeError("an importMap must be an object, got null");
1149 }
1150
1151 var type = _typeof(value);
1152
1153 if (type !== "object") {
1154 throw new TypeError("an importMap must be an object, received ".concat(value));
1155 }
1156
1157 if (Array.isArray(value)) {
1158 throw new TypeError("an importMap must be an object, received array ".concat(value));
1159 }
1160};
1161
1162var applyImportMap = function applyImportMap(_ref) {
1163 var importMap = _ref.importMap,
1164 href = _ref.href,
1165 importerHref = _ref.importerHref;
1166 assertImportMap(importMap);
1167
1168 if (typeof href !== "string") {
1169 throw new TypeError("href must be a string, got ".concat(href));
1170 }
1171
1172 var _importMap$imports = importMap.imports,
1173 imports = _importMap$imports === void 0 ? {} : _importMap$imports,
1174 _importMap$scopes = importMap.scopes,
1175 scopes = _importMap$scopes === void 0 ? {} : _importMap$scopes;
1176
1177 if (importerHref) {
1178 if (typeof importerHref !== "string") {
1179 throw new TypeError("importerHref must be a string, got ".concat(importerHref));
1180 }
1181
1182 var importerPathname = hrefToPathname(importerHref); // here instead or taking the first match
1183 // take the best match instead
1184 // check the importMap spec repo to find how
1185 // (bsically most char matching is a win)
1186 // (or just the longest scope)
1187
1188 var matchingPathnamePattern = Object.keys(scopes).find(function (pathnameMatchPattern) {
1189 return match(importerPathname, pathnameMatchPattern);
1190 });
1191
1192 if (matchingPathnamePattern) {
1193 var scopeImports = scopes[matchingPathnamePattern];
1194 return applyImports({
1195 href: href,
1196 imports: scopeImports // scopePattern: matchingPathnamePattern,
1197
1198 });
1199 }
1200 }
1201
1202 return applyImports({
1203 href: href,
1204 imports: imports
1205 });
1206};
1207
1208var applyImports = function applyImports(_ref2) {
1209 var href = _ref2.href,
1210 imports = _ref2.imports;
1211 var modulePathname = hrefToPathname(href);
1212 var pathnamePatternArray = Object.keys(imports);
1213 var i = 0;
1214
1215 while (i < pathnamePatternArray.length) {
1216 var pathnamePattern = pathnamePatternArray[i];
1217 i++;
1218 var matchResult = match(modulePathname, pathnamePattern);
1219 if (!matchResult) continue;
1220 var before = matchResult.before,
1221 after = matchResult.after;
1222 var moduleOrigin = hrefToOrigin(href);
1223 var replacement = imports[pathnamePattern];
1224 return "".concat(moduleOrigin).concat(before).concat(replacement).concat(after);
1225 }
1226
1227 return href;
1228};
1229
1230var match = function match(pathname, pattern) {
1231 var patternHasLeadingSlash = pattern[0] === "/";
1232 var patternHasTrailingSlash = pattern[pattern.length - 1] === "/"; // pattern : '/foo/'
1233
1234 if (patternHasLeadingSlash && patternHasTrailingSlash) {
1235 var index = pathname.indexOf(pattern); // pathname: '/fo/bar'
1236 // pathname: '/foobar'
1237
1238 if (index === -1) return null; // pathname: '/foo/bar'
1239
1240 return {
1241 before: pathname.slice(0, index),
1242 after: pathname.slice(index + pattern.length)
1243 };
1244 } // pattern: '/foo'
1245
1246
1247 if (patternHasLeadingSlash && !patternHasTrailingSlash) {
1248 // pathname: '/fo', /foobar'
1249 if (pathname !== pattern) return null; // pathname: '/foo'
1250
1251 return {
1252 before: "",
1253 after: ""
1254 };
1255 } // pattern: 'foo/'
1256
1257
1258 if (!patternHasLeadingSlash && patternHasTrailingSlash) {
1259 var _index = pathname.indexOf("/".concat(pattern)); // pathname: '/fo/bar'
1260
1261
1262 if (_index === -1) return null; // pathname: '/bar/foo/file.js'
1263
1264 if (_index !== 0) return null; // pathname: '/foo', '/foo/bar'
1265
1266 return {
1267 before: "",
1268 after: pathname.slice(pattern.length + 1)
1269 };
1270 } // pattern 'foo'
1271 // pathname: '/fo', /foobar'
1272
1273
1274 if (pathname.slice(1) !== pattern) return null; // pathname: '/foo'
1275
1276 return {
1277 before: "",
1278 after: ""
1279 };
1280};
1281
1282var sortImportMap = function sortImportMap(importMap) {
1283 assertImportMap(importMap);
1284 var imports = importMap.imports,
1285 scopes = importMap.scopes;
1286 var orderedImportMap = {
1287 imports: imports ? sortImportMapImports(imports) : {},
1288 scopes: scopes ? sortImportMapScopes(scopes) : {}
1289 };
1290 return orderedImportMap;
1291};
1292
1293var sortImportMapImports = function sortImportMapImports(imports) {
1294 var sortedImports = {};
1295 Object.keys(imports).sort(compareLengthOrLocaleCompare).forEach(function (name) {
1296 sortedImports[name] = imports[name];
1297 });
1298 return sortedImports;
1299};
1300
1301var sortImportMapScopes = function sortImportMapScopes(scopes) {
1302 var sortedScopes = {};
1303 Object.keys(scopes).sort(compareLengthOrLocaleCompare).forEach(function (scopeName) {
1304 sortedScopes[scopeName] = sortScopedImports(scopes[scopeName]);
1305 });
1306 return sortedScopes;
1307};
1308
1309var compareLengthOrLocaleCompare = function compareLengthOrLocaleCompare(a, b) {
1310 return b.length - a.length || a.localeCompare(b);
1311};
1312
1313var sortScopedImports = function sortScopedImports(scopedImports) {
1314 var compareScopedImport = function compareScopedImport(a, b) {
1315 // const aIsRoot = a === "/"
1316 // const bIsRoot = b === "/"
1317 // if (aIsRoot && !bIsRoot) return 1
1318 // if (!aIsRoot && bIsRoot) return -1
1319 // if (aIsRoot && bIsRoot) return 0
1320 // const aIsScope = a === scope
1321 // const bIsScope = b === scope
1322 // if (aIsScope && !bIsScope) return 1
1323 // if (!aIsScope && bIsScope) return -1
1324 // if (aIsScope && bIsScope) return 0
1325 return compareLengthOrLocaleCompare(a, b);
1326 };
1327
1328 var sortedScopedImports = {};
1329 Object.keys(scopedImports).sort(compareScopedImport).forEach(function (name) {
1330 sortedScopedImports[name] = scopedImports[name];
1331 });
1332 return sortedScopedImports;
1333};
1334
1335var composeTwoImportMaps = function composeTwoImportMaps(leftImportMap, rightImportMap) {
1336 assertImportMap(leftImportMap);
1337 assertImportMap(rightImportMap);
1338 return sortImportMap({
1339 imports: composeTwoImports(leftImportMap.imports, rightImportMap.imports),
1340 scopes: composeTwoScopes(leftImportMap.scopes, rightImportMap.scopes)
1341 });
1342};
1343
1344var composeTwoImports = function composeTwoImports() {
1345 var leftImports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1346 var rightImports = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1347 return _objectSpread2({}, leftImports, {}, rightImports);
1348};
1349
1350var composeTwoScopes = function composeTwoScopes() {
1351 var leftScopes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1352 var rightScopes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1353
1354 var scopes = _objectSpread2({}, leftScopes);
1355
1356 Object.keys(rightScopes).forEach(function (pattern) {
1357 if (scopes.hasOwnProperty(pattern)) {
1358 scopes[pattern] = _objectSpread2({}, scopes[pattern], {}, rightScopes[pattern]);
1359 } else {
1360 scopes[pattern] = _objectSpread2({}, rightScopes[pattern]);
1361 }
1362 });
1363 return scopes;
1364};
1365
1366// https://url.spec.whatwg.org/#example-start-with-a-widows-drive-letter
1367var isWindowsDriveLetter = function isWindowsDriveLetter(specifier) {
1368 var firstChar = specifier[0];
1369 if (!/[a-zA-Z]/.test(firstChar)) return false;
1370 var secondChar = specifier[1];
1371 if (secondChar !== ":") return false;
1372 var thirdChar = specifier[2];
1373 return thirdChar === "/";
1374};
1375
1376// "file:///folder/file.js"
1377// "chrome://folder/file.js"
1378
1379var isAbsoluteSpecifier = function isAbsoluteSpecifier(specifier) {
1380 // window drive letter could are not protocol yep
1381 // something like `C:/folder/file.js`
1382 // will be considered as a bare import
1383 if (isWindowsDriveLetter(specifier.slice(0, 3))) return false;
1384 return /^[a-zA-Z]+:/.test(specifier);
1385};
1386var resolveAbsoluteSpecifier = function resolveAbsoluteSpecifier(_ref) {
1387 var specifier = _ref.specifier;
1388 return specifier;
1389};
1390
1391var isSchemeRelativeSpecifier = function isSchemeRelativeSpecifier(specifier) {
1392 return specifier.slice(0, 2) === "//";
1393};
1394var resolveSchemeRelativeSpecifier = function resolveSchemeRelativeSpecifier(_ref) {
1395 var importer = _ref.importer,
1396 specifier = _ref.specifier;
1397 return "".concat(hrefToScheme(importer), ":").concat(specifier);
1398};
1399
1400var isOriginRelativeSpecifier = function isOriginRelativeSpecifier(specifier) {
1401 var firstChar = specifier[0];
1402 if (firstChar !== "/") return false;
1403 var secondChar = specifier[1];
1404 if (secondChar === "/") return false;
1405 return true;
1406};
1407var resolveOriginRelativeSpecifier = function resolveOriginRelativeSpecifier(_ref) {
1408 var importer = _ref.importer,
1409 specifier = _ref.specifier;
1410 var importerOrigin = hrefToOrigin(importer);
1411 return "".concat(importerOrigin, "/").concat(specifier.slice(1));
1412};
1413
1414// "../folder/file.js"
1415
1416var isPathnameRelativeSpecifier = function isPathnameRelativeSpecifier(specifier) {
1417 if (specifier.slice(0, 2) === "./") return true;
1418 if (specifier.slice(0, 3) === "../") return true;
1419 return false;
1420};
1421var resolvePathnameRelativeSpecifier = function resolvePathnameRelativeSpecifier(_ref) {
1422 var importer = _ref.importer,
1423 specifier = _ref.specifier;
1424 var importerPathname = hrefToPathname(importer); // ./foo.js on /folder/file.js -> /folder/foo.js
1425 // ./foo/bar.js on /folder/file.js -> /folder/foo/bar.js
1426 // ./foo.js on /folder/subfolder/file.js -> /folder/subfolder/foo.js
1427
1428 if (specifier.startsWith("./")) {
1429 var _importerOrigin = hrefToOrigin(importer);
1430
1431 var importerDirname = pathnameToDirname(importerPathname);
1432 return "".concat(_importerOrigin).concat(importerDirname, "/").concat(specifier.slice(2));
1433 } // ../foo/bar.js on /folder/file.js -> /foo/bar.js
1434 // ../foo/bar.js on /folder/subfolder/file.js -> /folder/foo/bar.js
1435 // ../../foo/bar.js on /folder/file.js -> /foo/bar.js
1436 // ../bar.js on / -> /bar.js
1437
1438
1439 var unresolvedPathname = specifier;
1440 var importerFolders = importerPathname.split("/");
1441 importerFolders.pop(); // remove file, it is not a folder
1442
1443 while (unresolvedPathname.slice(0, 3) === "../") {
1444 // when there is no folder left to resolved
1445 // we just ignore '../'
1446 if (importerFolders.length) {
1447 importerFolders.pop();
1448 }
1449
1450 unresolvedPathname = unresolvedPathname.slice(3);
1451 }
1452
1453 var importerOrigin = hrefToOrigin(importer);
1454 var resolvedPathname = "".concat(importerFolders.join("/"), "/").concat(unresolvedPathname);
1455 return "".concat(importerOrigin).concat(resolvedPathname);
1456};
1457
1458var resolveBareSpecifier = function resolveBareSpecifier(_ref) {
1459 var importer = _ref.importer,
1460 specifier = _ref.specifier;
1461 var importerOrigin = hrefToOrigin(importer);
1462 return "".concat(importerOrigin, "/").concat(specifier);
1463};
1464
1465var resolveImport = function resolveImport(_ref) {
1466 var importer = _ref.importer,
1467 specifier = _ref.specifier;
1468
1469 if (isAbsoluteSpecifier(specifier)) {
1470 return resolveAbsoluteSpecifier({
1471 importer: importer,
1472 specifier: specifier
1473 });
1474 }
1475
1476 if (!importer) {
1477 throw new Error("missing importer to resolve relative specifier.\nimporter: ".concat(importer, "\nspecifier: ").concat(specifier));
1478 }
1479
1480 if (isSchemeRelativeSpecifier(specifier)) {
1481 return resolveSchemeRelativeSpecifier({
1482 importer: importer,
1483 specifier: specifier
1484 });
1485 }
1486
1487 if (isOriginRelativeSpecifier(specifier)) {
1488 return resolveOriginRelativeSpecifier({
1489 importer: importer,
1490 specifier: specifier
1491 });
1492 }
1493
1494 if (isPathnameRelativeSpecifier(specifier)) {
1495 return resolvePathnameRelativeSpecifier({
1496 importer: importer,
1497 specifier: specifier
1498 });
1499 }
1500
1501 return resolveBareSpecifier({
1502 importer: importer,
1503 specifier: specifier
1504 });
1505};
1506
1507var resolvePath = function resolvePath(_ref) {
1508 var specifier = _ref.specifier,
1509 importer = _ref.importer,
1510 importMap = _ref.importMap,
1511 _ref$defaultExtension = _ref.defaultExtension,
1512 defaultExtension = _ref$defaultExtension === void 0 ? true : _ref$defaultExtension;
1513 var resolvedImport = resolveImport({
1514 specifier: specifier,
1515 importer: importer
1516 });
1517 var remappedImport = importMap ? applyImportMap({
1518 importMap: importMap,
1519 href: resolvedImport,
1520 importerHref: importer
1521 }) : resolvedImport;
1522
1523 if (typeof defaultExtension === "string") {
1524 var extension = pathnameToExtension(remappedImport);
1525
1526 if (extension === "") {
1527 return "".concat(remappedImport).concat(defaultExtension);
1528 }
1529 }
1530
1531 if (defaultExtension === true) {
1532 var _extension = pathnameToExtension(remappedImport);
1533
1534 if (_extension === "") {
1535 if (importer) {
1536 var importerPathname = hrefToPathname(importer);
1537 var importerExtension = pathnameToExtension(importerPathname);
1538 return "".concat(remappedImport).concat(importerExtension);
1539 }
1540 }
1541 }
1542
1543 return remappedImport;
1544};
1545
1546var nodeRequire = require;
1547var filenameContainsBackSlashes = __filename.indexOf("\\") > -1;
1548var url = filenameContainsBackSlashes ? "file://".concat(__filename.replace(/\\/g, "/")) : "file://".concat(__filename);
1549
1550var jsenvBundlingProjectPath;
1551
1552if (typeof __filename === "string") {
1553 jsenvBundlingProjectPath = path.resolve(__filename, "../../../"); // get ride of dist/node/main.js
1554} else {
1555 var selfPathname = hrefToPathname(url);
1556 var selfPath = pathnameToOperatingSystemPath(selfPathname);
1557 jsenvBundlingProjectPath = path.resolve(selfPath, "../../"); // get ride of src/JSENV_PATH.js
1558}
1559var jsenvBundlingProjectPathname = operatingSystemPathToPathname(jsenvBundlingProjectPath);
1560var jsenvBundlingRelativePathInception = function jsenvBundlingRelativePathInception(_ref) {
1561 var jsenvBundlingRelativePath = _ref.jsenvBundlingRelativePath,
1562 projectPathname = _ref.projectPathname;
1563 var jsenvPathname = "".concat(jsenvBundlingProjectPathname).concat(jsenvBundlingRelativePath);
1564 var relativePath = pathnameToRelativePath(jsenvPathname, projectPathname);
1565 return relativePath;
1566};
1567
1568function _await(value, then, direct) {
1569 if (direct) {
1570 return then ? then(value) : value;
1571 }
1572
1573 if (!value || !value.then) {
1574 value = Promise.resolve(value);
1575 }
1576
1577 return then ? value.then(then) : value;
1578}
1579
1580function _async(f) {
1581 return function () {
1582 for (var args = [], i = 0; i < arguments.length; i++) {
1583 args[i] = arguments[i];
1584 }
1585
1586 try {
1587 return Promise.resolve(f.apply(this, args));
1588 } catch (e) {
1589 return Promise.reject(e);
1590 }
1591 };
1592}
1593
1594var assertFolder = _async(function (path) {
1595 return _await(pathToFilesystemEntry(path), function (filesystemEntry) {
1596 if (!filesystemEntry) {
1597 throw new Error("folder not found on filesystem.\npath: ".concat(path));
1598 }
1599
1600 var type = filesystemEntry.type;
1601
1602 if (type !== "folder") {
1603 throw new Error("folder expected but found something else on filesystem.\npath: ".concat(path, "\nfound: ").concat(type));
1604 }
1605 });
1606});
1607var assertFile = _async(function (path) {
1608 return _await(pathToFilesystemEntry(path), function (filesystemEntry) {
1609 if (!filesystemEntry) {
1610 throw new Error("file not found on filesystem.\npath: ".concat(path));
1611 }
1612
1613 var type = filesystemEntry.type;
1614
1615 if (type !== "file") {
1616 throw new Error("file expected but found something else on filesystem.\npath: ".concat(path, "\nfound: ").concat(type));
1617 }
1618 });
1619});
1620var assertFileSync = function assertFileSync(path) {
1621 var stats;
1622
1623 try {
1624 stats = fs.statSync(path);
1625 } catch (e) {
1626 if (e.code === "ENOENT") {
1627 throw new Error("file not found on filesystem.\npath: ".concat(path));
1628 }
1629
1630 throw e;
1631 }
1632
1633 var entry = statsToEntry(stats);
1634
1635 if (entry !== "file") {
1636 throw new Error("file expected but found something else on filesystem.\npath: ".concat(path, "\nfound: ").concat(entry));
1637 }
1638};
1639
1640var pathToFilesystemEntry = function pathToFilesystemEntry(path) {
1641 return new Promise(function (resolve, reject) {
1642 fs.stat(path, function (error, stats) {
1643 if (error) {
1644 if (error.code === "ENOENT") resolve(null);else reject(error);
1645 } else {
1646 resolve({
1647 type: statsToEntry(stats),
1648 stats: stats
1649 });
1650 }
1651 });
1652 });
1653};
1654
1655var statsToEntry = function statsToEntry(stats) {
1656 if (stats.isFile()) {
1657 return "file";
1658 }
1659
1660 if (stats.isDirectory()) {
1661 return "folder";
1662 }
1663
1664 return "other";
1665};
1666
1667var LOG_LEVEL_OFF = "off";
1668var LOG_LEVEL_ERRORS = "errors";
1669var LOG_LEVEL_ERRORS_AND_WARNINGS = "errors+warnings";
1670var LOG_LEVEL_ERRORS_WARNINGS_AND_LOGS = "errors+warnings+logs";
1671var LOG_LEVEL_MAXIMUM = "maximum";
1672var createLogger = function createLogger(_ref) {
1673 var _ref$logLevel = _ref.logLevel,
1674 logLevel = _ref$logLevel === void 0 ? LOG_LEVEL_ERRORS_WARNINGS_AND_LOGS : _ref$logLevel;
1675
1676 if (logLevel === LOG_LEVEL_MAXIMUM) {
1677 return {
1678 logTrace: logTrace,
1679 log: log,
1680 logWarning: logWarning,
1681 logError: logError
1682 };
1683 }
1684
1685 if (logLevel === LOG_LEVEL_ERRORS_WARNINGS_AND_LOGS) {
1686 return {
1687 logTrace: logTraceDisabled,
1688 log: log,
1689 logWarning: logWarning,
1690 logError: logError
1691 };
1692 }
1693
1694 if (logLevel === LOG_LEVEL_ERRORS_AND_WARNINGS) {
1695 return {
1696 logTrace: logTraceDisabled,
1697 log: logDisabled,
1698 logWarning: logWarning,
1699 logError: logError
1700 };
1701 }
1702
1703 if (logLevel === LOG_LEVEL_ERRORS) {
1704 return {
1705 logTrace: logTraceDisabled,
1706 log: logDisabled,
1707 logWarning: logWarningDisabled,
1708 logError: logError
1709 };
1710 }
1711
1712 if (logLevel === LOG_LEVEL_OFF) {
1713 return {
1714 logTrace: logTraceDisabled,
1715 log: logDisabled,
1716 logWarning: logWarningDisabled,
1717 logError: logErrorDisabled
1718 };
1719 }
1720
1721 throw new Error("unexpected logLevel.\nlogLevel: ".concat(logLevel, "\nallowed log levels: ").concat(LOG_LEVEL_OFF, ", ").concat(LOG_LEVEL_ERRORS, ", ").concat(LOG_LEVEL_ERRORS_AND_WARNINGS, ", ").concat(LOG_LEVEL_ERRORS_WARNINGS_AND_LOGS, ", ").concat(LOG_LEVEL_MAXIMUM));
1722};
1723var logTrace = console.trace;
1724
1725var logTraceDisabled = function logTraceDisabled() {};
1726
1727var log = console.log;
1728
1729var logDisabled = function logDisabled() {};
1730
1731var logWarning = console.warn;
1732
1733var logWarningDisabled = function logWarningDisabled() {};
1734
1735var logError = console.error;
1736
1737var logErrorDisabled = function logErrorDisabled() {};
1738
1739var createRollupPluginExternalGlobal = nodeRequire("rollup-plugin-external-globals");
1740
1741var createImportFromGlobalRollupPlugin = function createImportFromGlobalRollupPlugin(_ref) {
1742 var platformGlobalName = _ref.platformGlobalName;
1743 if (typeof platformGlobalName !== "string") throw new TypeError("platformGlobalName must be a string, got ".concat(platformGlobalName, "."));
1744 return createRollupPluginExternalGlobal({
1745 global: platformGlobalName
1746 }, {
1747 exclude: [/\.json$/]
1748 });
1749};
1750
1751// certainly needs to be moved to @dmail/cancellation
1752var firstOperationMatching = function firstOperationMatching(_ref) {
1753 var array = _ref.array,
1754 start = _ref.start,
1755 predicate = _ref.predicate;
1756 if (_typeof(array) !== "object") throw new TypeError(createArrayErrorMessage({
1757 array: array
1758 }));
1759 if (typeof start !== "function") throw new TypeError(createStartErrorMessage({
1760 start: start
1761 }));
1762 if (typeof predicate !== "function") throw new TypeError(createPredicateErrorMessage({
1763 predicate: predicate
1764 }));
1765 return new Promise(function (resolve, reject) {
1766 var visit = function visit(index) {
1767 if (index >= array.length) {
1768 return resolve();
1769 }
1770
1771 var input = array[index];
1772 var returnValue = start(input);
1773 return Promise.resolve(returnValue).then(function (output) {
1774 if (predicate(output)) {
1775 return resolve(output);
1776 }
1777
1778 return visit(index + 1);
1779 }, reject);
1780 };
1781
1782 visit(0);
1783 });
1784};
1785
1786var createArrayErrorMessage = function createArrayErrorMessage(_ref2) {
1787 var array = _ref2.array;
1788 return "array must be an object.\narray: ".concat(array);
1789};
1790
1791var createStartErrorMessage = function createStartErrorMessage(_ref3) {
1792 var start = _ref3.start;
1793 return "start must be a function.\nstart: ".concat(start);
1794};
1795
1796var createPredicateErrorMessage = function createPredicateErrorMessage(_ref4) {
1797 var predicate = _ref4.predicate;
1798 return "predicate must be a function.\npredicate: ".concat(predicate);
1799};
1800
1801function _await$1(value, then, direct) {
1802 if (direct) {
1803 return then ? then(value) : value;
1804 }
1805
1806 if (!value || !value.then) {
1807 value = Promise.resolve(value);
1808 }
1809
1810 return then ? value.then(then) : value;
1811}
1812
1813function _empty() {}
1814
1815function _awaitIgnored(value, direct) {
1816 if (!direct) {
1817 return value && value.then ? value.then(_empty) : Promise.resolve();
1818 }
1819}
1820
1821function _call(body, then, direct) {
1822 if (direct) {
1823 return then ? then(body()) : body();
1824 }
1825
1826 try {
1827 var result = Promise.resolve(body());
1828 return then ? result.then(then) : result;
1829 } catch (e) {
1830 return Promise.reject(e);
1831 }
1832}
1833
1834function _async$1(f) {
1835 return function () {
1836 for (var args = [], i = 0; i < arguments.length; i++) {
1837 args[i] = arguments[i];
1838 }
1839
1840 try {
1841 return Promise.resolve(f.apply(this, args));
1842 } catch (e) {
1843 return Promise.reject(e);
1844 }
1845 };
1846}
1847
1848var promiseSequence = function promiseSequence(callbackArray) {
1849 var values = [];
1850
1851 var visit = _async$1(function (index) {
1852 if (index === callbackArray.length) return;
1853 var callback = callbackArray[index];
1854 return _call(callback, function (value) {
1855 values.push(value);
1856 return _awaitIgnored(visit(index + 1));
1857 });
1858 });
1859
1860 return _await$1(visit(0), function () {
1861 return values;
1862 });
1863};
1864
1865// export const ensureFolderLeadingTo = (file) => {
1866// return new Promise((resolve, reject) => {
1867// fs.mkdir(path.dirname(file), { resurcive: true }, (error) => {
1868// if (error) {
1869// if (error.code === "EEXIST") {
1870// resolve()
1871// return
1872// }
1873// reject(error)
1874// return
1875// }
1876// resolve()
1877// })
1878// })
1879// }
1880
1881function _await$2(value, then, direct) {
1882 if (direct) {
1883 return then ? then(value) : value;
1884 }
1885
1886 if (!value || !value.then) {
1887 value = Promise.resolve(value);
1888 }
1889
1890 return then ? value.then(then) : value;
1891}
1892
1893function _empty$1() {}
1894
1895function _invokeIgnored(body) {
1896 var result = body();
1897
1898 if (result && result.then) {
1899 return result.then(_empty$1);
1900 }
1901}
1902
1903function _async$2(f) {
1904 return function () {
1905 for (var args = [], i = 0; i < arguments.length; i++) {
1906 args[i] = arguments[i];
1907 }
1908
1909 try {
1910 return Promise.resolve(f.apply(this, args));
1911 } catch (e) {
1912 return Promise.reject(e);
1913 }
1914 };
1915}
1916
1917var fileMakeDirname = function fileMakeDirname(file) {
1918 var fileNormalized = normalizeSeparation(file); // remove first / in case path starts with / (linux)
1919 // because it would create a "" entry in folders array below
1920 // tryig to create a folder at ""
1921
1922 var fileStartsWithSlash = fileNormalized[0] === "/";
1923 var pathname = fileStartsWithSlash ? fileNormalized.slice(1) : fileNormalized;
1924 var folders = pathname.split("/");
1925 folders.pop();
1926 return promiseSequence(folders.map(function (_, index) {
1927 return function () {
1928 var folder = folders.slice(0, index + 1).join("/");
1929 return folderMake("".concat(fileStartsWithSlash ? "/" : "").concat(folder));
1930 };
1931 }));
1932};
1933
1934var normalizeSeparation = function normalizeSeparation(file) {
1935 return file.replace(/\\/g, "/");
1936};
1937
1938var folderMake = function folderMake(folder) {
1939 return new Promise(function (resolve, reject) {
1940 fs.mkdir(folder, _async$2(function (error) {
1941 return _invokeIgnored(function () {
1942 if (error) {
1943 // au cas ou deux script essayent de crée un dossier peu importe qui y arrive c'est ok
1944 return _invokeIgnored(function () {
1945 if (error.code === "EEXIST") {
1946 return _await$2(fileLastStat(folder), function (stat) {
1947 if (stat.isDirectory()) {
1948 resolve();
1949 } else {
1950 reject({
1951 status: 500,
1952 reason: "expect a directory"
1953 });
1954 }
1955 });
1956 } else {
1957 reject({
1958 status: 500,
1959 reason: error.code
1960 });
1961 }
1962 });
1963 } else {
1964 resolve();
1965 }
1966 });
1967 }));
1968 });
1969};
1970
1971var fileLastStat = function fileLastStat(path) {
1972 return new Promise(function (resolve, reject) {
1973 fs.lstat(path, function (error, lstat) {
1974 if (error) {
1975 reject({
1976 status: 500,
1977 reason: error.code
1978 });
1979 } else {
1980 resolve(lstat);
1981 }
1982 });
1983 });
1984};
1985
1986var copyFilePromisified = util.promisify(fs.copyFile);
1987
1988function _await$3(value, then, direct) {
1989 if (direct) {
1990 return then ? then(value) : value;
1991 }
1992
1993 if (!value || !value.then) {
1994 value = Promise.resolve(value);
1995 }
1996
1997 return then ? value.then(then) : value;
1998}
1999
2000var readFilePromisified = util.promisify(fs.readFile);
2001
2002function _async$3(f) {
2003 return function () {
2004 for (var args = [], i = 0; i < arguments.length; i++) {
2005 args[i] = arguments[i];
2006 }
2007
2008 try {
2009 return Promise.resolve(f.apply(this, args));
2010 } catch (e) {
2011 return Promise.reject(e);
2012 }
2013 };
2014}
2015
2016var fileRead = _async$3(function (file) {
2017 return _await$3(readFilePromisified(file), function (buffer) {
2018 return buffer.toString();
2019 });
2020});
2021
2022var statPromisified = util.promisify(fs.stat);
2023
2024var lstatPromisified = util.promisify(fs.lstat);
2025
2026function _await$4(value, then, direct) {
2027 if (direct) {
2028 return then ? then(value) : value;
2029 }
2030
2031 if (!value || !value.then) {
2032 value = Promise.resolve(value);
2033 }
2034
2035 return then ? value.then(then) : value;
2036}
2037
2038var writeFilePromisified = util.promisify(fs.writeFile);
2039
2040function _async$4(f) {
2041 return function () {
2042 for (var args = [], i = 0; i < arguments.length; i++) {
2043 args[i] = arguments[i];
2044 }
2045
2046 try {
2047 return Promise.resolve(f.apply(this, args));
2048 } catch (e) {
2049 return Promise.reject(e);
2050 }
2051 };
2052}
2053
2054var fileWrite = _async$4(function (file, content) {
2055 return _await$4(fileMakeDirname(file), function () {
2056 return writeFilePromisified(file, content);
2057 });
2058});
2059
2060var readdirPromisified = util.promisify(fs.readdir);
2061
2062var pathnameToDirname$1 = function pathnameToDirname(pathname) {
2063 var slashLastIndex = pathname.lastIndexOf("/");
2064 if (slashLastIndex === -1) return "";
2065 return pathname.slice(0, slashLastIndex);
2066};
2067
2068function _await$5(value, then, direct) {
2069 if (direct) {
2070 return then ? then(value) : value;
2071 }
2072
2073 if (!value || !value.then) {
2074 value = Promise.resolve(value);
2075 }
2076
2077 return then ? value.then(then) : value;
2078}
2079
2080function _async$5(f) {
2081 return function () {
2082 for (var args = [], i = 0; i < arguments.length; i++) {
2083 args[i] = arguments[i];
2084 }
2085
2086 try {
2087 return Promise.resolve(f.apply(this, args));
2088 } catch (e) {
2089 return Promise.reject(e);
2090 }
2091 };
2092}
2093
2094var readPackageData = _async$5(function (_ref) {
2095 var path = _ref.path;
2096 return _await$5(fileRead(path), function (packageString) {
2097 var packageData = JSON.parse(packageString);
2098 return packageData;
2099 });
2100});
2101
2102function _await$6(value, then, direct) {
2103 if (direct) {
2104 return then ? then(value) : value;
2105 }
2106
2107 if (!value || !value.then) {
2108 value = Promise.resolve(value);
2109 }
2110
2111 return then ? value.then(then) : value;
2112}
2113
2114function _async$6(f) {
2115 return function () {
2116 for (var args = [], i = 0; i < arguments.length; i++) {
2117 args[i] = arguments[i];
2118 }
2119
2120 try {
2121 return Promise.resolve(f.apply(this, args));
2122 } catch (e) {
2123 return Promise.reject(e);
2124 }
2125 };
2126}
2127
2128function _catch(body, recover) {
2129 try {
2130 var result = body();
2131 } catch (e) {
2132 return recover(e);
2133 }
2134
2135 if (result && result.then) {
2136 return result.then(void 0, recover);
2137 }
2138
2139 return result;
2140}
2141
2142var resolveNodeModule = _async$6(function (_ref) {
2143 var rootPathname = _ref.rootPathname,
2144 packagePathname = _ref.packagePathname,
2145 packageData = _ref.packageData,
2146 dependencyName = _ref.dependencyName,
2147 dependencyVersionPattern = _ref.dependencyVersionPattern,
2148 dependencyType = _ref.dependencyType,
2149 onWarn = _ref.onWarn;
2150 var packageFolderPathname = pathnameToDirname$1(packagePathname);
2151 var packageFolderRelativePath = pathnameToRelativePathname(packageFolderPathname, rootPathname);
2152 var nodeModuleCandidateArray = [].concat(_toConsumableArray(getCandidateArrayFromPackageFolder(packageFolderRelativePath)), ["node_modules"]);
2153 return _await$6(firstOperationMatching({
2154 array: nodeModuleCandidateArray,
2155 start: _async$6(function (nodeModuleCandidate) {
2156 var packagePathname = "".concat(rootPathname, "/").concat(nodeModuleCandidate, "/").concat(dependencyName, "/package.json");
2157 return _catch(function () {
2158 return _await$6(readPackageData({
2159 path: pathnameToOperatingSystemPath(packagePathname)
2160 }), function (packageData) {
2161 return {
2162 packagePathname: packagePathname,
2163 packageData: packageData
2164 };
2165 });
2166 }, function (e) {
2167 if (e.code === "ENOENT") {
2168 return {};
2169 }
2170
2171 if (e.name === "SyntaxError") {
2172 throw createDependencyPackageParsingError({
2173 parsingError: e,
2174 packagePathname: packagePathname
2175 });
2176 }
2177
2178 throw e;
2179 });
2180 }),
2181 predicate: function predicate(_ref2) {
2182 var packageData = _ref2.packageData;
2183 return Boolean(packageData);
2184 }
2185 }), function (result) {
2186 if (!result) {
2187 onWarn({
2188 code: "DEPENDENCY_NOT_FOUND",
2189 message: createDendencyNotFoundMessage({
2190 dependencyName: dependencyName,
2191 dependencyType: dependencyType,
2192 dependencyVersionPattern: dependencyVersionPattern,
2193 packagePathname: packagePathname,
2194 packageData: packageData
2195 }),
2196 data: {
2197 packagePathname: packagePathname,
2198 packageData: packageData,
2199 dependencyName: dependencyName,
2200 dependencyType: dependencyType
2201 }
2202 });
2203 }
2204
2205 return result;
2206 });
2207});
2208
2209var getCandidateArrayFromPackageFolder = function getCandidateArrayFromPackageFolder(packageFolderRelativePath) {
2210 if (packageFolderRelativePath === "") return [];
2211 var candidateArray = [];
2212 var relativeFolderNameArray = packageFolderRelativePath.split("/node_modules/"); // remove the first empty string
2213
2214 relativeFolderNameArray.shift();
2215 var i = relativeFolderNameArray.length;
2216
2217 while (i--) {
2218 candidateArray.push("node_modules/".concat(relativeFolderNameArray.slice(0, i + 1).join("/node_modules/"), "/node_modules"));
2219 }
2220
2221 return candidateArray;
2222};
2223
2224var createDependencyPackageParsingError = function createDependencyPackageParsingError(_ref3) {
2225 var parsingError = _ref3.parsingError,
2226 packagePathname = _ref3.packagePathname;
2227 return new SyntaxError("error while parsing dependency package.json.\n--- parsing error message ---\n".concat(parsingError.message, "\n--- package.json path ---\n").concat(pathnameToOperatingSystemPath(packagePathname), "\n"));
2228};
2229
2230var createDendencyNotFoundMessage = function createDendencyNotFoundMessage(_ref4) {
2231 var dependencyName = _ref4.dependencyName,
2232 dependencyType = _ref4.dependencyType,
2233 dependencyVersionPattern = _ref4.dependencyVersionPattern,
2234 packageData = _ref4.packageData,
2235 packagePathname = _ref4.packagePathname;
2236 return "cannot find a ".concat(dependencyType, ".\n--- ").concat(dependencyType, " ---\n").concat(dependencyName, "@").concat(dependencyVersionPattern, "\n--- required by ---\n").concat(packageData.name, "@").concat(packageData.version, "\n--- package.json path ---\n").concat(pathnameToOperatingSystemPath(packagePathname), "\n");
2237};
2238
2239function _await$7(value, then, direct) {
2240 if (direct) {
2241 return then ? then(value) : value;
2242 }
2243
2244 if (!value || !value.then) {
2245 value = Promise.resolve(value);
2246 }
2247
2248 return then ? value.then(then) : value;
2249}
2250
2251function _invoke(body, then) {
2252 var result = body();
2253
2254 if (result && result.then) {
2255 return result.then(then);
2256 }
2257
2258 return then(result);
2259}
2260
2261function _async$7(f) {
2262 return function () {
2263 for (var args = [], i = 0; i < arguments.length; i++) {
2264 args[i] = arguments[i];
2265 }
2266
2267 try {
2268 return Promise.resolve(f.apply(this, args));
2269 } catch (e) {
2270 return Promise.reject(e);
2271 }
2272 };
2273}
2274
2275var resolvePackageMain = function resolvePackageMain(_ref) {
2276 var packageData = _ref.packageData,
2277 packagePathname = _ref.packagePathname,
2278 onWarn = _ref.onWarn;
2279
2280 if ("module" in packageData) {
2281 return resolveMainFile({
2282 from: "module",
2283 main: packageData.module,
2284 packagePathname: packagePathname,
2285 onWarn: onWarn
2286 });
2287 }
2288
2289 if ("jsnext:main" in packageData) {
2290 return resolveMainFile({
2291 from: "jsnext:main",
2292 main: packageData["jsnext:main"],
2293 packagePathname: packagePathname,
2294 onWarn: onWarn
2295 });
2296 }
2297
2298 if ("main" in packageData) {
2299 return resolveMainFile({
2300 from: "main",
2301 main: packageData.main,
2302 packagePathname: packagePathname,
2303 onWarn: onWarn
2304 });
2305 }
2306
2307 return resolveMainFile({
2308 from: "default",
2309 main: "index",
2310 packagePathname: packagePathname,
2311 onWarn: onWarn
2312 });
2313};
2314var extensionCandidateArray = ["js", "json", "node"];
2315
2316var resolveMainFile = _async$7(function (_ref2) {
2317 var _exit = false;
2318 var main = _ref2.main,
2319 packagePathname = _ref2.packagePathname,
2320 onWarn = _ref2.onWarn;
2321 // main is explicitely empty meaning
2322 // it is assumed that we should not find a file
2323 if (main === "") return "";
2324 if (main.slice(0, 2) === "./") main = main.slice(2);
2325 if (main[0] === "/") main = main.slice(1);
2326 var packageDirname = pathnameToDirname$1(packagePathname);
2327 var extension = path.extname(main);
2328 return _invoke(function () {
2329 if (extension === "") {
2330 var fileWithoutExtensionPathname = "".concat(packageDirname, "/").concat(main);
2331 return _await$7(firstOperationMatching({
2332 array: extensionCandidateArray,
2333 start: _async$7(function (extensionCandidate) {
2334 var path = pathnameToOperatingSystemPath("".concat(fileWithoutExtensionPathname, ".").concat(extensionCandidate));
2335 return _await$7(pathLeadsToAFile(path), function (isFile) {
2336 return isFile ? extensionCandidate : null;
2337 });
2338 }),
2339 predicate: function predicate(extension) {
2340 return Boolean(extension);
2341 }
2342 }), function (extensionLeadingToFile) {
2343 if (extensionLeadingToFile) {
2344 _exit = true;
2345 return "".concat(main, ".").concat(extensionLeadingToFile);
2346 }
2347
2348 onWarn({
2349 code: "MAIN_FILE_NOT_FOUND",
2350 message: createMainFileNotFoundMessage({
2351 mainPathname: fileWithoutExtensionPathname,
2352 packagePathname: packagePathname
2353 }),
2354 data: {
2355 main: main,
2356 packagePathname: packagePathname
2357 }
2358 });
2359 _exit = true;
2360 return "".concat(main, ".js");
2361 });
2362 }
2363 }, function (_result) {
2364 if (_exit) return _result;
2365 var mainPathname = "".concat(packageDirname, "/").concat(main);
2366 return _await$7(pathLeadsToAFile(mainPathname), function (isFile) {
2367 if (!isFile) {
2368 onWarn({
2369 code: "MAIN_FILE_NOT_FOUND",
2370 message: createMainFileNotFoundMessage({
2371 mainPathname: mainPathname,
2372 packagePathname: packagePathname
2373 }),
2374 data: {
2375 main: main,
2376 packagePathname: packagePathname
2377 }
2378 });
2379 }
2380
2381 return main;
2382 });
2383 });
2384});
2385
2386var pathLeadsToAFile = function pathLeadsToAFile(path) {
2387 return new Promise(function (resolve, reject) {
2388 fs.stat(path, function (error, statObject) {
2389 if (error) {
2390 if (error.code === "ENOENT") resolve(false);else reject(error);
2391 } else {
2392 resolve(statObject.isFile());
2393 }
2394 });
2395 });
2396}; // we know in advance this remapping does not lead to an actual file.
2397// we only warn because we have no guarantee this remapping will actually be used
2398// in the codebase.
2399
2400
2401var createMainFileNotFoundMessage = function createMainFileNotFoundMessage(_ref3) {
2402 var mainPathname = _ref3.mainPathname,
2403 packagePathname = _ref3.packagePathname;
2404 return "cannot find a module main file.\n--- extensions tried ---\n".concat(extensionCandidateArray.join(","), "\n--- main path ---\n").concat(pathnameToOperatingSystemPath(mainPathname), "\n--- package.json path ---\n").concat(pathnameToOperatingSystemPath(packagePathname));
2405};
2406
2407var importMapToVsCodeConfigPaths = function importMapToVsCodeConfigPaths(_ref) {
2408 var _ref$imports = _ref.imports,
2409 imports = _ref$imports === void 0 ? {} : _ref$imports;
2410 var paths = {};
2411
2412 var handleImportsAt = function handleImportsAt(pathPattern, remappingValue) {
2413 var path;
2414
2415 if (pathPattern.endsWith("/")) {
2416 path = "".concat(pathPattern, "*");
2417 } else {
2418 path = pathPattern;
2419 }
2420
2421 var remappingArray = typeof remappingValue === "string" ? [remappingValue] : remappingValue;
2422 var candidates = remappingArray.filter(function (remapping) {
2423 return !remapping.endsWith("/");
2424 }).map(function (remapping) {
2425 return ".".concat(remapping);
2426 });
2427
2428 if (candidates.length) {
2429 if (path in paths) {
2430 paths[path] = [].concat(_toConsumableArray(paths[path]), _toConsumableArray(candidates));
2431 } else {
2432 paths[path] = candidates;
2433 }
2434 }
2435 };
2436
2437 Object.keys(imports).forEach(function (importPattern) {
2438 handleImportsAt(importPattern, imports[importPattern]);
2439 });
2440 return paths;
2441};
2442
2443function _async$8(f) {
2444 return function () {
2445 for (var args = [], i = 0; i < arguments.length; i++) {
2446 args[i] = arguments[i];
2447 }
2448
2449 try {
2450 return Promise.resolve(f.apply(this, args));
2451 } catch (e) {
2452 return Promise.reject(e);
2453 }
2454 };
2455}
2456
2457function _await$8(value, then, direct) {
2458 if (direct) {
2459 return then ? then(value) : value;
2460 }
2461
2462 if (!value || !value.then) {
2463 value = Promise.resolve(value);
2464 }
2465
2466 return then ? value.then(then) : value;
2467}
2468
2469function _catch$1(body, recover) {
2470 try {
2471 var result = body();
2472 } catch (e) {
2473 return recover(e);
2474 }
2475
2476 if (result && result.then) {
2477 return result.then(void 0, recover);
2478 }
2479
2480 return result;
2481}
2482
2483function _invoke$1(body, then) {
2484 var result = body();
2485
2486 if (result && result.then) {
2487 return result.then(then);
2488 }
2489
2490 return then(result);
2491}
2492
2493function _empty$2() {}
2494
2495function _awaitIgnored$1(value, direct) {
2496 if (!direct) {
2497 return value && value.then ? value.then(_empty$2) : Promise.resolve();
2498 }
2499}
2500
2501var generateImportMapForNodeModules = _async$8(function (_ref) {
2502 var projectPath = _ref.projectPath,
2503 _ref$rootProjectPath = _ref.rootProjectPath,
2504 rootProjectPath = _ref$rootProjectPath === void 0 ? projectPath : _ref$rootProjectPath,
2505 _ref$importMapRelativ = _ref.importMapRelativePath,
2506 importMapRelativePath = _ref$importMapRelativ === void 0 ? "/importMap.json" : _ref$importMapRelativ,
2507 _ref$inputImportMap = _ref.inputImportMap,
2508 inputImportMap = _ref$inputImportMap === void 0 ? {} : _ref$inputImportMap,
2509 _ref$includeDevDepend = _ref.includeDevDependencies,
2510 includeDevDependencies = _ref$includeDevDepend === void 0 ? false : _ref$includeDevDepend,
2511 _ref$onWarn = _ref.onWarn,
2512 onWarn = _ref$onWarn === void 0 ? function (_ref2) {
2513 var message = _ref2.message;
2514 console.warn(message);
2515 } : _ref$onWarn,
2516 _ref$writeImportMapFi = _ref.writeImportMapFile,
2517 writeImportMapFile = _ref$writeImportMapFi === void 0 ? false : _ref$writeImportMapFi,
2518 _ref$logImportMapFile = _ref.logImportMapFilePath,
2519 logImportMapFilePath = _ref$logImportMapFile === void 0 ? true : _ref$logImportMapFile,
2520 _ref$throwUnhandled = _ref.throwUnhandled,
2521 throwUnhandled = _ref$throwUnhandled === void 0 ? true : _ref$throwUnhandled,
2522 _ref$writeJsConfigFil = _ref.writeJsConfigFile,
2523 writeJsConfigFile = _ref$writeJsConfigFil === void 0 ? false : _ref$writeJsConfigFil,
2524 _ref$logJsConfigFileP = _ref.logJsConfigFilePath,
2525 logJsConfigFilePath = _ref$logJsConfigFileP === void 0 ? true : _ref$logJsConfigFileP;
2526 return catchAsyncFunctionCancellation(_async$8(function () {
2527 var projectPathname = operatingSystemPathToPathname(projectPath);
2528 var projectPackagePathname = "".concat(projectPathname, "/package.json");
2529 var rootProjectPathname = operatingSystemPathToPathname(rootProjectPath);
2530 var rootImporterName = path.basename(rootProjectPathname);
2531 var rootPackagePathname = "".concat(rootProjectPathname, "/package.json");
2532 var imports = {};
2533 var scopes = {};
2534
2535 var start = _async$8(function () {
2536 return _await$8(readPackageData({
2537 path: pathnameToOperatingSystemPath(projectPackagePathname),
2538 onWarn: onWarn
2539 }), function (projectPackageData) {
2540 return _await$8(visitProjectPackage({
2541 packagePathname: projectPackagePathname,
2542 packageData: projectPackageData
2543 }), function () {
2544 var nodeModuleImportMap = {
2545 imports: imports,
2546 scopes: scopes
2547 };
2548 var importMap = composeTwoImportMaps(inputImportMap, nodeModuleImportMap);
2549 var sortedImportMap = sortImportMap(importMap);
2550 return _invoke$1(function () {
2551 if (writeImportMapFile) {
2552 var importMapPath = pathnameToOperatingSystemPath("".concat(projectPathname).concat(importMapRelativePath));
2553 return _await$8(fileWrite(importMapPath, JSON.stringify(sortedImportMap, null, " ")), function () {
2554 if (logImportMapFilePath) {
2555 console.log("-> ".concat(importMapPath));
2556 }
2557 });
2558 }
2559 }, function () {
2560 return _invoke$1(function () {
2561 if (writeJsConfigFile) {
2562 var jsConfigPath = pathnameToOperatingSystemPath("".concat(projectPathname, "/jsconfig.json"));
2563 return _catch$1(function () {
2564 var jsConfig = {
2565 compilerOptions: {
2566 baseUrl: ".",
2567 paths: _objectSpread2({
2568 "/*": ["./*"]
2569 }, importMapToVsCodeConfigPaths(importMap))
2570 }
2571 };
2572 return _await$8(fileWrite(jsConfigPath, JSON.stringify(jsConfig, null, " ")), function () {
2573 if (logJsConfigFilePath) {
2574 console.log("-> ".concat(jsConfigPath));
2575 }
2576 });
2577 }, function (e) {
2578 if (e.code !== "ENOENT") {
2579 throw e;
2580 }
2581 });
2582 }
2583 }, function (_result2) {
2584 return sortedImportMap;
2585 });
2586 });
2587 });
2588 });
2589 });
2590
2591 var visitProjectPackage = _async$8(function (_ref3) {
2592 var packagePathname = _ref3.packagePathname,
2593 packageData = _ref3.packageData;
2594 return _awaitIgnored$1(visit({
2595 packagePathname: packagePathname,
2596 packageData: packageData,
2597 packageName: packageData.name,
2598 importerPackagePathname: packagePathname
2599 }));
2600 });
2601
2602 var seen = {};
2603
2604 var visit = _async$8(function (_ref4) {
2605 var packagePathname = _ref4.packagePathname,
2606 packageData = _ref4.packageData,
2607 packageName = _ref4.packageName,
2608 importerPackagePathname = _ref4.importerPackagePathname;
2609
2610 if (packagePathname in seen) {
2611 if (seen[packagePathname].includes(importerPackagePathname)) return;
2612 seen[packagePathname].push(importerPackagePathname);
2613 } else {
2614 seen[packagePathname] = [importerPackagePathname];
2615 }
2616
2617 return _await$8(visitPackage({
2618 packagePathname: packagePathname,
2619 packageData: packageData,
2620 packageName: packageName,
2621 importerPackagePathname: importerPackagePathname
2622 }), function () {
2623 return _awaitIgnored$1(visitDependencies({
2624 packagePathname: packagePathname,
2625 packageData: packageData
2626 }));
2627 });
2628 });
2629
2630 var visitPackage = _async$8(function (_ref5) {
2631 var packagePathname = _ref5.packagePathname,
2632 packageData = _ref5.packageData,
2633 packageName = _ref5.packageName,
2634 importerPackagePathname = _ref5.importerPackagePathname;
2635 var packagePathInfo = computePackagePathInfo({
2636 packagePathname: packagePathname,
2637 packageName: packageName,
2638 importerPackagePathname: importerPackagePathname
2639 });
2640 return _await$8(visitPackageMain({
2641 packagePathname: packagePathname,
2642 packageName: packageName,
2643 packageData: packageData,
2644 packagePathInfo: packagePathInfo
2645 }), function () {
2646 if ("imports" in packageData) {
2647 visitPackageImports({
2648 packagePathname: packagePathname,
2649 packageName: packageName,
2650 packageData: packageData,
2651 packagePathInfo: packagePathInfo
2652 });
2653 }
2654
2655 if ("exports" in packageData) {
2656 visitPackageExports({
2657 packagePathname: packagePathname,
2658 packageName: packageName,
2659 packageData: packageData,
2660 packagePathInfo: packagePathInfo
2661 });
2662 }
2663 });
2664 });
2665
2666 var visitPackageMain = _async$8(function (_ref6) {
2667 var packagePathname = _ref6.packagePathname,
2668 packageData = _ref6.packageData,
2669 packageName = _ref6.packageName,
2670 _ref6$packagePathInfo = _ref6.packagePathInfo,
2671 packageIsRoot = _ref6$packagePathInfo.packageIsRoot,
2672 packageIsProject = _ref6$packagePathInfo.packageIsProject,
2673 importerPackageIsRoot = _ref6$packagePathInfo.importerPackageIsRoot,
2674 importerName = _ref6$packagePathInfo.importerName,
2675 actualRelativePath = _ref6$packagePathInfo.actualRelativePath,
2676 expectedRelativePath = _ref6$packagePathInfo.expectedRelativePath;
2677 if (packageIsRoot) return;
2678 if (packageIsProject) return;
2679 return _await$8(resolvePackageMain({
2680 packagePathname: packagePathname,
2681 packageData: packageData,
2682 onWarn: function onWarn() {}
2683 }), function (main) {
2684 // it's possible to have no main
2685 // like { main: "" } in package.json
2686 // or a main that does not lead to an actual file
2687 if (!main) return;
2688 var from = packageName;
2689 var to = "".concat(actualRelativePath, "/").concat(main);
2690
2691 if (importerPackageIsRoot) {
2692 addImportMapping({
2693 from: from,
2694 to: to
2695 });
2696 } else {
2697 addScopedImportMapping({
2698 scope: "/".concat(importerName, "/"),
2699 from: from,
2700 to: to
2701 });
2702 }
2703
2704 if (actualRelativePath !== expectedRelativePath) {
2705 addScopedImportMapping({
2706 scope: "/".concat(importerName, "/"),
2707 from: from,
2708 to: to
2709 });
2710 }
2711 });
2712 });
2713
2714 var visitPackageImports = function visitPackageImports(_ref7) {
2715 var packagePathname = _ref7.packagePathname,
2716 packageData = _ref7.packageData,
2717 packagePathInfo = _ref7.packagePathInfo;
2718 var packageImports = packageData.imports;
2719
2720 if (_typeof(packageImports) !== "object" || packageImports === null) {
2721 onWarn(createUnexpectedPackageImportsWarning({
2722 packageImports: packageImports,
2723 packagePathname: packagePathname
2724 }));
2725 return;
2726 }
2727
2728 var packageIsRoot = packagePathInfo.packageIsRoot,
2729 actualRelativePath = packagePathInfo.actualRelativePath;
2730 Object.keys(packageImports).forEach(function (key) {
2731 var resolvedKey = resolvePathInPackage(key, packagePathname);
2732 if (!resolvedKey) return;
2733 var resolvedValue = resolvePathInPackage(packageImports[key], packagePathname);
2734 if (!resolvedValue) return;
2735
2736 if (packageIsRoot) {
2737 addImportMapping({
2738 from: resolvedKey,
2739 to: resolvedValue
2740 });
2741 } else {
2742 addScopedImportMapping({
2743 scope: "".concat(actualRelativePath, "/"),
2744 from: resolvedKey,
2745 to: "".concat(actualRelativePath).concat(resolvedValue)
2746 });
2747 }
2748 });
2749
2750 if (!packageIsRoot) {
2751 // ensureImportsScopedInsidePackage
2752 addScopedImportMapping({
2753 scope: "".concat(actualRelativePath, "/"),
2754 from: "".concat(actualRelativePath, "/"),
2755 to: "".concat(actualRelativePath, "/")
2756 });
2757 }
2758 };
2759
2760 var visitPackageExports = function visitPackageExports(_ref8) {
2761 var packagePathname = _ref8.packagePathname,
2762 packageName = _ref8.packageName,
2763 packageData = _ref8.packageData,
2764 _ref8$packagePathInfo = _ref8.packagePathInfo,
2765 importerName = _ref8$packagePathInfo.importerName,
2766 packageIsRoot = _ref8$packagePathInfo.packageIsRoot,
2767 actualRelativePath = _ref8$packagePathInfo.actualRelativePath,
2768 expectedRelativePath = _ref8$packagePathInfo.expectedRelativePath;
2769 if (packageIsRoot) return;
2770 var packageExports = packageData.exports;
2771
2772 if (_typeof(packageExports) !== "object" || packageExports === null) {
2773 onWarn(createUnexpectedPackageExportsWarning({
2774 packageExports: packageExports,
2775 packagePathname: packagePathname
2776 }));
2777 return;
2778 }
2779
2780 Object.keys(packageExports).forEach(function (key) {
2781 var resolvedKey = resolvePathInPackage(key, packagePathname);
2782 if (!resolvedKey) return;
2783 var resolvedValue = resolvePathInPackage(packageExports[key], packagePathname);
2784 if (!resolvedValue) return;
2785 var from = "".concat(packageName).concat(resolvedKey);
2786 var to = "".concat(actualRelativePath).concat(resolvedValue);
2787
2788 if (importerName === rootImporterName) {
2789 addImportMapping({
2790 from: from,
2791 to: to
2792 });
2793 } else {
2794 addScopedImportMapping({
2795 scope: "/".concat(importerName, "/"),
2796 from: from,
2797 to: to
2798 });
2799 }
2800
2801 if (actualRelativePath !== expectedRelativePath) {
2802 addScopedImportMapping({
2803 scope: "/".concat(importerName, "/"),
2804 from: from,
2805 to: to
2806 });
2807 }
2808 });
2809 };
2810
2811 var visitDependencies = _async$8(function (_ref9) {
2812 var packagePathname = _ref9.packagePathname,
2813 packageData = _ref9.packageData;
2814 var dependencyMap = {};
2815 var _packageData$dependen = packageData.dependencies,
2816 dependencies = _packageData$dependen === void 0 ? {} : _packageData$dependen;
2817 Object.keys(dependencies).forEach(function (dependencyName) {
2818 dependencyMap[dependencyName] = {
2819 type: "dependency",
2820 versionPattern: dependencies[dependencyName]
2821 };
2822 });
2823 var _packageData$peerDepe = packageData.peerDependencies,
2824 peerDependencies = _packageData$peerDepe === void 0 ? {} : _packageData$peerDepe;
2825 Object.keys(peerDependencies).forEach(function (dependencyName) {
2826 dependencyMap[dependencyName] = {
2827 type: "peerDependency",
2828 versionPattern: peerDependencies[dependencyName]
2829 };
2830 });
2831 var isProjectPackage = packagePathname === projectPackagePathname;
2832
2833 if (includeDevDependencies && isProjectPackage) {
2834 var _packageData$devDepen = packageData.devDependencies,
2835 devDependencies = _packageData$devDepen === void 0 ? {} : _packageData$devDepen;
2836 Object.keys(devDependencies).forEach(function (dependencyName) {
2837 if (!dependencyMap.hasOwnProperty(dependencyName)) {
2838 dependencyMap[dependencyName] = {
2839 type: "devDependency",
2840 versionPattern: devDependencies[dependencyName]
2841 };
2842 }
2843 });
2844 }
2845
2846 return _awaitIgnored$1(Promise.all(Object.keys(dependencyMap).map(_async$8(function (dependencyName) {
2847 var dependency = dependencyMap[dependencyName];
2848 return _await$8(findDependency({
2849 packagePathname: packagePathname,
2850 packageData: packageData,
2851 dependencyName: dependencyName,
2852 dependencyType: dependency.type,
2853 dependencyVersionPattern: dependency.versionPattern
2854 }), function (dependencyData) {
2855 if (!dependencyData) {
2856 return;
2857 }
2858
2859 var dependencyPackagePathname = dependencyData.packagePathname,
2860 dependencyPackageData = dependencyData.packageData;
2861 return _awaitIgnored$1(visit({
2862 packagePathname: dependencyPackagePathname,
2863 packageData: dependencyPackageData,
2864 packageName: dependencyName,
2865 importerPackagePathname: packagePathname
2866 }));
2867 });
2868 }))));
2869 });
2870
2871 var computePackagePathInfo = function computePackagePathInfo(_ref10) {
2872 var packagePathname = _ref10.packagePathname,
2873 packageName = _ref10.packageName,
2874 importerPackagePathname = _ref10.importerPackagePathname;
2875 var packageIsRoot = packagePathname === rootPackagePathname;
2876 var packageIsProject = packagePathname === projectPackagePathname;
2877 var importerPackageIsRoot = importerPackagePathname === rootPackagePathname;
2878 var importerPackageIsProject = importerPackagePathname === projectPackagePathname;
2879 var importerName = importerPackageIsRoot ? rootImporterName : pathnameToDirname$1(pathnameToRelativePathname(importerPackagePathname, rootProjectPathname)).slice(1);
2880 var actualPathname = pathnameToDirname$1(packagePathname);
2881 var actualRelativePath = pathnameToRelativePathname(actualPathname, rootProjectPathname);
2882 var expectedPathname;
2883
2884 if (packageIsProject && !packageIsRoot) {
2885 expectedPathname = pathnameToDirname$1(importerPackagePathname);
2886 } else {
2887 expectedPathname = "".concat(pathnameToDirname$1(importerPackagePathname), "/node_modules/").concat(packageName);
2888 }
2889
2890 var expectedRelativePath = pathnameToRelativePathname(expectedPathname, rootProjectPathname);
2891 return {
2892 importerPackageIsRoot: importerPackageIsRoot,
2893 importerPackageIsProject: importerPackageIsProject,
2894 importerName: importerName,
2895 packageIsRoot: packageIsRoot,
2896 packageIsProject: packageIsProject,
2897 actualRelativePath: actualRelativePath,
2898 expectedRelativePath: expectedRelativePath
2899 };
2900 };
2901
2902 var resolvePathInPackage = function resolvePathInPackage(path, packagePathname) {
2903 if (path[0] === "/") return path;
2904 if (path.slice(0, 2) === "./") return path.slice(1);
2905 onWarn(createInvalidPackageRelativePathWarning({
2906 path: path,
2907 packagePathname: packagePathname
2908 }));
2909 return "";
2910 };
2911
2912 var addImportMapping = function addImportMapping(_ref11) {
2913 var from = _ref11.from,
2914 to = _ref11.to;
2915 imports[from] = to;
2916 };
2917
2918 var addScopedImportMapping = function addScopedImportMapping(_ref12) {
2919 var scope = _ref12.scope,
2920 from = _ref12.from,
2921 to = _ref12.to;
2922 scopes[scope] = _objectSpread2({}, scopes[scope] || {}, _defineProperty({}, from, to));
2923 };
2924
2925 var dependenciesCache = {};
2926
2927 var findDependency = function findDependency(_ref13) {
2928 var packagePathname = _ref13.packagePathname,
2929 packageData = _ref13.packageData,
2930 dependencyName = _ref13.dependencyName,
2931 dependencyType = _ref13.dependencyType,
2932 dependencyVersionPattern = _ref13.dependencyVersionPattern;
2933
2934 if (packagePathname in dependenciesCache === false) {
2935 dependenciesCache[packagePathname] = {};
2936 }
2937
2938 if (dependencyName in dependenciesCache[packagePathname]) {
2939 return dependenciesCache[packagePathname][dependencyName];
2940 }
2941
2942 var dependencyPromise = resolveNodeModule({
2943 rootPathname: rootProjectPathname,
2944 packagePathname: packagePathname,
2945 packageData: packageData,
2946 dependencyName: dependencyName,
2947 dependencyType: dependencyType,
2948 dependencyVersionPattern: dependencyVersionPattern,
2949 onWarn: onWarn
2950 });
2951 dependenciesCache[packagePathname][dependencyName] = dependencyPromise;
2952 return dependencyPromise;
2953 };
2954
2955 var promise = start();
2956 return throwUnhandled ? promise.catch(function (e) {
2957 setTimeout(function () {
2958 throw e;
2959 });
2960 }) : promise;
2961 }));
2962});
2963
2964var createInvalidPackageRelativePathWarning = function createInvalidPackageRelativePathWarning(_ref14) {
2965 var path = _ref14.path,
2966 packagePathname = _ref14.packagePathname;
2967 return {
2968 code: "INVALID_PATH_RELATIVE_TO_PACKAGE",
2969 message: "\ninvalid path relative to package.\n--- path ---\n".concat(path, "\n--- package.json path ---\n").concat(pathnameToOperatingSystemPath(packagePathname), "\n"),
2970 data: {
2971 packagePathname: packagePathname,
2972 path: path
2973 }
2974 };
2975};
2976
2977var createUnexpectedPackageImportsWarning = function createUnexpectedPackageImportsWarning(_ref15) {
2978 var packageImports = _ref15.packageImports,
2979 packagePathname = _ref15.packagePathname;
2980 return {
2981 code: "UNEXPECTED_PACKAGE_IMPORTS",
2982 message: "\npackage.imports must be an object.\n--- package.json imports ---\n".concat(packageImports, "\n--- package.json path ---\n").concat(pathnameToOperatingSystemPath(packagePathname), "\n"),
2983 data: {
2984 packagePathname: packagePathname,
2985 packageImports: packageImports
2986 }
2987 };
2988};
2989
2990var createUnexpectedPackageExportsWarning = function createUnexpectedPackageExportsWarning(_ref16) {
2991 var packageExports = _ref16.packageExports,
2992 packagePathname = _ref16.packagePathname;
2993 return {
2994 code: "UNEXPECTED_PACKAGE_EXPORTS",
2995 message: "\npackage.exports must be an object.\n--- package.json exports ---\n".concat(packageExports, "\n--- package.json path ---\n").concat(pathnameToOperatingSystemPath(packagePathname), "\n"),
2996 data: {
2997 packagePathname: packagePathname,
2998 packageExports: packageExports
2999 }
3000 };
3001};
3002
3003var generateSpecifierMapOption = function generateSpecifierMapOption() {
3004 return undefined;
3005};
3006
3007var _require2 = nodeRequire("@babel/core"),
3008 buildExternalHelpers = _require2.buildExternalHelpers;
3009
3010var BABEL_HELPERS_FACADE_PATH = "/.jsenv/babelHelpers.js";
3011var GLOBAL_THIS_FACADE_PATH = "/.jsenv/helpers/global-this.js";
3012var generateSpecifierDynamicMapOption = function generateSpecifierDynamicMapOption() {
3013 var _ref;
3014
3015 return _ref = {}, _defineProperty(_ref, GLOBAL_THIS_FACADE_PATH, function () {
3016 return generateGlobalThisSource();
3017 }), _defineProperty(_ref, BABEL_HELPERS_FACADE_PATH, function () {
3018 return {
3019 code: buildExternalHelpers(undefined, "module"),
3020 // babel helper must not be retransformed
3021 skipTransform: true
3022 };
3023 }), _ref;
3024};
3025
3026var generateGlobalThisSource = function generateGlobalThisSource() {
3027 return "\n// eslint-disable-next-line no-undef\nif (typeof globalThis !== \"object\") {\n let globalObject\n\n if (this) {\n globalObject = this\n } else {\n // eslint-disable-next-line no-extend-native\n Object.defineProperty(Object.prototype, \"__global__\", {\n get() {\n return this\n },\n configurable: true,\n })\n // eslint-disable-next-line no-undef\n globalObject = __global__\n delete Object.prototype.__global__\n }\n\n globalObject.globalThis = globalObject\n}";
3028};
3029
3030var _require2$1 = nodeRequire("@babel/helper-module-imports"),
3031 addNamed = _require2$1.addNamed; // for reference this is how it's done to reference
3032// a global babel helper object instead of using
3033// a named import
3034// https://github.com/babel/babel/blob/master/packages/babel-plugin-external-helpers/src/index.js
3035// named import approach found here:
3036// https://github.com/rollup/rollup-plugin-babel/blob/18e4232a450f320f44c651aa8c495f21c74d59ac/src/helperPlugin.js#L1
3037
3038
3039var createReplaceBabelHelperByNamedImportsBabelPlugin = function createReplaceBabelHelperByNamedImportsBabelPlugin(_ref) {
3040 var babelHelpersFacadePath = _ref.babelHelpersFacadePath;
3041 return {
3042 pre: function pre(file) {
3043 var cachedHelpers = {};
3044 file.set("helperGenerator", function (name) {
3045 if (!file.availableHelper(name)) {
3046 return undefined;
3047 }
3048
3049 if (cachedHelpers[name]) {
3050 return cachedHelpers[name];
3051 } // https://github.com/babel/babel/tree/master/packages/babel-helper-module-imports
3052
3053
3054 var helper = addNamed(file.path, name, babelHelpersFacadePath);
3055 cachedHelpers[name] = helper;
3056 return helper;
3057 });
3058 }
3059 };
3060};
3061
3062var _require2$2 = nodeRequire("@babel/helper-module-imports"),
3063 addSideEffect = _require2$2.addSideEffect;
3064
3065var createForceImportsBabelPlugin = function createForceImportsBabelPlugin(_ref) {
3066 var sideEffectImportRelativePathArray = _ref.sideEffectImportRelativePathArray;
3067 return {
3068 pre: function pre(file) {
3069 var opts = file.path.hub.file.opts;
3070 var isFileItself = sideEffectImportRelativePathArray.some(function (relativePath) {
3071 return relativePath.slice(1) === opts.filenameRelative;
3072 });
3073 if (isFileItself) return;
3074 sideEffectImportRelativePathArray.forEach(function (relativePath) {
3075 addSideEffect(file.path, relativePath);
3076 });
3077 }
3078 };
3079};
3080
3081// https://github.com/cfware/babel-plugin-bundled-import-meta/blob/master/index.js
3082var _require2$3 = nodeRequire("@babel/helper-module-imports"),
3083 addNamed$1 = _require2$3.addNamed;
3084
3085var createImportMetaUrlNamedImportBabelPlugin = function createImportMetaUrlNamedImportBabelPlugin(_ref) {
3086 var importMetaFacadePath = _ref.importMetaFacadePath;
3087 return function () {
3088 return {
3089 visitor: {
3090 Program: function Program(programPath) {
3091 var metaPropertyMap = {};
3092 programPath.traverse({
3093 MemberExpression: function MemberExpression(path) {
3094 var node = path.node;
3095 var object = node.object;
3096 if (object.type !== "MetaProperty") return;
3097 var objectProperty = object.property;
3098 if (objectProperty.name !== "meta") return;
3099 var property = node.property;
3100 var name = property.name;
3101
3102 if (name in metaPropertyMap) {
3103 metaPropertyMap[name].push(path);
3104 } else {
3105 metaPropertyMap[name] = [path];
3106 }
3107 }
3108 });
3109 Object.keys(metaPropertyMap).forEach(function (propertyName) {
3110 var importMetaPropertyId = propertyName;
3111 var result = addNamed$1(programPath, importMetaPropertyId, importMetaFacadePath);
3112 metaPropertyMap[propertyName].forEach(function (path) {
3113 path.replaceWith(result);
3114 });
3115 });
3116 }
3117 }
3118 };
3119 };
3120};
3121
3122var generateBabelPluginMapOption = function generateBabelPluginMapOption(_ref) {
3123 var projectPathname = _ref.projectPathname,
3124 format = _ref.format,
3125 babelPluginMap = _ref.babelPluginMap,
3126 featureNameArray = _ref.featureNameArray,
3127 globalThisHelperRelativePath = _ref.globalThisHelperRelativePath;
3128 return _objectSpread2({}, generateBabelPluginMapSubset({
3129 babelPluginMap: babelPluginMap,
3130 featureNameArray: featureNameArray
3131 }), {}, generateBabelPluginMapForBundle({
3132 projectPathname: projectPathname,
3133 format: format,
3134 globalThisHelperRelativePath: GLOBAL_THIS_FACADE_PATH,
3135 babelHelpersFacadePath: BABEL_HELPERS_FACADE_PATH
3136 }));
3137};
3138
3139var generateBabelPluginMapSubset = function generateBabelPluginMapSubset(_ref2) {
3140 var babelPluginMap = _ref2.babelPluginMap,
3141 featureNameArray = _ref2.featureNameArray;
3142 var babelPluginMapSubset = {};
3143 Object.keys(babelPluginMap).forEach(function (babelPluginName) {
3144 if (featureNameArray.includes(babelPluginName)) {
3145 babelPluginMapSubset[babelPluginName] = babelPluginMap[babelPluginName];
3146 }
3147 });
3148 return babelPluginMapSubset;
3149};
3150
3151var generateBabelPluginMapForBundle = function generateBabelPluginMapForBundle(_ref3) {
3152 var projectPathname = _ref3.projectPathname,
3153 format = _ref3.format,
3154 globalThisHelperRelativePath = _ref3.globalThisHelperRelativePath,
3155 babelHelpersFacadePath = _ref3.babelHelpersFacadePath;
3156 var bundleBabelPluginMap = {};
3157 var forcedImportsBabelPlugin = createForceImportsBabelPlugin({
3158 projectPathname: projectPathname,
3159 sideEffectImportRelativePathArray: [globalThisHelperRelativePath]
3160 });
3161 bundleBabelPluginMap["force-imports"] = [forcedImportsBabelPlugin];
3162 var replaceBabelHelperByNamedImportsBabelPlugin = createReplaceBabelHelperByNamedImportsBabelPlugin({
3163 babelHelpersFacadePath: babelHelpersFacadePath
3164 });
3165 bundleBabelPluginMap["replace-babel-helper-by-named-imports"] = [replaceBabelHelperByNamedImportsBabelPlugin];
3166
3167 if (format === "commonjs" || format === "global") {
3168 var importMetaFacadePath;
3169
3170 if (projectPathname === jsenvBundlingProjectPathname) {
3171 importMetaFacadePath = "/src/babel-plugin-map/import-meta-".concat(format, ".js");
3172 } else {
3173 importMetaFacadePath = "@jsenv/bundling/src/babel-plugin-map/import-meta-".concat(format, ".js");
3174 }
3175
3176 bundleBabelPluginMap["import-meta-url-named-import"] = createImportMetaUrlNamedImportBabelPlugin({
3177 importMetaFacadePath: importMetaFacadePath
3178 });
3179 }
3180
3181 return bundleBabelPluginMap;
3182};
3183
3184function _await$9(value, then, direct) {
3185 if (direct) {
3186 return then ? then(value) : value;
3187 }
3188
3189 if (!value || !value.then) {
3190 value = Promise.resolve(value);
3191 }
3192
3193 return then ? value.then(then) : value;
3194}
3195
3196var fetch = nodeRequire("node-fetch");
3197
3198function _invoke$2(body, then) {
3199 var result = body();
3200
3201 if (result && result.then) {
3202 return result.then(then);
3203 }
3204
3205 return then(result);
3206}
3207
3208var AbortController = nodeRequire("abort-controller"); // ideally we should only pass this to the fetch below
3209
3210
3211function _async$9(f) {
3212 return function () {
3213 for (var args = [], i = 0; i < arguments.length; i++) {
3214 args[i] = arguments[i];
3215 }
3216
3217 try {
3218 return Promise.resolve(f.apply(this, args));
3219 } catch (e) {
3220 return Promise.reject(e);
3221 }
3222 };
3223}
3224
3225https.globalAgent.options.rejectUnauthorized = false;
3226var fetchUsingHttp = _async$9(function (url) {
3227 var _exit = false;
3228
3229 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3230
3231 var cancellationToken = _ref.cancellationToken,
3232 rest = _objectWithoutProperties(_ref, ["cancellationToken"]);
3233
3234 return _invoke$2(function () {
3235 if (cancellationToken) {
3236 // a cancelled fetch will never resolve, while cancellation api
3237 // expect to get a rejected promise.
3238 // createOperation ensure we'll get a promise rejected with a cancelError
3239 return _await$9(createOperation({
3240 cancellationToken: cancellationToken,
3241 start: function start() {
3242 return fetch(url, _objectSpread2({
3243 signal: cancellationTokenToAbortSignal(cancellationToken)
3244 }, rest));
3245 }
3246 }), function (response) {
3247 _exit = true;
3248 return normalizeResponse(response);
3249 });
3250 }
3251 }, function (_result) {
3252 return _exit ? _result : _await$9(fetch(url, rest), normalizeResponse);
3253 });
3254});
3255
3256var normalizeResponse = _async$9(function (response) {
3257 return _await$9(response.text(), function (text) {
3258 return {
3259 url: response.url,
3260 status: response.status,
3261 statusText: response.statusText,
3262 headers: responseToHeaderMap(response),
3263 body: text
3264 };
3265 });
3266}); // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal
3267
3268
3269var cancellationTokenToAbortSignal = function cancellationTokenToAbortSignal(cancellationToken) {
3270 var abortController = new AbortController();
3271 cancellationToken.register(function (reason) {
3272 abortController.abort(reason);
3273 });
3274 return abortController.signal;
3275};
3276
3277var responseToHeaderMap = function responseToHeaderMap(response) {
3278 var headerMap = {};
3279 response.headers.forEach(function (value, name) {
3280 headerMap[name] = value;
3281 });
3282 return headerMap;
3283};
3284
3285var writeSourceMappingURL = function writeSourceMappingURL(source, location) {
3286 return "".concat(source, "\n", "//#", " sourceMappingURL=").concat(location);
3287};
3288var updateSourceMappingURL = function updateSourceMappingURL(source, callback) {
3289 var sourceMappingUrlRegExp = /\/\/# ?sourceMappingURL=([^\s'"]+)/g;
3290 var lastSourceMappingUrl;
3291 var matchSourceMappingUrl;
3292
3293 while (matchSourceMappingUrl = sourceMappingUrlRegExp.exec(source)) {
3294 lastSourceMappingUrl = matchSourceMappingUrl;
3295 }
3296
3297 if (lastSourceMappingUrl) {
3298 var index = lastSourceMappingUrl.index;
3299 var before = source.slice(0, index);
3300 var after = source.slice(index);
3301 var mappedAfter = after.replace(sourceMappingUrlRegExp, function (match, firstGroup) {
3302 return "//#".concat(" sourceMappingURL=", callback(firstGroup));
3303 });
3304 return "".concat(before).concat(mappedAfter);
3305 }
3306
3307 return source;
3308};
3309var readSourceMappingURL = function readSourceMappingURL(source) {
3310 var sourceMappingURL;
3311 updateSourceMappingURL(source, function (value) {
3312 sourceMappingURL = value;
3313 });
3314 return sourceMappingURL;
3315};
3316var parseSourceMappingURL = function parseSourceMappingURL(source) {
3317 var sourceMappingURL = readSourceMappingURL(source);
3318 if (!sourceMappingURL) return null;
3319 var base64Prefix = "data:application/json;charset=utf-8;base64,";
3320
3321 if (sourceMappingURL.startsWith(base64Prefix)) {
3322 var mapBase64Source = sourceMappingURL.slice(base64Prefix.length);
3323 var sourcemapString = new Buffer(mapBase64Source, "base64").toString("utf8");
3324 return {
3325 sourcemapString: sourcemapString
3326 };
3327 }
3328
3329 return {
3330 sourcemapURL: sourceMappingURL
3331 };
3332};
3333var writeOrUpdateSourceMappingURL = function writeOrUpdateSourceMappingURL(source, location) {
3334 if (readSourceMappingURL(source)) {
3335 return updateSourceMappingURL(source, location);
3336 }
3337
3338 return writeSourceMappingURL(source, location);
3339};
3340
3341function _await$a(value, then, direct) {
3342 if (direct) {
3343 return then ? then(value) : value;
3344 }
3345
3346 if (!value || !value.then) {
3347 value = Promise.resolve(value);
3348 }
3349
3350 return then ? value.then(then) : value;
3351}
3352
3353function _catch$2(body, recover) {
3354 try {
3355 var result = body();
3356 } catch (e) {
3357 return recover(e);
3358 }
3359
3360 if (result && result.then) {
3361 return result.then(void 0, recover);
3362 }
3363
3364 return result;
3365}
3366
3367function _async$a(f) {
3368 return function () {
3369 for (var args = [], i = 0; i < arguments.length; i++) {
3370 args[i] = arguments[i];
3371 }
3372
3373 try {
3374 return Promise.resolve(f.apply(this, args));
3375 } catch (e) {
3376 return Promise.reject(e);
3377 }
3378 };
3379}
3380
3381var readProjectImportMap = _async$a(function (_ref) {
3382 var projectPathname = _ref.projectPathname,
3383 importMapRelativePath = _ref.importMapRelativePath;
3384 return importMapRelativePath ? _catch$2(function () {
3385 return _await$a(fileRead(pathnameToOperatingSystemPath("".concat(projectPathname, "/").concat(importMapRelativePath))), JSON.parse);
3386 }, function (e) {
3387 if (e && e.code === "ENOENT") {
3388 return {};
3389 }
3390
3391 throw e;
3392 }) : {};
3393});
3394
3395function _await$b(value, then, direct) {
3396 if (direct) {
3397 return then ? then(value) : value;
3398 }
3399
3400 if (!value || !value.then) {
3401 value = Promise.resolve(value);
3402 }
3403
3404 return then ? value.then(then) : value;
3405}
3406
3407var _require2$4 = nodeRequire("@jsenv/core"),
3408 transformSource = _require2$4.transformSource,
3409 jsenvTransform = _require2$4.jsenvTransform,
3410 findAsyncPluginNameInBabelPluginMap = _require2$4.findAsyncPluginNameInBabelPluginMap;
3411
3412function _async$b(f) {
3413 return function () {
3414 for (var args = [], i = 0; i < arguments.length; i++) {
3415 args[i] = arguments[i];
3416 }
3417
3418 try {
3419 return Promise.resolve(f.apply(this, args));
3420 } catch (e) {
3421 return Promise.reject(e);
3422 }
3423 };
3424}
3425
3426var _require3 = nodeRequire("terser"),
3427 minifyCode = _require3.minify;
3428
3429function _invoke$3(body, then) {
3430 var result = body();
3431
3432 if (result && result.then) {
3433 return result.then(then);
3434 }
3435
3436 return then(result);
3437}
3438
3439function _empty$3() {}
3440
3441function _awaitIgnored$2(value, direct) {
3442 if (!direct) {
3443 return value && value.then ? value.then(_empty$3) : Promise.resolve();
3444 }
3445}
3446
3447var createJsenvRollupPlugin = _async$b(function (_ref) {
3448 var cancellationToken = _ref.cancellationToken,
3449 projectPathname = _ref.projectPathname,
3450 importDefaultExtension = _ref.importDefaultExtension,
3451 importMapRelativePath = _ref.importMapRelativePath,
3452 _ref$importMapForBund = _ref.importMapForBundle,
3453 importMapForBundle = _ref$importMapForBund === void 0 ? {} : _ref$importMapForBund,
3454 specifierMap = _ref.specifierMap,
3455 specifierDynamicMap = _ref.specifierDynamicMap,
3456 _ref$origin = _ref.origin,
3457 origin = _ref$origin === void 0 ? "http://example.com" : _ref$origin,
3458 babelPluginMap = _ref.babelPluginMap,
3459 convertMap = _ref.convertMap,
3460 featureNameArray = _ref.featureNameArray,
3461 minify = _ref.minify,
3462 format = _ref.format,
3463 _ref$detectAndTransfo = _ref.detectAndTransformIfNeededAsyncInsertedByRollup,
3464 detectAndTransformIfNeededAsyncInsertedByRollup = _ref$detectAndTransfo === void 0 ? format === "global" : _ref$detectAndTransfo,
3465 dir = _ref.dir,
3466 entryPointMap = _ref.entryPointMap,
3467 logger = _ref.logger;
3468 return _await$b(generateImportMapForNodeModules({
3469 projectPath: jsenvBundlingProjectPath,
3470 rootProjectPath: pathnameToOperatingSystemPath(projectPathname),
3471 onWarn: function onWarn(_ref2) {
3472 var message = _ref2.message;
3473 return logger.logWarning(message);
3474 }
3475 }), function (bundlingImportMap) {
3476 return _await$b(readProjectImportMap({
3477 projectPathname: projectPathname,
3478 importMapRelativePath: importMapRelativePath
3479 }), function (projectImportMap) {
3480 var importMap = [importMapForBundle, bundlingImportMap, projectImportMap].reduce(function (previous, current) {
3481 return composeTwoImportMaps(previous, current);
3482 }, {});
3483 var importMapHref = "file://".concat(projectPathname).concat(importMapRelativePath);
3484 specifierMap = _objectSpread2({}, specifierMap, {}, generateSpecifierMapOption(), _defineProperty({}, "/.jsenv/importMap.json", importMapHref));
3485 var chunkId = "".concat(Object.keys(entryPointMap)[0], ".js");
3486 specifierDynamicMap = _objectSpread2({}, specifierDynamicMap, {}, generateSpecifierDynamicMapOption(), _defineProperty({}, "/BUNDLE_CONSTANTS.js", function BUNDLE_CONSTANTSJs() {
3487 return "export const chunkId = ".concat(JSON.stringify(chunkId));
3488 }));
3489 babelPluginMap = generateBabelPluginMapOption({
3490 projectPathname: projectPathname,
3491 format: format,
3492 babelPluginMap: babelPluginMap,
3493 featureNameArray: featureNameArray
3494 }); // https://github.com/babel/babel/blob/master/packages/babel-core/src/tools/build-external-helpers.js#L1
3495
3496 var idSkipTransformArray = [];
3497 var idLoadMap = {};
3498
3499 var getRollupGenerateOptions = function getRollupGenerateOptions() {
3500 return _await$b({});
3501 };
3502
3503 var jsenvRollupPlugin = {
3504 name: "jsenv",
3505 resolveId: function resolveId(specifier, importer) {
3506 if (specifier in specifierDynamicMap) {
3507 var specifierDynamicMapping = specifierDynamicMap[specifier];
3508
3509 if (typeof specifierDynamicMapping !== "function") {
3510 throw new Error("specifier inside specifierDynamicMap must be functions, found ".concat(specifierDynamicMapping, " for ").concat(specifier));
3511 }
3512
3513 var osPath = pathnameToOperatingSystemPath("".concat(projectPathname).concat(specifier));
3514 idLoadMap[osPath] = specifierDynamicMapping;
3515 return osPath;
3516 }
3517
3518 if (specifier in specifierMap) {
3519 var specifierMapping = specifierMap[specifier];
3520
3521 if (typeof specifierMapping !== "string") {
3522 throw new Error("specifier inside specifierMap must be strings, found ".concat(specifierMapping, " for ").concat(specifier));
3523 }
3524
3525 specifier = specifierMapping; // disable remapping when specifier starts with file://
3526 // this is the only way for now to explicitely disable remapping
3527 // to target a specific file on filesystem
3528 // also remove file:// to keep only the os path
3529 // otherwise windows and rollup will not be happy when
3530 // searching the files
3531
3532 if (specifier.startsWith("file:///")) {
3533 specifier = specifier.slice("file://".length);
3534 var path = pathnameToOperatingSystemPath(specifier);
3535 assertFileSync(path);
3536 return path;
3537 }
3538 }
3539
3540 if (!importer) {
3541 if (specifier[0] === "/") specifier = specifier.slice(1);
3542
3543 var _path = pathnameToOperatingSystemPath("".concat(projectPathname, "/").concat(specifier));
3544
3545 assertFileSync(_path);
3546 return _path;
3547 }
3548
3549 var importerHref;
3550
3551 if (isWindowsPath(importer)) {
3552 importer = operatingSystemPathToPathname(importer);
3553 } // 99% of the time importer is an operating system path
3554 // here we ensure / is resolved against project by forcing an url resolution
3555 // prefixing with origin
3556
3557
3558 if (importer.startsWith("".concat(projectPathname, "/"))) {
3559 importerHref = "".concat(origin).concat(pathnameToRelativePath(importer, projectPathname));
3560 } else if (hrefToScheme(importer)) {
3561 if (importer.startsWith("file://".concat(projectPathname, "/"))) {
3562 importerHref = "".concat(origin).concat(pathnameToRelativePath(hrefToPathname(importer), projectPathname));
3563 } else {
3564 // there is already a scheme (http, https, file), keep it
3565 // it means there is an absolute import starting with file:// or http:// for instance.
3566 importerHref = importer;
3567 }
3568 } else {
3569 throw createImporterOutsideProjectError({
3570 importer: importer,
3571 projectPathname: projectPathname
3572 });
3573 }
3574
3575 var id = resolvePath({
3576 specifier: specifier,
3577 importer: importerHref,
3578 importMap: importMap,
3579 defaultExtension: importDefaultExtension
3580 }); // rollup works with operating system path
3581 // return os path when possible
3582 // to ensure we can predict sourcemap.sources returned by rollup
3583
3584 if (id.startsWith("file://")) {
3585 var pathname = hrefToPathname(id);
3586
3587 if (!pathnameIsInside(pathname, projectPathname)) {
3588 throw new Error(createMustBeInsideProjectMessage({
3589 resolvedId: id,
3590 specifier: specifier,
3591 importer: importer,
3592 projectPathname: projectPathname
3593 }));
3594 }
3595
3596 var _path2 = pathnameToOperatingSystemPath(pathname);
3597
3598 assertFileSync(_path2);
3599 return _path2;
3600 } // we have http or https protocol
3601
3602
3603 var resolvedIdIsInsideProject = id.startsWith("".concat(origin, "/"));
3604
3605 if (resolvedIdIsInsideProject) {
3606 var idPathname = hrefToPathname(id);
3607
3608 var _path3 = pathnameToOperatingSystemPath("".concat(projectPathname).concat(idPathname));
3609
3610 assertFileSync(_path3);
3611 return _path3;
3612 }
3613
3614 return id;
3615 },
3616 // https://rollupjs.org/guide/en#resolvedynamicimport
3617 // resolveDynamicImport: (specifier, importer) => {
3618 // },
3619 load: _async$b(function (id) {
3620 var _exit = false;
3621 return _invoke$3(function () {
3622 if (id in idLoadMap) {
3623 return _await$b(idLoadMap[id](), function (returnValue) {
3624 if (typeof returnValue === "string") {
3625 _exit = true;
3626 return returnValue;
3627 }
3628
3629 if (returnValue.skipTransform) {
3630 idSkipTransformArray.push(id);
3631 }
3632
3633 _exit = true;
3634 return returnValue.code;
3635 });
3636 }
3637 }, function (_result) {
3638 if (_exit) return _result;
3639 var hasSheme = isWindowsPath(id) ? false : Boolean(hrefToScheme(id));
3640 var href = hasSheme ? id : "file://".concat(operatingSystemPathToPathname(id));
3641 return _await$b(fetchHref(href), function (response) {
3642 var responseStatus = response.status;
3643
3644 if (!responseStatusIsOk(responseStatus)) {
3645 if (responseStatus === 404 && href === importMapHref) {
3646 // importMap file is optionnal
3647 return {
3648 code: "export default {}"
3649 };
3650 }
3651
3652 throw new Error(createUnexpectedResponseStatusMessage({
3653 responseStatus: responseStatus,
3654 href: href
3655 }));
3656 }
3657
3658 var source = response.body;
3659
3660 if (id.endsWith(".json")) {
3661 source = "export default ".concat(source);
3662 }
3663
3664 var sourcemapParsingResult = parseSourceMappingURL(source);
3665
3666 if (!sourcemapParsingResult) {
3667 return {
3668 code: source
3669 };
3670 }
3671
3672 if (sourcemapParsingResult.sourcemapString) {
3673 return {
3674 code: source,
3675 map: JSON.parse(sourcemapParsingResult.sourcemapString)
3676 };
3677 }
3678
3679 var resolvedSourceMappingURL = url$1.resolve(href, sourcemapParsingResult.sourcemapURL);
3680 return _await$b(fetchHref(resolvedSourceMappingURL), function (sourcemapResponse) {
3681 var sourcemapResponseStatus = sourcemapResponse.status;
3682
3683 if (!responseStatusIsOk(sourcemapResponse)) {
3684 logger.logWarning(createUnexpectedResponseStatusMessage({
3685 responseStatus: sourcemapResponseStatus,
3686 href: resolvedSourceMappingURL
3687 }));
3688 return {
3689 code: source
3690 };
3691 }
3692
3693 return {
3694 code: source,
3695 map: JSON.parse(sourcemapResponse.body)
3696 };
3697 });
3698 });
3699 });
3700 }),
3701 // resolveImportMeta: () => {}
3702 transform: _async$b(function (source, id) {
3703 if (idSkipTransformArray.includes(id)) {
3704 return null;
3705 }
3706
3707 var sourceHref;
3708
3709 if (isWindowsPath(id)) {
3710 sourceHref = "file://".concat(operatingSystemPathToPathname(id));
3711 } else if (hrefToScheme(id)) {
3712 sourceHref = id;
3713 } else {
3714 sourceHref = "file://".concat(operatingSystemPathToPathname(id));
3715 }
3716
3717 return _await$b(transformSource({
3718 projectPathname: projectPathname,
3719 source: source,
3720 sourceHref: sourceHref,
3721 babelPluginMap: babelPluginMap,
3722 convertMap: convertMap,
3723 // false, rollup will take care to transform module into whatever format
3724 transformModuleIntoSystemFormat: false
3725 }), function (_ref3) {
3726 var code = _ref3.code,
3727 map = _ref3.map;
3728 return {
3729 code: code,
3730 map: map
3731 };
3732 });
3733 }),
3734 renderChunk: function renderChunk(source) {
3735 if (!minify) return null; // https://github.com/terser-js/terser#minify-options
3736
3737 var minifyOptions = format === "global" ? {
3738 toplevel: false
3739 } : {
3740 toplevel: true
3741 };
3742 var result = minifyCode(source, _objectSpread2({
3743 sourceMap: true
3744 }, minifyOptions));
3745
3746 if (result.error) {
3747 throw result.error;
3748 } else {
3749 return result;
3750 }
3751 },
3752 writeBundle: _async$b(function (bundle) {
3753 return _invoke$3(function () {
3754 if (detectAndTransformIfNeededAsyncInsertedByRollup) {
3755 return _awaitIgnored$2(transformAsyncInsertedByRollup({
3756 dir: dir,
3757 babelPluginMap: babelPluginMap,
3758 bundle: bundle
3759 }));
3760 }
3761 }, function () {
3762 Object.keys(bundle).forEach(function (bundleFilename) {
3763 logger.log("-> ".concat(dir, "/").concat(bundleFilename));
3764 });
3765 });
3766 })
3767 };
3768
3769 var fetchHref = _async$b(function (href) {
3770 var _exit2 = false;
3771 // this code allow you to have http/https dependency for convenience
3772 // but maybe we should warn about this.
3773 // it could also be vastly improved using a basic in memory cache
3774 return _invoke$3(function () {
3775 if (href.startsWith("http://")) {
3776 return _await$b(fetchUsingHttp(href, {
3777 cancellationToken: cancellationToken
3778 }), function (response) {
3779 _exit2 = true;
3780 return response;
3781 });
3782 }
3783 }, function (_result2) {
3784 var _exit3 = false;
3785 if (_exit2) return _result2;
3786 return _invoke$3(function () {
3787 if (href.startsWith("https://")) {
3788 return _await$b(fetchUsingHttp(href, {
3789 cancellationToken: cancellationToken
3790 }), function (response) {
3791 _exit3 = true;
3792 return response;
3793 });
3794 }
3795 }, function (_result3) {
3796 var _exit4 = false;
3797 if (_exit3) return _result3;
3798 return _invoke$3(function () {
3799 if (href.startsWith("file:///")) {
3800 return _await$b(createOperation({
3801 cancellationToken: cancellationToken,
3802 start: function start() {
3803 return fileRead(pathnameToOperatingSystemPath(hrefToPathname(href)));
3804 }
3805 }), function (code) {
3806 _exit4 = true;
3807 return {
3808 status: 200,
3809 body: code
3810 };
3811 });
3812 }
3813 }, function (_result4) {
3814 if (_exit4) return _result4;
3815 throw new Error("unsupported href: ".concat(href));
3816 });
3817 });
3818 });
3819 });
3820
3821 return {
3822 jsenvRollupPlugin: jsenvRollupPlugin,
3823 relativePathAbstractArray: Object.keys(specifierDynamicMap),
3824 getRollupGenerateOptions: getRollupGenerateOptions
3825 };
3826 });
3827 });
3828});
3829
3830var responseStatusIsOk = function responseStatusIsOk(responseStatus) {
3831 return responseStatus >= 200 && responseStatus < 300;
3832};
3833
3834var createUnexpectedResponseStatusMessage = function createUnexpectedResponseStatusMessage(_ref4) {
3835 var responseStatus = _ref4.responseStatus,
3836 href = _ref4.href;
3837 return "unexpected response status.\n--- response status ---\n".concat(responseStatus, "\n--- href ---\n").concat(href);
3838};
3839
3840var createMustBeInsideProjectMessage = function createMustBeInsideProjectMessage(_ref5) {
3841 var resolvedId = _ref5.resolvedId,
3842 specifier = _ref5.specifier,
3843 importer = _ref5.importer,
3844 projectPathname = _ref5.projectPathname;
3845 return "\nresolved id must be inside project.\n--- resolved id ---\n".concat(resolvedId, "\n--- specifier ---\n").concat(specifier, "\n--- importer ---\n").concat(importer, "\n--- project path ---\n").concat(pathnameToOperatingSystemPath(projectPathname));
3846};
3847
3848var createImporterOutsideProjectError = function createImporterOutsideProjectError(_ref6) {
3849 var importer = _ref6.importer,
3850 projectPathname = _ref6.projectPathname;
3851 return new Error("importer must be inside project\n importer: ".concat(importer, "\n project: ").concat(pathnameToOperatingSystemPath(projectPathname)));
3852};
3853
3854var transformAsyncInsertedByRollup = _async$b(function (_ref7) {
3855 var dir = _ref7.dir,
3856 babelPluginMap = _ref7.babelPluginMap,
3857 bundle = _ref7.bundle;
3858 var asyncPluginName = findAsyncPluginNameInBabelPluginMap(babelPluginMap);
3859 if (!asyncPluginName) return; // we have to do this because rollup ads
3860 // an async wrapper function without transpiling it
3861 // if your bundle contains a dynamic import
3862
3863 return _awaitIgnored$2(Promise.all(Object.keys(bundle).map(_async$b(function (bundleFilename) {
3864 var bundleInfo = bundle[bundleFilename];
3865 return _await$b(jsenvTransform({
3866 inputCode: bundleInfo.code,
3867 inputMap: bundleInfo.map,
3868 inputPath: bundleFilename,
3869 babelPluginMap: _defineProperty({}, asyncPluginName, babelPluginMap[asyncPluginName]),
3870 transformModuleIntoSystemFormat: false // already done by rollup
3871
3872 }), function (_ref8) {
3873 var code = _ref8.code,
3874 map = _ref8.map;
3875 return _awaitIgnored$2(Promise.all([fileWrite("".concat(dir, "/").concat(bundleFilename), writeSourceMappingURL(code, "./".concat(bundleFilename, ".map"))), fileWrite("".concat(dir, "/").concat(bundleFilename, ".map"), JSON.stringify(map))]));
3876 });
3877 }))));
3878});
3879
3880function _await$c(value, then, direct) {
3881 if (direct) {
3882 return then ? then(value) : value;
3883 }
3884
3885 if (!value || !value.then) {
3886 value = Promise.resolve(value);
3887 }
3888
3889 return then ? value.then(then) : value;
3890}
3891
3892var _require2$5 = nodeRequire("rollup"),
3893 rollup = _require2$5.rollup;
3894
3895function _async$c(f) {
3896 return function () {
3897 for (var args = [], i = 0; i < arguments.length; i++) {
3898 args[i] = arguments[i];
3899 }
3900
3901 try {
3902 return Promise.resolve(f.apply(this, args));
3903 } catch (e) {
3904 return Promise.reject(e);
3905 }
3906 };
3907}
3908
3909var generateBundleUsingRollup = _async$c(function (_ref) {
3910 var cancellationToken = _ref.cancellationToken,
3911 rollupParseOptions = _ref.rollupParseOptions,
3912 rollupGenerateOptions = _ref.rollupGenerateOptions,
3913 writeOnFileSystem = _ref.writeOnFileSystem;
3914 return _await$c(createOperation({
3915 cancellationToken: cancellationToken,
3916 start: function start() {
3917 return rollup(_objectSpread2({
3918 // about cache here, we should/could reuse previous rollup call
3919 // to get the cache from the entryPointMap
3920 // as shown here: https://rollupjs.org/guide/en#cache
3921 // it could be passed in arguments to this function
3922 // however parallelism and having different rollup options per
3923 // call make it a bit complex
3924 // cache: null
3925 // https://rollupjs.org/guide/en#experimentaltoplevelawait
3926 experimentalTopLevelAwait: true,
3927 // if we want to ignore some warning
3928 // please use https://rollupjs.org/guide/en#onwarn
3929 // to be very clear about what we want to ignore
3930 onwarn: function onwarn(warning, warn) {
3931 if (warningIsThisIsUndefinedFromGlobalThis(warning)) return;
3932 warn(warning);
3933 }
3934 }, rollupParseOptions));
3935 }
3936 }), function (rollupBundle) {
3937 return _await$c(createOperation({
3938 cancellationToken: cancellationToken,
3939 start: function start() {
3940 if (writeOnFileSystem) {
3941 return rollupBundle.write(_objectSpread2({
3942 // https://rollupjs.org/guide/en#experimentaltoplevelawait
3943 experimentalTopLevelAwait: true,
3944 // we could put prefConst to true by checking 'transform-block-scoping'
3945 // presence in babelPluginMap
3946 preferConst: false
3947 }, rollupGenerateOptions));
3948 }
3949
3950 return rollupBundle.generate(_objectSpread2({
3951 // https://rollupjs.org/guide/en#experimentaltoplevelawait
3952 experimentalTopLevelAwait: true,
3953 // we could put prefConst to true by checking 'transform-block-scoping'
3954 // presence in babelPluginMap
3955 preferConst: false
3956 }, rollupGenerateOptions));
3957 }
3958 }));
3959 });
3960});
3961
3962var warningIsThisIsUndefinedFromGlobalThis = function warningIsThisIsUndefinedFromGlobalThis(_ref2) {
3963 var code = _ref2.code,
3964 loc = _ref2.loc;
3965 if (code !== "THIS_IS_UNDEFINED") return false;
3966 if (!loc) return false;
3967 var file = loc.file;
3968 if (file.endsWith("/.jsenv/helpers/global-this.js")) return true;
3969 if (file.endsWith("\\.jsenv\\helpers\\global-this.js")) return true;
3970 return false;
3971};
3972
3973var formatToRollupFormat = function formatToRollupFormat(format) {
3974 if (format === "global") return "iife";
3975 if (format === "commonjs") return "cjs";
3976 if (format === "systemjs") return "system";
3977 throw new Error("unexpected format, got ".concat(format));
3978};
3979
3980function _await$d(value, then, direct) {
3981 if (direct) {
3982 return then ? then(value) : value;
3983 }
3984
3985 if (!value || !value.then) {
3986 value = Promise.resolve(value);
3987 }
3988
3989 return then ? value.then(then) : value;
3990}
3991
3992function _call$1(body, then, direct) {
3993 if (direct) {
3994 return then ? then(body()) : body();
3995 }
3996
3997 try {
3998 var result = Promise.resolve(body());
3999 return then ? result.then(then) : result;
4000 } catch (e) {
4001 return Promise.reject(e);
4002 }
4003}
4004
4005function _async$d(f) {
4006 return function () {
4007 for (var args = [], i = 0; i < arguments.length; i++) {
4008 args[i] = arguments[i];
4009 }
4010
4011 try {
4012 return Promise.resolve(f.apply(this, args));
4013 } catch (e) {
4014 return Promise.reject(e);
4015 }
4016 };
4017}
4018
4019var bundleWithoutBalancing = _async$d(function (_ref) {
4020 var cancellationToken = _ref.cancellationToken,
4021 projectPathname = _ref.projectPathname,
4022 bundleIntoRelativePath = _ref.bundleIntoRelativePath,
4023 importDefaultExtension = _ref.importDefaultExtension,
4024 importMapRelativePath = _ref.importMapRelativePath,
4025 importMapForBundle = _ref.importMapForBundle,
4026 specifierMap = _ref.specifierMap,
4027 specifierDynamicMap = _ref.specifierDynamicMap,
4028 nativeModulePredicate = _ref.nativeModulePredicate,
4029 entryPointMap = _ref.entryPointMap,
4030 babelPluginMap = _ref.babelPluginMap,
4031 convertMap = _ref.convertMap,
4032 minify = _ref.minify,
4033 logLevel = _ref.logLevel,
4034 format = _ref.format,
4035 formatOutputOptions = _ref.formatOutputOptions,
4036 writeOnFileSystem = _ref.writeOnFileSystem;
4037 var logger = createLogger({
4038 logLevel: logLevel
4039 });
4040 var dir = pathnameToOperatingSystemPath("".concat(projectPathname).concat(bundleIntoRelativePath));
4041 return _await$d(createJsenvRollupPlugin({
4042 cancellationToken: cancellationToken,
4043 projectPathname: projectPathname,
4044 dir: dir,
4045 entryPointMap: entryPointMap,
4046 importDefaultExtension: importDefaultExtension,
4047 importMapRelativePath: importMapRelativePath,
4048 importMapForBundle: importMapForBundle,
4049 specifierMap: specifierMap,
4050 specifierDynamicMap: specifierDynamicMap,
4051 babelPluginMap: babelPluginMap,
4052 convertMap: convertMap,
4053 featureNameArray: Object.keys(babelPluginMap),
4054 minify: minify,
4055 format: format,
4056 logger: logger
4057 }), function (_ref2) {
4058 var jsenvRollupPlugin = _ref2.jsenvRollupPlugin,
4059 relativePathAbstractArray = _ref2.relativePathAbstractArray,
4060 getRollupGenerateOptions = _ref2.getRollupGenerateOptions;
4061 var importFromGlobalRollupPlugin = createImportFromGlobalRollupPlugin({
4062 platformGlobalName: "globalThis"
4063 });
4064 logger.logTrace("\nbundle entry points without balancing.\nformat: ".concat(format, "\nentry point names: ").concat(Object.keys(entryPointMap), "\ndir: ").concat(dir, "\nminify: ").concat(minify, "\n"));
4065 return _call$1(getRollupGenerateOptions, function (rollupGenerateOptions) {
4066 return _await$d(generateBundleUsingRollup({
4067 cancellationToken: cancellationToken,
4068 writeOnFileSystem: writeOnFileSystem,
4069 rollupParseOptions: {
4070 input: entryPointMap,
4071 plugins: [importFromGlobalRollupPlugin, jsenvRollupPlugin],
4072 external: function external(id) {
4073 return nativeModulePredicate(id);
4074 }
4075 },
4076 rollupGenerateOptions: _objectSpread2({
4077 // https://rollupjs.org/guide/en#output-dir
4078 dir: dir,
4079 // https://rollupjs.org/guide/en#output-format
4080 format: formatToRollupFormat(format),
4081 // entryFileNames: `./[name].js`,
4082 // https://rollupjs.org/guide/en#output-sourcemap
4083 sourcemap: true,
4084 // we could exclude them
4085 // but it's better to put them directly
4086 // in case source files are not reachable
4087 // for whatever reason
4088 sourcemapExcludeSources: false
4089 }, rollupGenerateOptions, {}, formatOutputOptions)
4090 }), function (rollupBundle) {
4091 return {
4092 rollupBundle: rollupBundle,
4093 relativePathAbstractArray: relativePathAbstractArray
4094 };
4095 });
4096 });
4097 });
4098});
4099
4100function _await$e(value, then, direct) {
4101 if (direct) {
4102 return then ? then(value) : value;
4103 }
4104
4105 if (!value || !value.then) {
4106 value = Promise.resolve(value);
4107 }
4108
4109 return then ? value.then(then) : value;
4110}
4111
4112function _async$e(f) {
4113 return function () {
4114 for (var args = [], i = 0; i < arguments.length; i++) {
4115 args[i] = arguments[i];
4116 }
4117
4118 try {
4119 return Promise.resolve(f.apply(this, args));
4120 } catch (e) {
4121 return Promise.reject(e);
4122 }
4123 };
4124}
4125
4126var bundleWithBalancing = _async$e(function (_ref) {
4127 var cancellationToken = _ref.cancellationToken,
4128 projectPathname = _ref.projectPathname,
4129 bundleIntoRelativePath = _ref.bundleIntoRelativePath,
4130 importDefaultExtension = _ref.importDefaultExtension,
4131 importMapRelativePath = _ref.importMapRelativePath,
4132 importMapForBundle = _ref.importMapForBundle,
4133 specifierMap = _ref.specifierMap,
4134 specifierDynamicMap = _ref.specifierDynamicMap,
4135 nativeModulePredicate = _ref.nativeModulePredicate,
4136 entryPointMap = _ref.entryPointMap,
4137 babelPluginMap = _ref.babelPluginMap,
4138 convertMap = _ref.convertMap,
4139 minify = _ref.minify,
4140 logLevel = _ref.logLevel,
4141 format = _ref.format,
4142 formatOutputOptions = _ref.formatOutputOptions,
4143 groupMap = _ref.groupMap,
4144 compileId = _ref.compileId,
4145 writeOnFileSystem = _ref.writeOnFileSystem;
4146 var logger = createLogger({
4147 logLevel: logLevel
4148 });
4149 var dir = pathnameToOperatingSystemPath("".concat(projectPathname).concat(bundleIntoRelativePath, "/").concat(compileId));
4150 return _await$e(createJsenvRollupPlugin({
4151 cancellationToken: cancellationToken,
4152 projectPathname: projectPathname,
4153 dir: dir,
4154 entryPointMap: entryPointMap,
4155 importDefaultExtension: importDefaultExtension,
4156 importMapRelativePath: importMapRelativePath,
4157 importMapForBundle: importMapForBundle,
4158 specifierMap: specifierMap,
4159 specifierDynamicMap: specifierDynamicMap,
4160 babelPluginMap: babelPluginMap,
4161 convertMap: convertMap,
4162 featureNameArray: groupMap[compileId].incompatibleNameArray,
4163 minify: minify,
4164 format: format,
4165 logger: logger
4166 }), function (_ref2) {
4167 var jsenvRollupPlugin = _ref2.jsenvRollupPlugin;
4168 var importFromGlobalRollupPlugin = createImportFromGlobalRollupPlugin({
4169 platformGlobalName: "globalThis"
4170 });
4171 logger.logTrace("\n bundle entry points with balancing.\n format: ".concat(format, "\n compileId: ").concat(compileId, "\n entryPointArray: ").concat(Object.keys(entryPointMap), "\n dir: ").concat(dir, "\n minify: ").concat(minify, "\n "));
4172 return _await$e(generateBundleUsingRollup({
4173 cancellationToken: cancellationToken,
4174 writeOnFileSystem: writeOnFileSystem,
4175 rollupParseOptions: {
4176 input: entryPointMap,
4177 plugins: [importFromGlobalRollupPlugin, jsenvRollupPlugin],
4178 external: function external(id) {
4179 return nativeModulePredicate(id);
4180 }
4181 },
4182 rollupGenerateOptions: _objectSpread2({
4183 dir: dir,
4184 format: formatToRollupFormat(format),
4185 sourcemap: true,
4186 sourceMapExcludeSources: true
4187 }, formatOutputOptions)
4188 }), function (rollupBundle) {
4189 return {
4190 rollupBundle: rollupBundle
4191 };
4192 });
4193 });
4194});
4195
4196function _await$f(value, then, direct) {
4197 if (direct) {
4198 return then ? then(value) : value;
4199 }
4200
4201 if (!value || !value.then) {
4202 value = Promise.resolve(value);
4203 }
4204
4205 return then ? value.then(then) : value;
4206}
4207
4208function _async$f(f) {
4209 return function () {
4210 for (var args = [], i = 0; i < arguments.length; i++) {
4211 args[i] = arguments[i];
4212 }
4213
4214 try {
4215 return Promise.resolve(f.apply(this, args));
4216 } catch (e) {
4217 return Promise.reject(e);
4218 }
4219 };
4220}
4221
4222var bundleBalancer = _async$f(function (_ref) {
4223 var cancellationToken = _ref.cancellationToken,
4224 projectPathname = _ref.projectPathname,
4225 bundleIntoRelativePath = _ref.bundleIntoRelativePath,
4226 importDefaultExtension = _ref.importDefaultExtension,
4227 importMapRelativePath = _ref.importMapRelativePath,
4228 importMapForBundle = _ref.importMapForBundle,
4229 specifierMap = _ref.specifierMap,
4230 specifierDynamicMap = _ref.specifierDynamicMap,
4231 nativeModulePredicate = _ref.nativeModulePredicate,
4232 entryPointMap = _ref.entryPointMap,
4233 babelPluginMap = _ref.babelPluginMap,
4234 convertMap = _ref.convertMap,
4235 minify = _ref.minify,
4236 logLevel = _ref.logLevel,
4237 format = _ref.format,
4238 balancerDataClientPathname = _ref.balancerDataClientPathname,
4239 groupMap = _ref.groupMap,
4240 writeOnFileSystem = _ref.writeOnFileSystem;
4241 var logger = createLogger({
4242 logLevel: logLevel
4243 });
4244 var entryPointName = Object.keys(entryPointMap)[0];
4245 var dir = pathnameToOperatingSystemPath("".concat(projectPathname).concat(bundleIntoRelativePath));
4246 return _await$f(createJsenvRollupPlugin({
4247 cancellationToken: cancellationToken,
4248 projectPathname: projectPathname,
4249 dir: dir,
4250 entryPointMap: entryPointMap,
4251 importDefaultExtension: importDefaultExtension,
4252 importMapRelativePath: importMapRelativePath,
4253 importMapForBundle: importMapForBundle,
4254 specifierMap: specifierMap,
4255 specifierDynamicMap: _objectSpread2({}, specifierDynamicMap, _defineProperty({}, balancerDataClientPathname, function () {
4256 return "export const entryPointName = ".concat(JSON.stringify(entryPointName), "\n export const groupMap = ").concat(JSON.stringify(groupMap));
4257 })),
4258 babelPluginMap: babelPluginMap,
4259 convertMap: convertMap,
4260 featureNameArray: groupMap.otherwise.incompatibleNameArray,
4261 minify: minify,
4262 format: format,
4263 logger: logger
4264 }), function (_ref2) {
4265 var jsenvRollupPlugin = _ref2.jsenvRollupPlugin;
4266 var importFromGlobalRollupPlugin = createImportFromGlobalRollupPlugin({
4267 platformGlobalName: "globalThis"
4268 });
4269 logger.logTrace("\n bundle balancer file.\n format: ".concat(format, "\n entryPointName: ").concat(entryPointName, "\n file: ").concat(dir, "/").concat(entryPointName, ".js\n minify: ").concat(minify, "\n "));
4270 return _await$f(generateBundleUsingRollup({
4271 cancellationToken: cancellationToken,
4272 writeOnFileSystem: writeOnFileSystem,
4273 rollupParseOptions: {
4274 input: entryPointMap,
4275 plugins: [importFromGlobalRollupPlugin, jsenvRollupPlugin],
4276 external: function external(id) {
4277 return nativeModulePredicate(id);
4278 }
4279 },
4280 rollupGenerateOptions: {
4281 dir: dir,
4282 format: "iife",
4283 sourcemap: true,
4284 sourcemapExcludeSources: true
4285 }
4286 }), function (rollupBundle) {
4287 return {
4288 rollupBundle: rollupBundle
4289 };
4290 });
4291 });
4292});
4293
4294var rimraf = nodeRequire("rimraf");
4295
4296var removeFolder = function removeFolder(foldername) {
4297 return new Promise(function (resolve, reject) {
4298 return rimraf(foldername, function (error) {
4299 if (error) reject(error);else resolve();
4300 });
4301 });
4302};
4303
4304// https://github.com/browserify/resolve/blob/a09a2e7f16273970be4639313c83b913daea15d7/lib/core.json#L1
4305// https://nodejs.org/api/modules.html#modules_module_builtinmodules
4306// https://stackoverflow.com/a/35825896
4307// https://github.com/browserify/resolve/blob/master/lib/core.json#L1
4308var NATIVE_NODE_MODULE_SPECIFIER_ARRAY = ["assert", "async_hooks", "buffer_ieee754", "buffer", "child_process", "cluster", "console", "constants", "crypto", "_debugger", "dgram", "dns", "domain", "events", "freelist", "fs", "fs/promises", "_http_agent", "_http_client", "_http_common", "_http_incoming", "_http_outgoing", "_http_server", "http", "http2", "https", "inspector", "_linklist", "module", "net", "node-inspect/lib/_inspect", "node-inspect/lib/internal/inspect_client", "node-inspect/lib/internal/inspect_repl", "os", "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "smalloc", "_stream_duplex", "_stream_transform", "_stream_wrap", "_stream_passthrough", "_stream_readable", "_stream_writable", "stream", "string_decoder", "sys", "timers", "_tls_common", "_tls_legacy", "_tls_wrap", "tls", "trace_events", "tty", "url", "util", "v8/tools/arguments", "v8/tools/codemap", "v8/tools/consarray", "v8/tools/csvparser", "v8/tools/logreader", "v8/tools/profile_view", "v8/tools/splaytree", "v8", "vm", "worker_threads", "zlib", // global is special
4309"global"];
4310var isNativeNodeModuleBareSpecifier = function isNativeNodeModuleBareSpecifier(specifier) {
4311 return NATIVE_NODE_MODULE_SPECIFIER_ARRAY.includes(specifier);
4312};
4313
4314var _require2$6 = nodeRequire("@jsenv/babel-plugin-map"),
4315 jsenvBabelPluginMap = _require2$6.jsenvBabelPluginMap;
4316
4317var DEFAULT_IMPORT_MAP_RELATIVE_PATH = "/importMap.json";
4318var DEFAULT_ENTRY_POINT_MAP = {
4319 main: "index.js"
4320};
4321var DEFAULT_NATIVE_MODULE_PREDICATE = function DEFAULT_NATIVE_MODULE_PREDICATE(id) {
4322 // the global specifier is also in @jsenv/compile-server
4323 if (id === "global") return true;
4324 if (isNativeNodeModuleBareSpecifier(id)) return true;
4325 return false;
4326};
4327var DEFAULT_BABEL_PLUGIN_MAP = jsenvBabelPluginMap;
4328var DEFAULT_PLATFORM_SCORE_MAP = _objectSpread2({}, browserScoreMap, {
4329 node: nodeVersionScoreMap
4330});
4331
4332function _empty$4() {}
4333
4334function _awaitIgnored$3(value, direct) {
4335 if (!direct) {
4336 return value && value.then ? value.then(_empty$4) : Promise.resolve();
4337 }
4338}
4339
4340function _await$g(value, then, direct) {
4341 if (direct) {
4342 return then ? then(value) : value;
4343 }
4344
4345 if (!value || !value.then) {
4346 value = Promise.resolve(value);
4347 }
4348
4349 return then ? value.then(then) : value;
4350}
4351
4352function _invoke$4(body, then) {
4353 var result = body();
4354
4355 if (result && result.then) {
4356 return result.then(then);
4357 }
4358
4359 return then(result);
4360}
4361
4362function _async$g(f) {
4363 return function () {
4364 for (var args = [], i = 0; i < arguments.length; i++) {
4365 args[i] = arguments[i];
4366 }
4367
4368 try {
4369 return Promise.resolve(f.apply(this, args));
4370 } catch (e) {
4371 return Promise.reject(e);
4372 }
4373 };
4374}
4375
4376var generateBundle = function generateBundle(_ref) {
4377 var projectPath = _ref.projectPath,
4378 bundleIntoRelativePath = _ref.bundleIntoRelativePath,
4379 _ref$cleanBundleInto = _ref.cleanBundleInto,
4380 cleanBundleInto = _ref$cleanBundleInto === void 0 ? false : _ref$cleanBundleInto,
4381 importDefaultExtension = _ref.importDefaultExtension,
4382 _ref$importMapRelativ = _ref.importMapRelativePath,
4383 importMapRelativePath = _ref$importMapRelativ === void 0 ? DEFAULT_IMPORT_MAP_RELATIVE_PATH : _ref$importMapRelativ,
4384 importMapForBundle = _ref.importMapForBundle,
4385 specifierMap = _ref.specifierMap,
4386 specifierDynamicMap = _ref.specifierDynamicMap,
4387 _ref$nativeModulePred = _ref.nativeModulePredicate,
4388 nativeModulePredicate = _ref$nativeModulePred === void 0 ? DEFAULT_NATIVE_MODULE_PREDICATE : _ref$nativeModulePred,
4389 _ref$entryPointMap = _ref.entryPointMap,
4390 entryPointMap = _ref$entryPointMap === void 0 ? DEFAULT_ENTRY_POINT_MAP : _ref$entryPointMap,
4391 _ref$babelPluginMap = _ref.babelPluginMap,
4392 babelPluginMap = _ref$babelPluginMap === void 0 ? DEFAULT_BABEL_PLUGIN_MAP : _ref$babelPluginMap,
4393 convertMap = _ref.convertMap,
4394 _ref$logLevel = _ref.logLevel,
4395 logLevel = _ref$logLevel === void 0 ? LOG_LEVEL_ERRORS_WARNINGS_AND_LOGS : _ref$logLevel,
4396 _ref$minify = _ref.minify,
4397 minify = _ref$minify === void 0 ? false : _ref$minify,
4398 _ref$writeOnFileSyste = _ref.writeOnFileSystem,
4399 writeOnFileSystem = _ref$writeOnFileSyste === void 0 ? true : _ref$writeOnFileSyste,
4400 _ref$throwUnhandled = _ref.throwUnhandled,
4401 throwUnhandled = _ref$throwUnhandled === void 0 ? true : _ref$throwUnhandled,
4402 format = _ref.format,
4403 _ref$formatOutputOpti = _ref.formatOutputOptions,
4404 formatOutputOptions = _ref$formatOutputOpti === void 0 ? {} : _ref$formatOutputOpti,
4405 _ref$compileGroupCoun = _ref.compileGroupCount,
4406 compileGroupCount = _ref$compileGroupCoun === void 0 ? 1 : _ref$compileGroupCoun,
4407 platformAlwaysInsidePlatformScoreMap = _ref.platformAlwaysInsidePlatformScoreMap,
4408 balancerTemplateRelativePath = _ref.balancerTemplateRelativePath,
4409 defaultBalancerTemplateRelativePath = _ref.defaultBalancerTemplateRelativePath,
4410 balancerDataClientPathname = _ref.balancerDataClientPathname,
4411 _ref$platformScoreMap = _ref.platformScoreMap,
4412 platformScoreMap = _ref$platformScoreMap === void 0 ? DEFAULT_PLATFORM_SCORE_MAP : _ref$platformScoreMap;
4413 var promise = catchAsyncFunctionCancellation(_async$g(function () {
4414 if (typeof projectPath !== "string") throw new TypeError("projectPath must be a string, got ".concat(projectPath));
4415 if (typeof bundleIntoRelativePath !== "string") throw new TypeError("bundleIntoRelativePath must be a string, got ".concat(bundleIntoRelativePath));
4416 if (_typeof(entryPointMap) !== "object") throw new TypeError("entryPointMap must be an object, got ".concat(entryPointMap));
4417 if (typeof compileGroupCount !== "number") throw new TypeError("compileGroupCount must be a number, got ".concat(compileGroupCount));
4418 if (compileGroupCount < 1) throw new Error("compileGroupCount must be >= 1, got ".concat(compileGroupCount));
4419 var cancellationToken = createProcessInterruptionCancellationToken();
4420 var projectPathname = operatingSystemPathToPathname(projectPath);
4421 return _await$g(assertFolder(projectPathname), function () {
4422 return _invoke$4(function () {
4423 if (cleanBundleInto) return _awaitIgnored$3(removeFolder(pathnameToOperatingSystemPath("".concat(projectPathname).concat(bundleIntoRelativePath))));
4424 }, function () {
4425 if (compileGroupCount === 1) {
4426 return bundleWithoutBalancing({
4427 cancellationToken: cancellationToken,
4428 projectPathname: projectPathname,
4429 bundleIntoRelativePath: bundleIntoRelativePath,
4430 importDefaultExtension: importDefaultExtension,
4431 importMapRelativePath: importMapRelativePath,
4432 importMapForBundle: importMapForBundle,
4433 specifierMap: specifierMap,
4434 specifierDynamicMap: specifierDynamicMap,
4435 nativeModulePredicate: nativeModulePredicate,
4436 entryPointMap: entryPointMap,
4437 babelPluginMap: babelPluginMap,
4438 convertMap: convertMap,
4439 minify: minify,
4440 logLevel: logLevel,
4441 format: format,
4442 formatOutputOptions: formatOutputOptions,
4443 writeOnFileSystem: writeOnFileSystem
4444 });
4445 }
4446
4447 if (typeof balancerTemplateRelativePath === "undefined") {
4448 if (!defaultBalancerTemplateRelativePath) {
4449 throw createFormatIncompatibleWithBalancingError({
4450 format: format
4451 });
4452 }
4453
4454 balancerTemplateRelativePath = jsenvBundlingRelativePathInception({
4455 jsenvBundlingRelativePath: defaultBalancerTemplateRelativePath,
4456 projectPathname: projectPathname
4457 });
4458 }
4459
4460 return _await$g(assertFile(pathnameToOperatingSystemPath("".concat(projectPathname).concat(balancerTemplateRelativePath))), function () {
4461 var groupMap = generateGroupMap({
4462 babelPluginMap: babelPluginMap,
4463 platformScoreMap: platformScoreMap,
4464 groupCount: compileGroupCount,
4465 platformAlwaysInsidePlatformScoreMap: platformAlwaysInsidePlatformScoreMap
4466 });
4467 return _await$g(Promise.all([generateEntryPointsFolders({
4468 cancellationToken: cancellationToken,
4469 projectPathname: projectPathname,
4470 bundleIntoRelativePath: bundleIntoRelativePath,
4471 importDefaultExtension: importDefaultExtension,
4472 importMapRelativePath: importMapRelativePath,
4473 importMapForBundle: importMapForBundle,
4474 specifierMap: specifierMap,
4475 specifierDynamicMap: specifierDynamicMap,
4476 nativeModulePredicate: nativeModulePredicate,
4477 entryPointMap: entryPointMap,
4478 babelPluginMap: babelPluginMap,
4479 convertMap: convertMap,
4480 minify: minify,
4481 logLevel: logLevel,
4482 writeOnFileSystem: writeOnFileSystem,
4483 format: format,
4484 formatOutputOptions: formatOutputOptions,
4485 groupMap: groupMap
4486 }), generateEntryPointsBalancerFiles({
4487 cancellationToken: cancellationToken,
4488 projectPathname: projectPathname,
4489 bundleIntoRelativePath: bundleIntoRelativePath,
4490 importDefaultExtension: importDefaultExtension,
4491 importMapRelativePath: importMapRelativePath,
4492 importMapForBundle: importMapForBundle,
4493 specifierMap: specifierMap,
4494 specifierDynamicMap: specifierDynamicMap,
4495 nativeModulePredicate: nativeModulePredicate,
4496 entryPointMap: entryPointMap,
4497 babelPluginMap: babelPluginMap,
4498 convertMap: convertMap,
4499 minify: minify,
4500 logLevel: logLevel,
4501 writeOnFileSystem: writeOnFileSystem,
4502 format: format,
4503 balancerTemplateRelativePath: balancerTemplateRelativePath,
4504 balancerDataClientPathname: balancerDataClientPathname,
4505 groupMap: groupMap
4506 })]));
4507 });
4508 });
4509 });
4510 }));
4511 if (!throwUnhandled) return promise;
4512 return promise.catch(function (e) {
4513 setTimeout(function () {
4514 throw e;
4515 });
4516 });
4517};
4518
4519var generateEntryPointsFolders = _async$g(function (_ref2) {
4520 var cancellationToken = _ref2.cancellationToken,
4521 projectPathname = _ref2.projectPathname,
4522 bundleIntoRelativePath = _ref2.bundleIntoRelativePath,
4523 importDefaultExtension = _ref2.importDefaultExtension,
4524 importMapRelativePath = _ref2.importMapRelativePath,
4525 importMapForBundle = _ref2.importMapForBundle,
4526 specifierMap = _ref2.specifierMap,
4527 specifierDynamicMap = _ref2.specifierDynamicMap,
4528 nativeModulePredicate = _ref2.nativeModulePredicate,
4529 entryPointMap = _ref2.entryPointMap,
4530 babelPluginMap = _ref2.babelPluginMap,
4531 convertMap = _ref2.convertMap,
4532 minify = _ref2.minify,
4533 logLevel = _ref2.logLevel,
4534 writeOnFileSystem = _ref2.writeOnFileSystem,
4535 format = _ref2.format,
4536 formatOutputOptions = _ref2.formatOutputOptions,
4537 groupMap = _ref2.groupMap;
4538 return Promise.all(Object.keys(groupMap).map(_async$g(function (compileId) {
4539 return bundleWithBalancing({
4540 cancellationToken: cancellationToken,
4541 projectPathname: projectPathname,
4542 bundleIntoRelativePath: bundleIntoRelativePath,
4543 importDefaultExtension: importDefaultExtension,
4544 importMapRelativePath: importMapRelativePath,
4545 importMapForBundle: importMapForBundle,
4546 specifierMap: specifierMap,
4547 specifierDynamicMap: specifierDynamicMap,
4548 nativeModulePredicate: nativeModulePredicate,
4549 entryPointMap: entryPointMap,
4550 babelPluginMap: babelPluginMap,
4551 convertMap: convertMap,
4552 minify: minify,
4553 logLevel: logLevel,
4554 format: format,
4555 formatOutputOptions: formatOutputOptions,
4556 groupMap: groupMap,
4557 compileId: compileId,
4558 writeOnFileSystem: writeOnFileSystem
4559 });
4560 })));
4561});
4562
4563var generateEntryPointsBalancerFiles = function generateEntryPointsBalancerFiles(_ref3) {
4564 var cancellationToken = _ref3.cancellationToken,
4565 projectPathname = _ref3.projectPathname,
4566 bundleIntoRelativePath = _ref3.bundleIntoRelativePath,
4567 importDefaultExtension = _ref3.importDefaultExtension,
4568 importMapRelativePath = _ref3.importMapRelativePath,
4569 importMapForBundle = _ref3.importMapForBundle,
4570 specifierMap = _ref3.specifierMap,
4571 specifierDynamicMap = _ref3.specifierDynamicMap,
4572 nativeModulePredicate = _ref3.nativeModulePredicate,
4573 entryPointMap = _ref3.entryPointMap,
4574 babelPluginMap = _ref3.babelPluginMap,
4575 convertMap = _ref3.convertMap,
4576 minify = _ref3.minify,
4577 logLevel = _ref3.logLevel,
4578 writeOnFileSystem = _ref3.writeOnFileSystem,
4579 format = _ref3.format,
4580 balancerTemplateRelativePath = _ref3.balancerTemplateRelativePath,
4581 balancerDataClientPathname = _ref3.balancerDataClientPathname,
4582 groupMap = _ref3.groupMap;
4583 return Promise.all(Object.keys(entryPointMap).map(_async$g(function (entryPointName) {
4584 return bundleBalancer({
4585 cancellationToken: cancellationToken,
4586 projectPathname: projectPathname,
4587 bundleIntoRelativePath: bundleIntoRelativePath,
4588 importDefaultExtension: importDefaultExtension,
4589 importMapRelativePath: importMapRelativePath,
4590 importMapForBundle: importMapForBundle,
4591 specifierMap: specifierMap,
4592 specifierDynamicMap: specifierDynamicMap,
4593 nativeModulePredicate: nativeModulePredicate,
4594 entryPointMap: _defineProperty({}, entryPointName, balancerTemplateRelativePath),
4595 babelPluginMap: babelPluginMap,
4596 convertMap: convertMap,
4597 minify: minify,
4598 logLevel: logLevel,
4599 format: format,
4600 balancerDataClientPathname: balancerDataClientPathname,
4601 groupMap: groupMap,
4602 writeOnFileSystem: writeOnFileSystem
4603 });
4604 })));
4605};
4606
4607var createFormatIncompatibleWithBalancingError = function createFormatIncompatibleWithBalancingError(_ref4) {
4608 var format = _ref4.format;
4609 return new Error("format not compatible with balancing.\nformat: ".concat(format));
4610};
4611
4612var DEFAULT_BUNDLE_INTO_RELATIVE_PATH = "/dist/global";
4613
4614function _async$h(f) {
4615 return function () {
4616 for (var args = [], i = 0; i < arguments.length; i++) {
4617 args[i] = arguments[i];
4618 }
4619
4620 try {
4621 return Promise.resolve(f.apply(this, args));
4622 } catch (e) {
4623 return Promise.reject(e);
4624 }
4625 };
4626}
4627
4628var generateGlobalBundle = _async$h(function (_ref) {
4629 var projectPath = _ref.projectPath,
4630 _ref$bundleIntoRelati = _ref.bundleIntoRelativePath,
4631 bundleIntoRelativePath = _ref$bundleIntoRelati === void 0 ? DEFAULT_BUNDLE_INTO_RELATIVE_PATH : _ref$bundleIntoRelati,
4632 cleanBundleInto = _ref.cleanBundleInto,
4633 globalName = _ref.globalName,
4634 importDefaultExtension = _ref.importDefaultExtension,
4635 importMapRelativePath = _ref.importMapRelativePath,
4636 importMapForBundle = _ref.importMapForBundle,
4637 specifierMap = _ref.specifierMap,
4638 specifierDynamicMap = _ref.specifierDynamicMap,
4639 entryPointMap = _ref.entryPointMap,
4640 babelPluginMap = _ref.babelPluginMap,
4641 convertMap = _ref.convertMap,
4642 logLevel = _ref.logLevel,
4643 minify = _ref.minify,
4644 throwUnhandled = _ref.throwUnhandled,
4645 writeOnFileSystem = _ref.writeOnFileSystem,
4646 platformScoreMap = _ref.platformScoreMap,
4647 platformAlwaysInsidePlatformScoreMap = _ref.platformAlwaysInsidePlatformScoreMap;
4648 return generateBundle({
4649 format: "global",
4650 formatOutputOptions: globalName ? {
4651 name: globalName
4652 } : {},
4653 projectPath: projectPath,
4654 bundleIntoRelativePath: bundleIntoRelativePath,
4655 cleanBundleInto: cleanBundleInto,
4656 importDefaultExtension: importDefaultExtension,
4657 importMapRelativePath: importMapRelativePath,
4658 importMapForBundle: importMapForBundle,
4659 specifierMap: specifierMap,
4660 specifierDynamicMap: specifierDynamicMap,
4661 entryPointMap: entryPointMap,
4662 babelPluginMap: babelPluginMap,
4663 convertMap: convertMap,
4664 logLevel: logLevel,
4665 minify: minify,
4666 throwUnhandled: throwUnhandled,
4667 writeOnFileSystem: writeOnFileSystem,
4668 compileGroupCount: 1,
4669 platformScoreMap: platformScoreMap,
4670 platformAlwaysInsidePlatformScoreMap: platformAlwaysInsidePlatformScoreMap
4671 });
4672});
4673
4674var DEFAULT_BUNDLE_INTO_RELATIVE_PATH$1 = "/dist/commonjs";
4675
4676function _async$i(f) {
4677 return function () {
4678 for (var args = [], i = 0; i < arguments.length; i++) {
4679 args[i] = arguments[i];
4680 }
4681
4682 try {
4683 return Promise.resolve(f.apply(this, args));
4684 } catch (e) {
4685 return Promise.reject(e);
4686 }
4687 };
4688}
4689
4690var generateCommonJsBundle = _async$i(function (_ref) {
4691 var projectPath = _ref.projectPath,
4692 _ref$bundleIntoRelati = _ref.bundleIntoRelativePath,
4693 bundleIntoRelativePath = _ref$bundleIntoRelati === void 0 ? DEFAULT_BUNDLE_INTO_RELATIVE_PATH$1 : _ref$bundleIntoRelati,
4694 cleanBundleInto = _ref.cleanBundleInto,
4695 balancerTemplateRelativePath = _ref.balancerTemplateRelativePath,
4696 importDefaultExtension = _ref.importDefaultExtension,
4697 importMapRelativePath = _ref.importMapRelativePath,
4698 importMapForBundle = _ref.importMapForBundle,
4699 specifierMap = _ref.specifierMap,
4700 dynamicSpecifierMap = _ref.dynamicSpecifierMap,
4701 entryPointMap = _ref.entryPointMap,
4702 babelPluginMap = _ref.babelPluginMap,
4703 convertMap = _ref.convertMap,
4704 logLevel = _ref.logLevel,
4705 minify = _ref.minify,
4706 throwUnhandled = _ref.throwUnhandled,
4707 writeOnFileSystem = _ref.writeOnFileSystem,
4708 compileGroupCount = _ref.compileGroupCount,
4709 platformScoreMap = _ref.platformScoreMap,
4710 platformAlwaysInsidePlatformScoreMap = _ref.platformAlwaysInsidePlatformScoreMap;
4711 return generateBundle({
4712 format: "commonjs",
4713 balancerTemplateRelativePath: balancerTemplateRelativePath,
4714 defaultBalancerTemplateRelativePath: "/src/bundle-commonjs/commonjs-balancer-template.js",
4715 balancerDataClientPathname: "/.jsenv/commonjs-balancer-data.js",
4716 projectPath: projectPath,
4717 bundleIntoRelativePath: bundleIntoRelativePath,
4718 cleanBundleInto: cleanBundleInto,
4719 importDefaultExtension: importDefaultExtension,
4720 importMapRelativePath: importMapRelativePath,
4721 importMapForBundle: importMapForBundle,
4722 specifierMap: specifierMap,
4723 dynamicSpecifierMap: dynamicSpecifierMap,
4724 entryPointMap: entryPointMap,
4725 babelPluginMap: babelPluginMap,
4726 convertMap: convertMap,
4727 logLevel: logLevel,
4728 minify: minify,
4729 throwUnhandled: throwUnhandled,
4730 writeOnFileSystem: writeOnFileSystem,
4731 compileGroupCount: compileGroupCount,
4732 platformScoreMap: platformScoreMap,
4733 platformAlwaysInsidePlatformScoreMap: platformAlwaysInsidePlatformScoreMap
4734 });
4735});
4736
4737var DEFAULT_BUNDLE_INTO_RELATIVE_PATH$2 = "/dist/systemjs";
4738
4739function _async$j(f) {
4740 return function () {
4741 for (var args = [], i = 0; i < arguments.length; i++) {
4742 args[i] = arguments[i];
4743 }
4744
4745 try {
4746 return Promise.resolve(f.apply(this, args));
4747 } catch (e) {
4748 return Promise.reject(e);
4749 }
4750 };
4751}
4752
4753var generateSystemJsBundle = _async$j(function (_ref) {
4754 var projectPath = _ref.projectPath,
4755 _ref$bundleIntoRelati = _ref.bundleIntoRelativePath,
4756 bundleIntoRelativePath = _ref$bundleIntoRelati === void 0 ? DEFAULT_BUNDLE_INTO_RELATIVE_PATH$2 : _ref$bundleIntoRelati,
4757 cleanBundleInto = _ref.cleanBundleInto,
4758 balancerTemplateRelativePath = _ref.balancerTemplateRelativePath,
4759 importDefaultExtension = _ref.importDefaultExtension,
4760 importMapRelativePath = _ref.importMapRelativePath,
4761 importMapForBundle = _ref.importMapForBundle,
4762 specifierMap = _ref.specifierMap,
4763 dynamicSpecifierMap = _ref.dynamicSpecifierMap,
4764 entryPointMap = _ref.entryPointMap,
4765 babelPluginMap = _ref.babelPluginMap,
4766 convertMap = _ref.convertMap,
4767 logLevel = _ref.logLevel,
4768 minify = _ref.minify,
4769 throwUnhandled = _ref.throwUnhandled,
4770 writeOnFileSystem = _ref.writeOnFileSystem,
4771 compileGroupCount = _ref.compileGroupCount,
4772 platformScoreMap = _ref.platformScoreMap,
4773 platformAlwaysInsidePlatformScoreMap = _ref.platformAlwaysInsidePlatformScoreMap;
4774 return generateBundle({
4775 format: "systemjs",
4776 balancerTemplateRelativePath: balancerTemplateRelativePath,
4777 defaultBalancerTemplateRelativePath: "/src/bundle-systemjs/systemjs-balancer-template.js",
4778 balancerDataClientPathname: "/.jsenv/systemjs-balancer-data.js",
4779 projectPath: projectPath,
4780 bundleIntoRelativePath: bundleIntoRelativePath,
4781 cleanBundleInto: cleanBundleInto,
4782 importDefaultExtension: importDefaultExtension,
4783 importMapRelativePath: importMapRelativePath,
4784 importMapForBundle: importMapForBundle,
4785 specifierMap: specifierMap,
4786 dynamicSpecifierMap: dynamicSpecifierMap,
4787 entryPointMap: entryPointMap,
4788 babelPluginMap: babelPluginMap,
4789 convertMap: convertMap,
4790 logLevel: logLevel,
4791 minify: minify,
4792 throwUnhandled: throwUnhandled,
4793 writeOnFileSystem: writeOnFileSystem,
4794 compileGroupCount: compileGroupCount,
4795 platformScoreMap: platformScoreMap,
4796 platformAlwaysInsidePlatformScoreMap: platformAlwaysInsidePlatformScoreMap
4797 });
4798});
4799
4800var bundleToCompilationResult = function bundleToCompilationResult(_ref, _ref2) {
4801 var rollupBundle = _ref.rollupBundle,
4802 relativePathAbstractArray = _ref.relativePathAbstractArray;
4803 var projectPathname = _ref2.projectPathname,
4804 entryRelativePath = _ref2.entryRelativePath,
4805 sourcemapAssetPath = _ref2.sourcemapAssetPath,
4806 _ref2$sourcemapPath = _ref2.sourcemapPath,
4807 sourcemapPath = _ref2$sourcemapPath === void 0 ? sourcemapAssetPath : _ref2$sourcemapPath;
4808 var sources = [];
4809 var sourcesContent = [];
4810 var assets = [];
4811 var assetsContent = [];
4812 var output = rollupBundle.output;
4813 var main = output[0];
4814 var mainRollupSourcemap = main.map;
4815 var mainDependencyMap = rollupSourcemapToDependencyMap({
4816 rollupSourcemap: mainRollupSourcemap,
4817 projectPathname: projectPathname,
4818 entryRelativePath: entryRelativePath,
4819 relativePathAbstractArray: relativePathAbstractArray
4820 });
4821
4822 var addDependencyMap = function addDependencyMap(dependencyMap) {
4823 Object.keys(dependencyMap).forEach(function (relativePath) {
4824 if (relativePathAbstractArray.includes(relativePath)) return;
4825 if (sources.includes(relativePath)) return;
4826 sources.push(relativePath);
4827 sourcesContent.push(dependencyMap[relativePath]);
4828 });
4829 }; // main file
4830
4831
4832 var mainSourceContent = writeOrUpdateSourceMappingURL(main.code, sourcemapPath); // main sourcemap
4833
4834 assets.push(sourcemapAssetPath.slice(2));
4835
4836 var mainSourcemap = _objectSpread2({}, mainRollupSourcemap, {}, dependencyMapToSourcemapSubset(mainDependencyMap));
4837
4838 assetsContent.push(JSON.stringify(mainSourcemap, null, " ")); // main dependencies
4839
4840 addDependencyMap(mainDependencyMap);
4841 output.slice(1).forEach(function (chunk) {
4842 var chunkRollupSourcemap = chunk.map;
4843 var chunkDependencyMap = rollupSourcemapToDependencyMap({
4844 rollupSourcemap: chunkRollupSourcemap,
4845 projectPathname: projectPathname,
4846 entryRelativePath: entryRelativePath,
4847 relativePathAbstractArray: relativePathAbstractArray
4848 }); // chunk file
4849
4850 assets.push(chunk.fileName);
4851 var chunkSourceContent = writeOrUpdateSourceMappingURL(chunk.code, "./".concat(chunk.fileName, ".map"));
4852 assetsContent.push(chunkSourceContent); // chunk sourcemap
4853
4854 assets.push("".concat(chunk.fileName, ".map"));
4855
4856 var chunkSourcemap = _objectSpread2({}, chunkRollupSourcemap, {}, dependencyMapToSourcemapSubset(chunkDependencyMap));
4857
4858 assetsContent.push(JSON.stringify(chunkSourcemap, null, " ")); // chunk dependencies
4859
4860 addDependencyMap(chunkDependencyMap);
4861 });
4862 return {
4863 contentType: "application/javascript",
4864 compiledSource: mainSourceContent,
4865 sources: sources,
4866 sourcesContent: sourcesContent,
4867 assets: assets,
4868 assetsContent: assetsContent
4869 };
4870};
4871
4872var dependencyMapToSourcemapSubset = function dependencyMapToSourcemapSubset(dependencyMap) {
4873 var sources = Object.keys(dependencyMap);
4874 var sourcesContent = sources.map(function (source) {
4875 // for sourcemap the source content of a json file is the js
4876 // transformation of that json
4877 if (source.endsWith(".json")) return "export default ".concat(dependencyMap[source]);
4878 return dependencyMap[source];
4879 });
4880 return {
4881 sources: sources,
4882 sourcesContent: sourcesContent
4883 };
4884};
4885
4886var rollupSourcemapToDependencyMap = function rollupSourcemapToDependencyMap(_ref3) {
4887 var rollupSourcemap = _ref3.rollupSourcemap,
4888 projectPathname = _ref3.projectPathname,
4889 entryRelativePath = _ref3.entryRelativePath,
4890 relativePathAbstractArray = _ref3.relativePathAbstractArray;
4891 var dependencyMap = {};
4892 rollupSourcemap.sources.forEach(function (sourceRelativeToEntry, index) {
4893 var sourcePath = path.resolve(path.dirname(pathnameToOperatingSystemPath("".concat(projectPathname).concat(entryRelativePath))), sourceRelativeToEntry);
4894 var sourcePathname = operatingSystemPathToPathname(sourcePath);
4895
4896 if (!pathnameIsInside(sourcePathname, projectPathname)) {
4897 throw createSourceOutsideProjectError({
4898 sourcePath: sourcePath,
4899 projectPathname: projectPathname,
4900 source: sourceRelativeToEntry,
4901 file: entryRelativePath
4902 });
4903 }
4904
4905 var sourceRelativePath = pathnameToRelativePath(sourcePathname, projectPathname);
4906 var isAbstract = relativePathAbstractArray.includes(sourceRelativePath);
4907 var dependencyContent;
4908 var sourcesContent = rollupSourcemap.sourcesContent || [];
4909
4910 if (index in sourcesContent) {
4911 // abstract ressource cannot be found on filesystem
4912 // so trust what we found in sourcesContent
4913 if (isAbstract) {
4914 dependencyContent = sourcesContent[index];
4915 } // .json file source content is not the one inside the file
4916 // because jsenv-rollup-plugin transforms it to
4917 // export default, so we must set back the
4918 // right file content
4919 else if (sourceRelativePath.endsWith(".json")) {
4920 dependencyContent = readSourceContent({
4921 projectPathname: projectPathname,
4922 sourceRelativePath: sourceRelativePath,
4923 entryRelativePath: entryRelativePath
4924 });
4925 } else {
4926 dependencyContent = sourcesContent[index];
4927 }
4928 } else {
4929 if (isAbstract) {
4930 throw createAbstractSourceMissingError({
4931 sourceRelativePath: sourceRelativePath,
4932 entryRelativePath: entryRelativePath
4933 });
4934 }
4935
4936 dependencyContent = readSourceContent({
4937 projectPathname: projectPathname,
4938 sourceRelativePath: sourceRelativePath,
4939 entryRelativePath: entryRelativePath
4940 });
4941 }
4942
4943 dependencyMap[sourceRelativePath] = dependencyContent;
4944 });
4945 return dependencyMap;
4946};
4947
4948var readSourceContent = function readSourceContent(_ref4) {
4949 var projectPathname = _ref4.projectPathname,
4950 sourceRelativePath = _ref4.sourceRelativePath,
4951 entryRelativePath = _ref4.entryRelativePath;
4952 var sourcePath = pathnameToOperatingSystemPath("".concat(projectPathname).concat(sourceRelativePath)); // this could be async but it's ok for now
4953 // making it async could be harder than it seems
4954 // because sourcesContent must be in sync with sources
4955
4956 try {
4957 var buffer = fs.readFileSync(sourcePath);
4958 return String(buffer);
4959 } catch (e) {
4960 if (e && e.code === "ENOENT") {
4961 throw createSourceNotFoundError({
4962 sourcePath: sourcePath,
4963 projectPathname: projectPathname,
4964 source: sourceRelativePath,
4965 file: entryRelativePath
4966 });
4967 }
4968
4969 throw e;
4970 }
4971};
4972
4973var createAbstractSourceMissingError = function createAbstractSourceMissingError(_ref5) {
4974 var source = _ref5.source,
4975 file = _ref5.file;
4976 return new Error("an abstract file source content is missing.\nsource: ".concat(source, "\nfile: ").concat(file));
4977};
4978
4979var createSourceNotFoundError = function createSourceNotFoundError(_ref6) {
4980 var sourcePath = _ref6.sourcePath,
4981 projectPathname = _ref6.projectPathname,
4982 source = _ref6.source,
4983 file = _ref6.file;
4984 return new Error("a file source cannot be found.\nsource path: ".concat(sourcePath, "\nproject path: ").concat(pathnameToOperatingSystemPath(projectPathname), "\nsource: ").concat(source, "\nfile: ").concat(file));
4985};
4986
4987var createSourceOutsideProjectError = function createSourceOutsideProjectError(_ref7) {
4988 var sourcePath = _ref7.sourcePath,
4989 projectPathname = _ref7.projectPathname,
4990 source = _ref7.source,
4991 file = _ref7.file;
4992 return new Error("a file source is not inside project.\nsource path: ".concat(sourcePath, "\nproject path: ").concat(pathnameToOperatingSystemPath(projectPathname), "\nsource: ").concat(source, "\nfile: ").concat(file));
4993};
4994
4995exports.bundleToCompilationResult = bundleToCompilationResult;
4996exports.generateBundle = generateBundle;
4997exports.generateCommonJsBundle = generateCommonJsBundle;
4998exports.generateGlobalBundle = generateGlobalBundle;
4999exports.generateSystemJsBundle = generateSystemJsBundle;
5000//# sourceMappingURL=main.js.map