@vercel/go 2.3.11 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2890 -166
  2. package/package.json +7 -4
package/dist/index.js CHANGED
@@ -113,6 +113,124 @@ function retry(fn, opts) {
113
113
  module.exports = retry;
114
114
 
115
115
 
116
+ /***/ }),
117
+
118
+ /***/ 7938:
119
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
120
+
121
+ var Buffer = __webpack_require__(4293).Buffer;
122
+
123
+ var CRC_TABLE = [
124
+ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
125
+ 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
126
+ 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
127
+ 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
128
+ 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
129
+ 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
130
+ 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
131
+ 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
132
+ 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
133
+ 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
134
+ 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
135
+ 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
136
+ 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
137
+ 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
138
+ 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
139
+ 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
140
+ 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
141
+ 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
142
+ 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
143
+ 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
144
+ 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
145
+ 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
146
+ 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
147
+ 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
148
+ 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
149
+ 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
150
+ 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
151
+ 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
152
+ 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
153
+ 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
154
+ 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
155
+ 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
156
+ 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
157
+ 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
158
+ 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
159
+ 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
160
+ 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
161
+ 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
162
+ 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
163
+ 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
164
+ 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
165
+ 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
166
+ 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
167
+ 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
168
+ 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
169
+ 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
170
+ 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
171
+ 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
172
+ 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
173
+ 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
174
+ 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
175
+ 0x2d02ef8d
176
+ ];
177
+
178
+ if (typeof Int32Array !== 'undefined') {
179
+ CRC_TABLE = new Int32Array(CRC_TABLE);
180
+ }
181
+
182
+ function ensureBuffer(input) {
183
+ if (Buffer.isBuffer(input)) {
184
+ return input;
185
+ }
186
+
187
+ var hasNewBufferAPI =
188
+ typeof Buffer.alloc === "function" &&
189
+ typeof Buffer.from === "function";
190
+
191
+ if (typeof input === "number") {
192
+ return hasNewBufferAPI ? Buffer.alloc(input) : new Buffer(input);
193
+ }
194
+ else if (typeof input === "string") {
195
+ return hasNewBufferAPI ? Buffer.from(input) : new Buffer(input);
196
+ }
197
+ else {
198
+ throw new Error("input must be buffer, number, or string, received " +
199
+ typeof input);
200
+ }
201
+ }
202
+
203
+ function bufferizeInt(num) {
204
+ var tmp = ensureBuffer(4);
205
+ tmp.writeInt32BE(num, 0);
206
+ return tmp;
207
+ }
208
+
209
+ function _crc32(buf, previous) {
210
+ buf = ensureBuffer(buf);
211
+ if (Buffer.isBuffer(previous)) {
212
+ previous = previous.readUInt32BE(0);
213
+ }
214
+ var crc = ~~previous ^ -1;
215
+ for (var n = 0; n < buf.length; n++) {
216
+ crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8);
217
+ }
218
+ return (crc ^ -1);
219
+ }
220
+
221
+ function crc32() {
222
+ return bufferizeInt(_crc32.apply(null, arguments));
223
+ }
224
+ crc32.signed = function () {
225
+ return _crc32.apply(null, arguments);
226
+ };
227
+ crc32.unsigned = function () {
228
+ return _crc32.apply(null, arguments) >>> 0;
229
+ };
230
+
231
+ module.exports = crc32;
232
+
233
+
116
234
  /***/ }),
117
235
 
118
236
  /***/ 899:
@@ -875,6 +993,241 @@ var eos = function(stream, opts, callback) {
875
993
  module.exports = eos;
876
994
 
877
995
 
996
+ /***/ }),
997
+
998
+ /***/ 7052:
999
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
1000
+
1001
+ (function () {
1002
+
1003
+ var events = __webpack_require__(8614);
1004
+ var util = __webpack_require__(1669);
1005
+
1006
+ function intercept(type, interceptor) {
1007
+ var m;
1008
+
1009
+ if (typeof interceptor !== 'function') {
1010
+ throw new TypeError('interceptor must be a function');
1011
+ }
1012
+
1013
+ this.emit('newInterceptor', type, interceptor);
1014
+
1015
+ if (!this._interceptors[type]) {
1016
+ this._interceptors[type] = [interceptor];
1017
+ } else {
1018
+ this._interceptors[type].push(interceptor);
1019
+ }
1020
+
1021
+ // Check for listener leak
1022
+ if (!this._interceptors[type].warned) {
1023
+ if (typeof this._maxInterceptors !== 'undefined') {
1024
+ m = this._maxInterceptors;
1025
+ } else {
1026
+ m = EventEmitter.defaultMaxInterceptors;
1027
+ }
1028
+
1029
+ if (m && m > 0 && this._interceptors[type].length > m) {
1030
+ this._interceptors[type].warned = true;
1031
+ console.error('(node) warning: possible events-intercept EventEmitter memory ' +
1032
+ 'leak detected. %d interceptors added. ' +
1033
+ 'Use emitter.setMaxInterceptors(n) to increase limit.',
1034
+ this._interceptors[type].length);
1035
+ console.trace();
1036
+ }
1037
+ }
1038
+
1039
+ return this;
1040
+ }
1041
+
1042
+ function emitFactory(superCall) {
1043
+ return function (type) {
1044
+ var completed,
1045
+ interceptor,
1046
+ _this = this;
1047
+
1048
+ function next(err) {
1049
+ var trueArgs;
1050
+ if (err) {
1051
+ _this.emit('error', err);
1052
+ } else if (completed === interceptor.length) {
1053
+ return superCall.apply(_this, [type].concat(Array.prototype.slice.call(arguments).slice(1)));
1054
+ } else {
1055
+ trueArgs = Array.prototype.slice.call(arguments).slice(1).concat([next]);
1056
+ completed += 1;
1057
+ return interceptor[completed - 1].apply(_this, trueArgs);
1058
+ }
1059
+ }
1060
+
1061
+ if (!_this._interceptors) {
1062
+ _this._interceptors = {};
1063
+ }
1064
+
1065
+ interceptor = _this._interceptors[type];
1066
+
1067
+ if (!interceptor) {
1068
+
1069
+ //Just pass through
1070
+ return superCall.apply(_this, arguments);
1071
+
1072
+ } else {
1073
+
1074
+ completed = 0;
1075
+ return next.apply(_this, [null].concat(Array.prototype.slice.call(arguments).slice(1)));
1076
+
1077
+ }
1078
+ };
1079
+ }
1080
+
1081
+ function interceptors(type) {
1082
+ var ret;
1083
+
1084
+ if (!this._interceptors || !this._interceptors[type]) {
1085
+ ret = [];
1086
+ } else {
1087
+ ret = this._interceptors[type].slice();
1088
+ }
1089
+
1090
+ return ret;
1091
+ }
1092
+
1093
+ function removeInterceptor(type, interceptor) {
1094
+ var list, position, length, i;
1095
+
1096
+ if (typeof interceptor !== 'function') {
1097
+ throw new TypeError('interceptor must be a function');
1098
+ }
1099
+
1100
+ if (!this._interceptors || !this._interceptors[type]) {
1101
+ return this;
1102
+ }
1103
+
1104
+ list = this._interceptors[type];
1105
+ length = list.length;
1106
+ position = -1;
1107
+
1108
+ for (i = length - 1; i >= 0; i--) {
1109
+ if (list[i] === interceptor) {
1110
+ position = i;
1111
+ break;
1112
+ }
1113
+ }
1114
+
1115
+ if (position < 0) {
1116
+ return this;
1117
+ }
1118
+
1119
+ if (length === 1) {
1120
+ delete this._interceptors[type];
1121
+ } else {
1122
+ list.splice(position, 1);
1123
+ }
1124
+
1125
+ this.emit('removeInterceptor', type, interceptor);
1126
+
1127
+ return this;
1128
+ }
1129
+
1130
+ function listenersFactory(superCall) {
1131
+ return function (type) {
1132
+ var superListeners = superCall.call(this, type);
1133
+ var fakeFunctionIndex;
1134
+ var tempSuperListeners = superListeners.slice();
1135
+ if (type === 'newListener' || type === 'removeListener') {
1136
+ fakeFunctionIndex = superListeners.indexOf(fakeFunction);
1137
+ if (fakeFunctionIndex !== -1) {
1138
+ tempSuperListeners.splice(fakeFunctionIndex, 1);
1139
+ }
1140
+ return tempSuperListeners;
1141
+ }
1142
+ return superListeners;
1143
+ };
1144
+ }
1145
+
1146
+ function fakeFunction() {}
1147
+
1148
+ function fixListeners(emitter) {
1149
+ emitter.on('newListener', fakeFunction);
1150
+ emitter.on('removeListener', fakeFunction);
1151
+ }
1152
+
1153
+ function setMaxInterceptors(n) {
1154
+ if (typeof n !== 'number' || n < 0 || isNaN(n)) {
1155
+ throw new TypeError('n must be a positive number');
1156
+ }
1157
+ this._maxInterceptors = n;
1158
+ return this;
1159
+ }
1160
+
1161
+ function removeAllInterceptors(type) {
1162
+ var key, theseInterceptors, length, i;
1163
+
1164
+ if (!this._interceptors || Object.getOwnPropertyNames(this._interceptors).length === 0) {
1165
+ return this;
1166
+ }
1167
+
1168
+ if (arguments.length === 0) {
1169
+
1170
+ for (key in this._interceptors) {
1171
+ if (this._interceptors.hasOwnProperty(key) && key !== 'removeInterceptor') {
1172
+ this.removeAllInterceptors(key);
1173
+ }
1174
+ }
1175
+ this.removeAllInterceptors('removeInterceptor');
1176
+ this._interceptors = {};
1177
+
1178
+ } else if (this._interceptors[type]) {
1179
+ theseInterceptors = this._interceptors[type];
1180
+ length = theseInterceptors.length;
1181
+
1182
+ // LIFO order
1183
+ for (i = length - 1; i >= 0; i--) {
1184
+ this.removeInterceptor(type, theseInterceptors[i]);
1185
+ }
1186
+
1187
+ delete this._interceptors[type];
1188
+ }
1189
+
1190
+ return this;
1191
+ }
1192
+
1193
+ function EventEmitter() {
1194
+ events.EventEmitter.call(this);
1195
+ fixListeners(this);
1196
+ }
1197
+
1198
+ util.inherits(EventEmitter, events.EventEmitter);
1199
+
1200
+ EventEmitter.prototype.intercept = intercept;
1201
+ EventEmitter.prototype.emit = emitFactory(EventEmitter.super_.prototype.emit);
1202
+ EventEmitter.prototype.interceptors = interceptors;
1203
+ EventEmitter.prototype.removeInterceptor = removeInterceptor;
1204
+ EventEmitter.prototype.removeAllInterceptors = removeAllInterceptors;
1205
+ EventEmitter.prototype.setMaxInterceptors = setMaxInterceptors;
1206
+ EventEmitter.prototype.listeners = listenersFactory(EventEmitter.super_.prototype.listeners);
1207
+ EventEmitter.defaultMaxInterceptors = 10;
1208
+
1209
+ function monkeyPatch(emitter) {
1210
+ var oldEmit = emitter.emit;
1211
+ var oldListeners = emitter.listeners;
1212
+
1213
+ emitter.emit = emitFactory(oldEmit);
1214
+ emitter.intercept = intercept;
1215
+ emitter.interceptors = interceptors;
1216
+ emitter.removeInterceptor = removeInterceptor;
1217
+ emitter.removeAllInterceptors = removeAllInterceptors;
1218
+ emitter.setMaxInterceptors = setMaxInterceptors;
1219
+ emitter.listeners = listenersFactory(oldListeners);
1220
+ fixListeners(emitter);
1221
+ }
1222
+
1223
+ module.exports = {
1224
+ EventEmitter: EventEmitter,
1225
+ patch: monkeyPatch
1226
+ };
1227
+
1228
+ })();
1229
+
1230
+
878
1231
  /***/ }),
879
1232
 
880
1233
  /***/ 389:
@@ -1340,6 +1693,309 @@ module.exports = opts => {
1340
1693
  };
1341
1694
 
1342
1695
 
1696
+ /***/ }),
1697
+
1698
+ /***/ 402:
1699
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1700
+
1701
+ var fs = __webpack_require__(5747);
1702
+ var util = __webpack_require__(1669);
1703
+ var stream = __webpack_require__(2413);
1704
+ var Readable = stream.Readable;
1705
+ var Writable = stream.Writable;
1706
+ var PassThrough = stream.PassThrough;
1707
+ var Pend = __webpack_require__(1059);
1708
+ var EventEmitter = __webpack_require__(8614).EventEmitter;
1709
+
1710
+ exports.createFromBuffer = createFromBuffer;
1711
+ exports.createFromFd = createFromFd;
1712
+ exports.BufferSlicer = BufferSlicer;
1713
+ exports.FdSlicer = FdSlicer;
1714
+
1715
+ util.inherits(FdSlicer, EventEmitter);
1716
+ function FdSlicer(fd, options) {
1717
+ options = options || {};
1718
+ EventEmitter.call(this);
1719
+
1720
+ this.fd = fd;
1721
+ this.pend = new Pend();
1722
+ this.pend.max = 1;
1723
+ this.refCount = 0;
1724
+ this.autoClose = !!options.autoClose;
1725
+ }
1726
+
1727
+ FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
1728
+ var self = this;
1729
+ self.pend.go(function(cb) {
1730
+ fs.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
1731
+ cb();
1732
+ callback(err, bytesRead, buffer);
1733
+ });
1734
+ });
1735
+ };
1736
+
1737
+ FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
1738
+ var self = this;
1739
+ self.pend.go(function(cb) {
1740
+ fs.write(self.fd, buffer, offset, length, position, function(err, written, buffer) {
1741
+ cb();
1742
+ callback(err, written, buffer);
1743
+ });
1744
+ });
1745
+ };
1746
+
1747
+ FdSlicer.prototype.createReadStream = function(options) {
1748
+ return new ReadStream(this, options);
1749
+ };
1750
+
1751
+ FdSlicer.prototype.createWriteStream = function(options) {
1752
+ return new WriteStream(this, options);
1753
+ };
1754
+
1755
+ FdSlicer.prototype.ref = function() {
1756
+ this.refCount += 1;
1757
+ };
1758
+
1759
+ FdSlicer.prototype.unref = function() {
1760
+ var self = this;
1761
+ self.refCount -= 1;
1762
+
1763
+ if (self.refCount > 0) return;
1764
+ if (self.refCount < 0) throw new Error("invalid unref");
1765
+
1766
+ if (self.autoClose) {
1767
+ fs.close(self.fd, onCloseDone);
1768
+ }
1769
+
1770
+ function onCloseDone(err) {
1771
+ if (err) {
1772
+ self.emit('error', err);
1773
+ } else {
1774
+ self.emit('close');
1775
+ }
1776
+ }
1777
+ };
1778
+
1779
+ util.inherits(ReadStream, Readable);
1780
+ function ReadStream(context, options) {
1781
+ options = options || {};
1782
+ Readable.call(this, options);
1783
+
1784
+ this.context = context;
1785
+ this.context.ref();
1786
+
1787
+ this.start = options.start || 0;
1788
+ this.endOffset = options.end;
1789
+ this.pos = this.start;
1790
+ this.destroyed = false;
1791
+ }
1792
+
1793
+ ReadStream.prototype._read = function(n) {
1794
+ var self = this;
1795
+ if (self.destroyed) return;
1796
+
1797
+ var toRead = Math.min(self._readableState.highWaterMark, n);
1798
+ if (self.endOffset != null) {
1799
+ toRead = Math.min(toRead, self.endOffset - self.pos);
1800
+ }
1801
+ if (toRead <= 0) {
1802
+ self.destroyed = true;
1803
+ self.push(null);
1804
+ self.context.unref();
1805
+ return;
1806
+ }
1807
+ self.context.pend.go(function(cb) {
1808
+ if (self.destroyed) return cb();
1809
+ var buffer = new Buffer(toRead);
1810
+ fs.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
1811
+ if (err) {
1812
+ self.destroy(err);
1813
+ } else if (bytesRead === 0) {
1814
+ self.destroyed = true;
1815
+ self.push(null);
1816
+ self.context.unref();
1817
+ } else {
1818
+ self.pos += bytesRead;
1819
+ self.push(buffer.slice(0, bytesRead));
1820
+ }
1821
+ cb();
1822
+ });
1823
+ });
1824
+ };
1825
+
1826
+ ReadStream.prototype.destroy = function(err) {
1827
+ if (this.destroyed) return;
1828
+ err = err || new Error("stream destroyed");
1829
+ this.destroyed = true;
1830
+ this.emit('error', err);
1831
+ this.context.unref();
1832
+ };
1833
+
1834
+ util.inherits(WriteStream, Writable);
1835
+ function WriteStream(context, options) {
1836
+ options = options || {};
1837
+ Writable.call(this, options);
1838
+
1839
+ this.context = context;
1840
+ this.context.ref();
1841
+
1842
+ this.start = options.start || 0;
1843
+ this.endOffset = (options.end == null) ? Infinity : +options.end;
1844
+ this.bytesWritten = 0;
1845
+ this.pos = this.start;
1846
+ this.destroyed = false;
1847
+
1848
+ this.on('finish', this.destroy.bind(this));
1849
+ }
1850
+
1851
+ WriteStream.prototype._write = function(buffer, encoding, callback) {
1852
+ var self = this;
1853
+ if (self.destroyed) return;
1854
+
1855
+ if (self.pos + buffer.length > self.endOffset) {
1856
+ var err = new Error("maximum file length exceeded");
1857
+ err.code = 'ETOOBIG';
1858
+ self.destroy();
1859
+ callback(err);
1860
+ return;
1861
+ }
1862
+ self.context.pend.go(function(cb) {
1863
+ if (self.destroyed) return cb();
1864
+ fs.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) {
1865
+ if (err) {
1866
+ self.destroy();
1867
+ cb();
1868
+ callback(err);
1869
+ } else {
1870
+ self.bytesWritten += bytes;
1871
+ self.pos += bytes;
1872
+ self.emit('progress');
1873
+ cb();
1874
+ callback();
1875
+ }
1876
+ });
1877
+ });
1878
+ };
1879
+
1880
+ WriteStream.prototype.destroy = function() {
1881
+ if (this.destroyed) return;
1882
+ this.destroyed = true;
1883
+ this.context.unref();
1884
+ };
1885
+
1886
+ util.inherits(BufferSlicer, EventEmitter);
1887
+ function BufferSlicer(buffer, options) {
1888
+ EventEmitter.call(this);
1889
+
1890
+ options = options || {};
1891
+ this.refCount = 0;
1892
+ this.buffer = buffer;
1893
+ this.maxChunkSize = options.maxChunkSize || Number.MAX_SAFE_INTEGER;
1894
+ }
1895
+
1896
+ BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
1897
+ var end = position + length;
1898
+ var delta = end - this.buffer.length;
1899
+ var written = (delta > 0) ? delta : length;
1900
+ this.buffer.copy(buffer, offset, position, end);
1901
+ setImmediate(function() {
1902
+ callback(null, written);
1903
+ });
1904
+ };
1905
+
1906
+ BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) {
1907
+ buffer.copy(this.buffer, position, offset, offset + length);
1908
+ setImmediate(function() {
1909
+ callback(null, length, buffer);
1910
+ });
1911
+ };
1912
+
1913
+ BufferSlicer.prototype.createReadStream = function(options) {
1914
+ options = options || {};
1915
+ var readStream = new PassThrough(options);
1916
+ readStream.destroyed = false;
1917
+ readStream.start = options.start || 0;
1918
+ readStream.endOffset = options.end;
1919
+ // by the time this function returns, we'll be done.
1920
+ readStream.pos = readStream.endOffset || this.buffer.length;
1921
+
1922
+ // respect the maxChunkSize option to slice up the chunk into smaller pieces.
1923
+ var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
1924
+ var offset = 0;
1925
+ while (true) {
1926
+ var nextOffset = offset + this.maxChunkSize;
1927
+ if (nextOffset >= entireSlice.length) {
1928
+ // last chunk
1929
+ if (offset < entireSlice.length) {
1930
+ readStream.write(entireSlice.slice(offset, entireSlice.length));
1931
+ }
1932
+ break;
1933
+ }
1934
+ readStream.write(entireSlice.slice(offset, nextOffset));
1935
+ offset = nextOffset;
1936
+ }
1937
+
1938
+ readStream.end();
1939
+ readStream.destroy = function() {
1940
+ readStream.destroyed = true;
1941
+ };
1942
+ return readStream;
1943
+ };
1944
+
1945
+ BufferSlicer.prototype.createWriteStream = function(options) {
1946
+ var bufferSlicer = this;
1947
+ options = options || {};
1948
+ var writeStream = new Writable(options);
1949
+ writeStream.start = options.start || 0;
1950
+ writeStream.endOffset = (options.end == null) ? this.buffer.length : +options.end;
1951
+ writeStream.bytesWritten = 0;
1952
+ writeStream.pos = writeStream.start;
1953
+ writeStream.destroyed = false;
1954
+ writeStream._write = function(buffer, encoding, callback) {
1955
+ if (writeStream.destroyed) return;
1956
+
1957
+ var end = writeStream.pos + buffer.length;
1958
+ if (end > writeStream.endOffset) {
1959
+ var err = new Error("maximum file length exceeded");
1960
+ err.code = 'ETOOBIG';
1961
+ writeStream.destroyed = true;
1962
+ callback(err);
1963
+ return;
1964
+ }
1965
+ buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length);
1966
+
1967
+ writeStream.bytesWritten += buffer.length;
1968
+ writeStream.pos = end;
1969
+ writeStream.emit('progress');
1970
+ callback();
1971
+ };
1972
+ writeStream.destroy = function() {
1973
+ writeStream.destroyed = true;
1974
+ };
1975
+ return writeStream;
1976
+ };
1977
+
1978
+ BufferSlicer.prototype.ref = function() {
1979
+ this.refCount += 1;
1980
+ };
1981
+
1982
+ BufferSlicer.prototype.unref = function() {
1983
+ this.refCount -= 1;
1984
+
1985
+ if (this.refCount < 0) {
1986
+ throw new Error("invalid unref");
1987
+ }
1988
+ };
1989
+
1990
+ function createFromBuffer(buffer, options) {
1991
+ return new BufferSlicer(buffer, options);
1992
+ }
1993
+
1994
+ function createFromFd(fd, options) {
1995
+ return new FdSlicer(fd, options);
1996
+ }
1997
+
1998
+
1343
1999
  /***/ }),
1344
2000
 
1345
2001
  /***/ 3838:
@@ -11208,51 +11864,189 @@ function onceStrict (fn) {
11208
11864
 
11209
11865
  /***/ }),
11210
11866
 
11211
- /***/ 6472:
11212
- /***/ ((module) => {
11867
+ /***/ 9801:
11868
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
11213
11869
 
11214
11870
  "use strict";
11871
+ /* eslint-env es6, node */
11872
+ // # spell-checker:ignore HomeDrive HomePath LocalAppData UserProfile WinDir
11215
11873
 
11216
- module.exports = (promise, onFinally) => {
11217
- onFinally = onFinally || (() => {});
11218
-
11219
- return promise.then(
11220
- val => new Promise(resolve => {
11221
- resolve(onFinally());
11222
- }).then(() => val),
11223
- err => new Promise(resolve => {
11224
- resolve(onFinally());
11225
- }).then(() => {
11226
- throw err;
11227
- })
11228
- );
11229
- };
11230
11874
 
11875
+ const os = __webpack_require__(2087);
11876
+ const paths = __webpack_require__(5622);
11231
11877
 
11232
- /***/ }),
11878
+ const isWinOS = /^win/i.test(process.platform);
11233
11879
 
11234
- /***/ 2658:
11235
- /***/ ((module) => {
11880
+ function normalize_path(path) {
11881
+ return paths.normalize(paths.join(path, '.'));
11882
+ }
11236
11883
 
11237
- "use strict";
11884
+ const base = () => {
11885
+ const { env } = process;
11238
11886
 
11239
- module.exports = opts => {
11240
- opts = opts || {};
11887
+ const object = {};
11241
11888
 
11242
- const env = opts.env || process.env;
11243
- const platform = opts.platform || process.platform;
11889
+ object.home = () => normalize_path(os.homedir ? os.homedir() : env.HOME);
11244
11890
 
11245
- if (platform !== 'win32') {
11246
- return 'PATH';
11247
- }
11891
+ object.temp = () => normalize_path(os.tmpdir ? os.tmpdir() : env.TMPDIR || env.TEMP || env.TMP);
11248
11892
 
11249
- return Object.keys(env).find(x => x.toUpperCase() === 'PATH') || 'Path';
11893
+ return object;
11250
11894
  };
11251
11895
 
11896
+ const windows = () => {
11897
+ const { env } = process;
11252
11898
 
11253
- /***/ }),
11899
+ const object = {};
11254
11900
 
11255
- /***/ 8140:
11901
+ object.home = () =>
11902
+ normalize_path(
11903
+ os.homedir
11904
+ ? os.homedir()
11905
+ : env.USERPROFILE || paths.join(env.HOMEDRIVE, env.HOMEPATH) || env.HOME
11906
+ );
11907
+
11908
+ object.temp = () =>
11909
+ normalize_path(
11910
+ os.tmpdir
11911
+ ? os.tmpdir()
11912
+ : env.TEMP ||
11913
+ env.TMP ||
11914
+ paths.join(env.LOCALAPPDATA || env.SystemRoot || env.windir, 'Temp')
11915
+ );
11916
+
11917
+ return object;
11918
+ };
11919
+
11920
+ class _OSPaths {
11921
+ constructor() {
11922
+ const OSPaths = function () {
11923
+ return new _OSPaths();
11924
+ };
11925
+
11926
+ this._fn = OSPaths;
11927
+
11928
+ // Connect to platform-specific API functions by extension
11929
+ const extension = isWinOS ? windows() : base();
11930
+ Object.keys(extension).forEach((key) => {
11931
+ this._fn[key] = extension[key];
11932
+ });
11933
+
11934
+ return this._fn;
11935
+ }
11936
+ }
11937
+
11938
+ module.exports = new _OSPaths();
11939
+
11940
+
11941
+ /***/ }),
11942
+
11943
+ /***/ 6472:
11944
+ /***/ ((module) => {
11945
+
11946
+ "use strict";
11947
+
11948
+ module.exports = (promise, onFinally) => {
11949
+ onFinally = onFinally || (() => {});
11950
+
11951
+ return promise.then(
11952
+ val => new Promise(resolve => {
11953
+ resolve(onFinally());
11954
+ }).then(() => val),
11955
+ err => new Promise(resolve => {
11956
+ resolve(onFinally());
11957
+ }).then(() => {
11958
+ throw err;
11959
+ })
11960
+ );
11961
+ };
11962
+
11963
+
11964
+ /***/ }),
11965
+
11966
+ /***/ 2658:
11967
+ /***/ ((module) => {
11968
+
11969
+ "use strict";
11970
+
11971
+ module.exports = opts => {
11972
+ opts = opts || {};
11973
+
11974
+ const env = opts.env || process.env;
11975
+ const platform = opts.platform || process.platform;
11976
+
11977
+ if (platform !== 'win32') {
11978
+ return 'PATH';
11979
+ }
11980
+
11981
+ return Object.keys(env).find(x => x.toUpperCase() === 'PATH') || 'Path';
11982
+ };
11983
+
11984
+
11985
+ /***/ }),
11986
+
11987
+ /***/ 1059:
11988
+ /***/ ((module) => {
11989
+
11990
+ module.exports = Pend;
11991
+
11992
+ function Pend() {
11993
+ this.pending = 0;
11994
+ this.max = Infinity;
11995
+ this.listeners = [];
11996
+ this.waiting = [];
11997
+ this.error = null;
11998
+ }
11999
+
12000
+ Pend.prototype.go = function(fn) {
12001
+ if (this.pending < this.max) {
12002
+ pendGo(this, fn);
12003
+ } else {
12004
+ this.waiting.push(fn);
12005
+ }
12006
+ };
12007
+
12008
+ Pend.prototype.wait = function(cb) {
12009
+ if (this.pending === 0) {
12010
+ cb(this.error);
12011
+ } else {
12012
+ this.listeners.push(cb);
12013
+ }
12014
+ };
12015
+
12016
+ Pend.prototype.hold = function() {
12017
+ return pendHold(this);
12018
+ };
12019
+
12020
+ function pendHold(self) {
12021
+ self.pending += 1;
12022
+ var called = false;
12023
+ return onCb;
12024
+ function onCb(err) {
12025
+ if (called) throw new Error("callback called twice");
12026
+ called = true;
12027
+ self.error = self.error || err;
12028
+ self.pending -= 1;
12029
+ if (self.waiting.length > 0 && self.pending < self.max) {
12030
+ pendGo(self, self.waiting.shift());
12031
+ } else if (self.pending === 0) {
12032
+ var listeners = self.listeners;
12033
+ self.listeners = [];
12034
+ listeners.forEach(cbListener);
12035
+ }
12036
+ }
12037
+ function cbListener(listener) {
12038
+ listener(self.error);
12039
+ }
12040
+ }
12041
+
12042
+ function pendGo(self, fn) {
12043
+ fn(pendHold(self));
12044
+ }
12045
+
12046
+
12047
+ /***/ }),
12048
+
12049
+ /***/ 8140:
11256
12050
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
11257
12051
 
11258
12052
  var once = __webpack_require__(1924)
@@ -19627,6 +20421,336 @@ function wrappy (fn, cb) {
19627
20421
  }
19628
20422
 
19629
20423
 
20424
+ /***/ }),
20425
+
20426
+ /***/ 4925:
20427
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
20428
+
20429
+ "use strict";
20430
+ // # spell-checker:ignore macos APPDATA LOCALAPPDATA
20431
+ /* eslint-env es6, node */
20432
+
20433
+
20434
+ const path = __webpack_require__(5622);
20435
+ const os = __webpack_require__(2087);
20436
+ const xdg = __webpack_require__(5442);
20437
+
20438
+ const isWinOS = /^win/i.test(process.platform);
20439
+
20440
+ function _normalizeOptions(options, isolated) {
20441
+ options = options || {};
20442
+ if (typeof options !== 'object') {
20443
+ options = {isolated: options};
20444
+ }
20445
+
20446
+ options.isolated = ((options.isolated === undefined) || (options.isolated === null)) ? isolated : options.isolated;
20447
+ if (typeof options.isolated !== 'boolean') {
20448
+ throw new TypeError(`Expected boolean for "isolated" argument, got ${typeof options.isolated}`);
20449
+ }
20450
+
20451
+ return options;
20452
+ }
20453
+
20454
+ const base = (name, isolated) => {
20455
+ const object = {};
20456
+
20457
+ object.cache = (options = {isolated: null}) => {
20458
+ options = _normalizeOptions(options, isolated);
20459
+ return path.join(xdg.cache(), options.isolated ? name : '');
20460
+ };
20461
+
20462
+ object.config = (options = {isolated: null}) => {
20463
+ options = _normalizeOptions(options, isolated);
20464
+ return path.join(xdg.config(), options.isolated ? name : '');
20465
+ };
20466
+
20467
+ object.data = (options = {isolated: null}) => {
20468
+ options = _normalizeOptions(options, isolated);
20469
+ return path.join(xdg.data(), options.isolated ? name : '');
20470
+ };
20471
+
20472
+ object.runtime = (options = {isolated: null}) => {
20473
+ options = _normalizeOptions(options, isolated);
20474
+ return xdg.runtime() ? path.join(xdg.runtime(), options.isolated ? name : '') : undefined;
20475
+ };
20476
+
20477
+ object.state = (options = {isolated: null}) => {
20478
+ options = _normalizeOptions(options, isolated);
20479
+ return path.join(xdg.state(), options.isolated ? name : '');
20480
+ };
20481
+
20482
+ object.configDirs = (options = {isolated: null}) => {
20483
+ options = _normalizeOptions(options, isolated);
20484
+ return (xdg.configDirs()).map(s => path.join(s, options.isolated ? name : ''));
20485
+ };
20486
+
20487
+ object.dataDirs = (options = {isolated: null}) => {
20488
+ options = _normalizeOptions(options, isolated);
20489
+ return (xdg.dataDirs()).map(s => path.join(s, options.isolated ? name : ''));
20490
+ };
20491
+
20492
+ return object;
20493
+ };
20494
+
20495
+ const windows = (name, isolated) => {
20496
+ const {env} = process;
20497
+ const homedir = os.homedir();
20498
+ const tmpdir = os.tmpdir();
20499
+
20500
+ // # ref: <https://www.thewindowsclub.com/local-localnow-roaming-folders-windows-10> @@ <http://archive.is/tDEPl>
20501
+ const appData = env.APPDATA || path.join(homedir || tmpdir, 'AppData', 'Roaming'); // APPDATA == "AppData/Roaming" contains data which may follow user between machines
20502
+ const localAppData = env.LOCALAPPDATA || path.join(homedir || tmpdir, 'AppData', 'Local'); // LOCALAPPDATA == "AppData/Local" contains local-machine-only user data
20503
+
20504
+ const object = {};
20505
+
20506
+ // Locations for data/config/cache/state are invented (Windows doesn't have a popular convention)
20507
+
20508
+ object.cache = (options = {isolated: null}) => {
20509
+ options = _normalizeOptions(options, isolated);
20510
+ return (!options.isolated || env.XDG_CACHE_HOME) ?
20511
+ path.join(xdg.cache(), options.isolated ? name : '') :
20512
+ path.join(localAppData, options.isolated ? name : '', 'Cache');
20513
+ };
20514
+
20515
+ object.config = (options = {isolated: null}) => {
20516
+ options = _normalizeOptions(options, isolated);
20517
+ const config = (!options.isolated || env.XDG_CONFIG_HOME) ?
20518
+ path.join(xdg.config(), options.isolated ? name : '') :
20519
+ path.join(appData, options.isolated ? name : '', 'Config');
20520
+ return config;
20521
+ };
20522
+
20523
+ object.data = (options = {isolated: null}) => {
20524
+ options = _normalizeOptions(options, isolated);
20525
+ const data = (!options.isolated || env.XDG_DATA_HOME) ?
20526
+ path.join(xdg.data(), options.isolated ? name : '') :
20527
+ path.join(appData, options.isolated ? name : '', 'Data');
20528
+ return data;
20529
+ };
20530
+
20531
+ object.runtime = (options = {isolated: null}) => {
20532
+ options = _normalizeOptions(options, isolated);
20533
+ return xdg.runtime() ? path.join(xdg.runtime(), options.isolated ? name : '') : undefined;
20534
+ };
20535
+
20536
+ object.state = (options = {isolated: null}) => {
20537
+ options = _normalizeOptions(options, isolated);
20538
+ return (!options.isolated || env.XDG_STATE_HOME) ?
20539
+ path.join(xdg.state(), options.isolated ? name : '') :
20540
+ path.join(localAppData, options.isolated ? name : '', 'State');
20541
+ };
20542
+
20543
+ object.configDirs = (options = {isolated: null}) => {
20544
+ options = _normalizeOptions(options, isolated);
20545
+ const dirs = [object.config(options)];
20546
+ if (env.XDG_CONFIG_DIRS) {
20547
+ dirs.push(...env.XDG_CONFIG_DIRS.split(path.delimiter).map(s => path.join(s, options.isolated ? name : '')));
20548
+ }
20549
+
20550
+ return dirs;
20551
+ };
20552
+
20553
+ object.dataDirs = (options = {isolated: null}) => {
20554
+ options = _normalizeOptions(options, isolated);
20555
+ const dirs = [object.data(options)];
20556
+ if (env.XDG_DATA_DIRS) {
20557
+ dirs.push(...env.XDG_DATA_DIRS.split(path.delimiter).map(s => path.join(s, options.isolated ? name : '')));
20558
+ }
20559
+
20560
+ return dirs;
20561
+ };
20562
+
20563
+ return object;
20564
+ };
20565
+
20566
+ class _XDGAppPaths {
20567
+ constructor(options = {name: null, suffix: null, isolated: true}) {
20568
+ const XDGAppPaths = function (options = {name: null, suffix: null, isolated: true}) {
20569
+ return new _XDGAppPaths(options);
20570
+ };
20571
+
20572
+ this._fn = XDGAppPaths;
20573
+
20574
+ options = options || {};
20575
+ if (typeof options !== 'object') {
20576
+ options = {name: options};
20577
+ }
20578
+
20579
+ let name = options.name || '';
20580
+ if (typeof name !== 'string') {
20581
+ throw new TypeError(`Expected string for "name" argument, got ${typeof name}`);
20582
+ }
20583
+
20584
+ const suffix = options.suffix || '';
20585
+ if (typeof suffix !== 'string') {
20586
+ throw new TypeError(`Expected string for "suffix" argument, got ${typeof suffix}`);
20587
+ }
20588
+
20589
+ const isolated = ((options.isolated === undefined) || (options.isolated === null)) ? true : options.isolated;
20590
+ if (typeof isolated !== 'boolean') {
20591
+ throw new TypeError(`Expected boolean for "isolated" argument, got ${typeof isolated}`);
20592
+ }
20593
+
20594
+ if (!name) {
20595
+ // Find a suitable application name (ref: <https://stackoverflow.com/a/46110961/43774>)
20596
+ name = path.parse(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0])).name;
20597
+ }
20598
+
20599
+ if (suffix) {
20600
+ name += suffix;
20601
+ }
20602
+
20603
+ this._fn.$name = () => name;
20604
+ this._fn.$isolated = () => isolated;
20605
+
20606
+ // Connect to platform-specific API functions by extension
20607
+ const extension = isWinOS ? windows(name, isolated) : base(name, isolated);
20608
+ Object.keys(extension).forEach(key => {
20609
+ this._fn[key] = extension[key];
20610
+ });
20611
+
20612
+ return this._fn;
20613
+ }
20614
+ }
20615
+
20616
+ module.exports = new _XDGAppPaths();
20617
+
20618
+
20619
+ /***/ }),
20620
+
20621
+ /***/ 5442:
20622
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
20623
+
20624
+ "use strict";
20625
+ // # spell-checker:ignore macos APPDATA LOCALAPPDATA
20626
+ /* eslint-env es6, node */
20627
+
20628
+
20629
+ const path = __webpack_require__(5622);
20630
+
20631
+ const osPaths = __webpack_require__(9801);
20632
+
20633
+ // XDG references
20634
+ // # ref: <https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html> @@ <https://archive.is/aAhtw>
20635
+ // # ref: <https://specifications.freedesktop.org/basedir-spec/latest/ar01s03.html> @@ <https://archive.is/7N0TN>
20636
+ // # ref: <https://wiki.archlinux.org/index.php/XDG_Base_Directory> @@ <https://archive.is/VdO9n>
20637
+ // # ref: <https://wiki.debian.org/XDGBaseDirectorySpecification#state> @@ <http://archive.is/pahId>
20638
+ // # ref: <https://ploum.net/207-modify-your-application-to-use-xdg-folders> @@ <https://archive.is/f43Gk>
20639
+
20640
+ const linux = () => {
20641
+ const object = {};
20642
+
20643
+ object.cache = () =>
20644
+ process.env.XDG_CACHE_HOME || path.join(osPaths.home() || osPaths.temp(), '.cache');
20645
+ object.config = () =>
20646
+ process.env.XDG_CONFIG_HOME || path.join(osPaths.home() || osPaths.temp(), '.config');
20647
+ object.data = () =>
20648
+ process.env.XDG_DATA_HOME || path.join(osPaths.home() || osPaths.temp(), '.local', 'share');
20649
+ object.runtime = () => process.env.XDG_RUNTIME_DIR || undefined;
20650
+ object.state = () =>
20651
+ process.env.XDG_STATE_HOME || path.join(osPaths.home() || osPaths.temp(), '.local', 'state');
20652
+
20653
+ return object;
20654
+ };
20655
+
20656
+ const macos = () => {
20657
+ const object = {};
20658
+
20659
+ object.cache = () =>
20660
+ process.env.XDG_CACHE_HOME ||
20661
+ path.join(path.join(osPaths.home() || osPaths.temp(), 'Library'), 'Caches');
20662
+ object.config = () =>
20663
+ process.env.XDG_CONFIG_HOME ||
20664
+ path.join(path.join(osPaths.home() || osPaths.temp(), 'Library'), 'Preferences');
20665
+ object.data = () =>
20666
+ process.env.XDG_DATA_HOME ||
20667
+ path.join(path.join(osPaths.home() || osPaths.temp(), 'Library'), 'Application Support');
20668
+ object.runtime = () => process.env.XDG_RUNTIME_DIR || undefined;
20669
+ object.state = () =>
20670
+ process.env.XDG_STATE_HOME ||
20671
+ path.join(path.join(osPaths.home() || osPaths.temp(), 'Library'), 'State');
20672
+
20673
+ return object;
20674
+ };
20675
+
20676
+ const windows = () => {
20677
+ const object = {};
20678
+ // # ref: <https://www.thewindowsclub.com/local-localnow-roaming-folders-windows-10> @@ <http://archive.is/tDEPl>
20679
+ // Locations for cache/config/data/state are invented (Windows doesn't have a popular convention)
20680
+
20681
+ object.cache = () => {
20682
+ const localAppData =
20683
+ process.env.LOCALAPPDATA || path.join(osPaths.home() || osPaths.temp(), 'AppData', 'Local'); // "AppData/Local" contains local-machine-only user data
20684
+ return process.env.XDG_CACHE_HOME || path.join(localAppData, 'xdg.cache');
20685
+ };
20686
+
20687
+ object.config = () => {
20688
+ const appData =
20689
+ process.env.APPDATA || path.join(osPaths.home() || osPaths.temp(), 'AppData', 'Roaming'); // "AppData/Roaming" contains data which may follow user between machines
20690
+ return process.env.XDG_CONFIG_HOME || path.join(appData, 'xdg.config');
20691
+ };
20692
+
20693
+ object.data = () => {
20694
+ const appData =
20695
+ process.env.APPDATA || path.join(osPaths.home() || osPaths.temp(), 'AppData', 'Roaming'); // "AppData/Roaming" contains data which may follow user between machines
20696
+ return process.env.XDG_DATA_HOME || path.join(appData, 'xdg.data');
20697
+ };
20698
+
20699
+ object.runtime = () => process.env.XDG_RUNTIME_DIR || undefined;
20700
+
20701
+ object.state = () => {
20702
+ const localAppData =
20703
+ process.env.LOCALAPPDATA || path.join(osPaths.home() || osPaths.temp(), 'AppData', 'Local'); // "AppData/Local" contains local-machine-only user data
20704
+ return process.env.XDG_STATE_HOME || path.join(localAppData, 'xdg.state');
20705
+ };
20706
+
20707
+ return object;
20708
+ };
20709
+
20710
+ const _XDGPortable = () => {
20711
+ const XDGPortable = function () {
20712
+ return _XDGPortable();
20713
+ };
20714
+
20715
+ let extension = {};
20716
+ if (/^darwin$/i.test(process.platform)) {
20717
+ extension = macos();
20718
+ } else if (/^win/i.test(process.platform)) {
20719
+ extension = windows();
20720
+ } else {
20721
+ extension = linux();
20722
+ }
20723
+
20724
+ extension.configDirs = () => {
20725
+ const dirs = [];
20726
+ dirs.push(extension.config());
20727
+ if (process.env.XDG_CONFIG_DIRS) {
20728
+ dirs.push(...process.env.XDG_CONFIG_DIRS.split(path.delimiter));
20729
+ }
20730
+
20731
+ return dirs;
20732
+ };
20733
+
20734
+ extension.dataDirs = () => {
20735
+ const dirs = [];
20736
+ dirs.push(extension.data());
20737
+ if (process.env.XDG_DATA_DIRS) {
20738
+ dirs.push(...process.env.XDG_DATA_DIRS.split(path.delimiter));
20739
+ }
20740
+
20741
+ return dirs;
20742
+ };
20743
+
20744
+ Object.keys(extension).forEach((key) => {
20745
+ XDGPortable[key] = extension[key];
20746
+ });
20747
+
20748
+ return XDGPortable;
20749
+ };
20750
+
20751
+ module.exports = _XDGPortable();
20752
+
20753
+
19630
20754
  /***/ }),
19631
20755
 
19632
20756
  /***/ 194:
@@ -20079,75 +21203,1512 @@ try {
20079
21203
 
20080
21204
  /***/ }),
20081
21205
 
20082
- /***/ 3097:
20083
- /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
21206
+ /***/ 5011:
21207
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
20084
21208
 
20085
21209
  "use strict";
21210
+ /* --------------------
21211
+ * yauzl-clone module
21212
+ * Clone yauzl module so it can be modified without affecting original
21213
+ * ------------------*/
20086
21214
 
20087
- var __importDefault = (this && this.__importDefault) || function (mod) {
20088
- return (mod && mod.__esModule) ? mod : { "default": mod };
20089
- };
20090
- Object.defineProperty(exports, "__esModule", ({ value: true }));
20091
- exports.downloadGo = exports.createGo = exports.getAnalyzedEntrypoint = exports.OUT_EXTENSION = exports.cacheDir = void 0;
20092
- const tar_1 = __importDefault(__webpack_require__(6758));
20093
- const execa_1 = __importDefault(__webpack_require__(389));
20094
- const node_fetch_1 = __importDefault(__webpack_require__(779));
20095
- const fs_extra_1 = __webpack_require__(7692);
20096
- const path_1 = __webpack_require__(5622);
20097
- const string_argv_1 = __importDefault(__webpack_require__(2534));
20098
- const build_utils_1 = __webpack_require__(3445);
20099
- const versionMap = new Map([
20100
- ['1.19', '1.19.5'],
20101
- ['1.18', '1.18.1'],
20102
- ['1.17', '1.17.3'],
20103
- ['1.16', '1.16.10'],
20104
- ['1.15', '1.15.8'],
20105
- ['1.14', '1.14.15'],
20106
- ['1.13', '1.13.15'],
20107
- ]);
20108
- const archMap = new Map([
20109
- ['x64', 'amd64'],
20110
- ['x86', '386'],
20111
- ]);
20112
- const platformMap = new Map([['win32', 'windows']]);
20113
- exports.cacheDir = path_1.join('.vercel', 'cache', 'golang');
20114
- const getGoDir = (workPath) => path_1.join(workPath, exports.cacheDir);
20115
- const GO_FLAGS = process.platform === 'win32' ? [] : ['-ldflags', '-s -w'];
20116
- const GO_MIN_VERSION = 13;
20117
- const getPlatform = (p) => platformMap.get(p) || p;
20118
- const getArch = (a) => archMap.get(a) || a;
20119
- const getGoUrl = (version, platform, arch) => {
20120
- const goArch = getArch(arch);
20121
- const goPlatform = getPlatform(platform);
20122
- const ext = platform === 'win32' ? 'zip' : 'tar.gz';
20123
- return `https://dl.google.com/go/go${version}.${goPlatform}-${goArch}.${ext}`;
21215
+
21216
+
21217
+ // Modules
21218
+ const util = __webpack_require__(1669),
21219
+ eventsIntercept = __webpack_require__(7052);
21220
+
21221
+ // Exports
21222
+ module.exports = {
21223
+ clone,
21224
+ patch,
21225
+ patchAll
20124
21226
  };
20125
- exports.OUT_EXTENSION = process.platform === 'win32' ? '.exe' : '';
20126
- async function getAnalyzedEntrypoint(workPath, filePath, modulePath) {
20127
- build_utils_1.debug('Analyzing entrypoint %o with modulePath %o', filePath, modulePath);
20128
- const bin = path_1.join(__dirname, `analyze${exports.OUT_EXTENSION}`);
20129
- const isAnalyzeExist = await fs_extra_1.pathExists(bin);
20130
- if (!isAnalyzeExist) {
20131
- const src = __webpack_require__.ab + "analyze.go";
20132
- const go = await downloadGo(workPath, modulePath);
20133
- await go.build(__webpack_require__.ab + "analyze.go", bin);
20134
- }
20135
- const args = [`-modpath=${modulePath}`, filePath];
20136
- const analyzed = await execa_1.default.stdout(bin, args);
20137
- build_utils_1.debug('Analyzed entrypoint %o', analyzed);
21227
+
21228
+ /**
21229
+ * yauzlClone.clone( yauzl [, options] )
21230
+ *
21231
+ * Clone `yauzl` object and optionally subclass `yauzl.ZipFile` + `yauzl.Entry`
21232
+ * @param {Object} yauzl - yauzl module object
21233
+ * @param {Object} [options] - options object
21234
+ * @param {boolean} [options.clone=true] - If true, creates clone of `yauzl` object
21235
+ * @param {boolean} [options.subclassZipFile=false] - If true, creates subclass of
21236
+ * `yauzl.ZipFile` and saves to `yauzl` object
21237
+ * @param {boolean} [options.subclassEntry=false] - If true, creates subclass of
21238
+ * `yauzl.Entry` and saves to `yauzl` object
21239
+ * @param {boolean} [options.eventsIntercept=false] - If true, patches prototype of
21240
+ * `yauzl.ZipFile` to support event interception using events-intercept module
21241
+ * @returns {Object} - Cloned yauzl module object
21242
+ *
21243
+ * If ZipFile is subclassed, all access methods (`.open()`, `.fromFd()` etc) are
21244
+ * patched to callback with an instance of the ZipFile subclass.
21245
+ *
21246
+ * If Entry is subclassed, emitted 'entry' events are intercepted and re-emitted
21247
+ * so entries are instance of the entry subclass.
21248
+ */
21249
+ function clone(yauzl, options) {
21250
+ // Conform options
21251
+ options = Object.assign({
21252
+ clone: true,
21253
+ subclassZipFile: false,
21254
+ subclassEntry: false,
21255
+ eventsIntercept: false
21256
+ }, options);
21257
+ if (options.subclassEntry) options.eventsIntercept = true;
21258
+
21259
+ // Clone main object
21260
+ if (options.clone) yauzl = Object.assign({}, yauzl);
21261
+
21262
+ // Subclass ZipFile
21263
+ if (options.subclassZipFile) {
21264
+ // Subclass ZipFile
21265
+ const original = yauzl.ZipFile;
21266
+ yauzl.ZipFile = function ZipFile() {
21267
+ original.apply(this, arguments);
21268
+ };
21269
+ util.inherits(yauzl.ZipFile, original);
21270
+
21271
+ // Patch access methods to callback with instance of ZipFile subclass
21272
+ patchAll(yauzl, original => zipFilePatcher(original, yauzl.ZipFile));
21273
+ }
21274
+
21275
+ // Patch ZipFile prototype with events-intercept methods
21276
+ if (options.eventsIntercept) {
21277
+ const ZipFileProto = yauzl.ZipFile.prototype;
21278
+ if (!ZipFileProto.intercept) {
21279
+ eventsIntercept.patch(ZipFileProto);
21280
+ ['_events', '_eventsCount', '_interceptors'].forEach(key => delete ZipFileProto[key]);
21281
+ }
21282
+ }
21283
+
21284
+ // Subclass Entry
21285
+ if (options.subclassEntry) {
21286
+ // Subclass Entry
21287
+ const original = yauzl.Entry;
21288
+ yauzl.Entry = function Entry() {
21289
+ original.apply(this, arguments);
21290
+ };
21291
+ util.inherits(yauzl.Entry, original);
21292
+
21293
+ // Patch access methods to add 'entry' event interceptor
21294
+ // which re-emits instances of Entry subclass
21295
+ patchAll(yauzl, original => entryPatcher(original, yauzl.Entry));
21296
+ }
21297
+
21298
+ // Return cloned copy of yauzl
21299
+ return yauzl;
21300
+ }
21301
+
21302
+ /**
21303
+ * yauzlClone.patchAll( yauzl, fn )
21304
+ *
21305
+ * Patch all access methods with patcher function `fn`
21306
+ * @param {Object} yauzl - yauzl module object
21307
+ * @param {Function} fn - Patcher function
21308
+ * @returns {undefined}
21309
+ *
21310
+ * Patcher function will be called with arguments `(original)` which is original
21311
+ * method (see below for complications)
21312
+ */
21313
+ function patchAll(yauzl, fn) {
21314
+ patch(yauzl, 'open', fn);
21315
+ patch(yauzl, 'fromFd', fn);
21316
+ patch(yauzl, 'fromBuffer', fn);
21317
+ patch(yauzl, 'fromRandomAccessReader', fn);
21318
+ }
21319
+
21320
+ /**
21321
+ * yauzlClone.patch( yauzl, fnName, fn )
21322
+ *
21323
+ * Patch access method with patcher function `fn`
21324
+ * @param {Object} yauzl - yauzl module object
21325
+ * @param {String} fnName - Name of method to patch
21326
+ * @param {Function} fn - Patcher function
21327
+ * @returns {Function} - Patched function
21328
+ *
21329
+ * Patcher function will be called with arguments `(original)` which is original
21330
+ * method.
21331
+ *
21332
+ * EXCEPT: Arguments are conformed so they're the same for all 4 access methods.
21333
+ * This involves adding a dummy extra argument to `.open()`, `.fromFd()` and
21334
+ * `.fromBuffer()`.
21335
+ * Rationale is to make it easier to use the same patching function for all 4
21336
+ * methods so no need to conform arguments in the patching function.
21337
+ *
21338
+ * e.g.:
21339
+ * patchMethod(yauzl, 'open', function(original) {
21340
+ * return function(path, _, options, callback) {
21341
+ * original.call(path, _, options, function(err, zipFile) {
21342
+ * // Do something to modify zipFile
21343
+ * callback(err, zipFile);
21344
+ * });
21345
+ * });
21346
+ * });
21347
+ */
21348
+ function patch(yauzl, methodName, fn) {
21349
+ // Convert original function to function which takes 4 arguments
21350
+ // i.e. open(path, options, cb) -> open(path, _, options, cb)
21351
+ // So same shimming function can be used on all 4 methods.
21352
+ const original = yauzl[methodName];
21353
+ if (methodName == 'fromRandomAccessReader') {
21354
+ const shimmed = fn(original);
21355
+
21356
+ yauzl.fromRandomAccessReader = function(reader, totalSize, options, callback) {
21357
+ if (typeof options == 'function') {
21358
+ callback = options;
21359
+ options = {};
21360
+ } else if (!options) {
21361
+ options = {};
21362
+ }
21363
+
21364
+ return shimmed.call(this, reader, totalSize, options, callback);
21365
+ };
21366
+ } else {
21367
+ const shimmed = fn(function(path, unused, options, callback) { // jshint ignore:line
21368
+ return original.call(this, path, options, callback);
21369
+ });
21370
+
21371
+ yauzl[methodName] = function(path, options, callback) {
21372
+ if (typeof options == 'function') {
21373
+ callback = options;
21374
+ options = {};
21375
+ } else if (!options) {
21376
+ options = {};
21377
+ }
21378
+
21379
+ return shimmed.call(this, path, null, options, callback);
21380
+ };
21381
+ }
21382
+
21383
+ // Return shimmed function
21384
+ return yauzl[methodName];
21385
+ }
21386
+
21387
+ /**
21388
+ * Patcher to make all access methods callback with instance of ZipFile subclass
21389
+ * (rather than original yauzl.ZipFile class)
21390
+ */
21391
+ function zipFilePatcher(original, ZipFile) {
21392
+ return function(path, totalSize, options, callback) {
21393
+ // Set `lazyEntries` option to prevent `._readEntry()` being called on
21394
+ // internal zipFile object. Needs to be called on subclass instance instead.
21395
+ const {lazyEntries} = options,
21396
+ hasLazyEntries = options.hasOwnProperty('lazyEntries');
21397
+ if (!lazyEntries) options.lazyEntries = true;
21398
+
21399
+ // Call original method
21400
+ return original.call(this, path, totalSize, options, function(err, zipFile) {
21401
+ if (err) return callback(err);
21402
+
21403
+ // Convert to instance of subclass
21404
+ const zipFileInternal = zipFile;
21405
+ zipFile = Object.assign(Object.create(ZipFile.prototype), zipFile);
21406
+
21407
+ // Forward events from internal ZipFile to exposed one
21408
+ zipFileInternal.emit = zipFile.emit.bind(zipFile);
21409
+
21410
+ // If lazyEntries option was modified, restore to previous setting
21411
+ // and call `._readEntry()` on subclass instance
21412
+ if (!lazyEntries) {
21413
+ if (hasLazyEntries) {
21414
+ options.lazyEntries = lazyEntries;
21415
+ } else {
21416
+ delete options.lazyEntries;
21417
+ }
21418
+
21419
+ zipFile.lazyEntries = false;
21420
+ zipFileInternal.lazyEntries = false;
21421
+
21422
+ zipFile._readEntry();
21423
+ }
21424
+
21425
+ // Callback with subclass instance
21426
+ callback(null, zipFile);
21427
+ });
21428
+ };
21429
+ }
21430
+
21431
+ /**
21432
+ * Patcher to make all access methods attach event interceptor to zipFiles
21433
+ * which intercept 'entry' events and re-emit entries from Entry subclass
21434
+ */
21435
+ function entryPatcher(original, Entry) {
21436
+ return function(path, totalSize, options, callback) {
21437
+ return original.call(this, path, totalSize, options, function(err, zipFile) {
21438
+ if (err) return callback(err);
21439
+
21440
+ zipFile.intercept('entry', function(entry, cb) {
21441
+ entry = Object.assign(Object.create(Entry.prototype), entry);
21442
+ cb(null, entry);
21443
+ });
21444
+
21445
+ callback(null, zipFile);
21446
+ });
21447
+ };
21448
+ }
21449
+
21450
+
21451
+ /***/ }),
21452
+
21453
+ /***/ 7542:
21454
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
21455
+
21456
+ "use strict";
21457
+ /* --------------------
21458
+ * yauzl-promise module
21459
+ * ------------------*/
21460
+
21461
+
21462
+
21463
+ // Modules
21464
+ const yauzlOriginal = __webpack_require__(2277),
21465
+ cloner = __webpack_require__(5011);
21466
+
21467
+ // Imports
21468
+ const NativePromise = __webpack_require__(612),
21469
+ promisify = __webpack_require__(9384);
21470
+
21471
+ // Exports
21472
+ function use(Promise, yauzl, options) {
21473
+ // Conform options
21474
+ options = Object.assign({clone: true}, options);
21475
+
21476
+ // Use defaults if not provided
21477
+ if (!Promise) Promise = NativePromise;
21478
+ if (!yauzl) yauzl = yauzlOriginal;
21479
+
21480
+ // Clone yauzl unless `options.clone` false
21481
+ if (options.clone) {
21482
+ yauzl = cloner.clone(yauzl, {subclassZipFile: true, subclassEntry: true});
21483
+ } else {
21484
+ // Patch ZipFile prototype with events-intercept methods
21485
+ cloner.clone(yauzl, {clone: false, eventsIntercept: true});
21486
+ }
21487
+
21488
+ // Add promisfied methods
21489
+ if (Promise) {
21490
+ promisify(yauzl, Promise);
21491
+ } else {
21492
+ yauzl = {};
21493
+ }
21494
+
21495
+ // Add `use` methods
21496
+ yauzl.use = use;
21497
+ yauzl.usePromise = function(Promise) {
21498
+ return use(Promise, null);
21499
+ };
21500
+ yauzl.useYauzl = function(yauzl, options) {
21501
+ return use(null, yauzl, options);
21502
+ };
21503
+
21504
+ // Return yauzl object
21505
+ return yauzl;
21506
+ }
21507
+
21508
+ module.exports = use();
21509
+
21510
+
21511
+ /***/ }),
21512
+
21513
+ /***/ 612:
21514
+ /***/ ((module) => {
21515
+
21516
+ "use strict";
21517
+ /* --------------------
21518
+ * yauzl-promise module
21519
+ * Return native Promise
21520
+ * ------------------*/
21521
+
21522
+
21523
+
21524
+ // Exports
21525
+ let NativePromise;
21526
+ try {
21527
+ NativePromise = Promise;
21528
+ } catch(e) {}
21529
+
21530
+ module.exports = NativePromise;
21531
+
21532
+
21533
+ /***/ }),
21534
+
21535
+ /***/ 9384:
21536
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
21537
+
21538
+ "use strict";
21539
+ /* --------------------
21540
+ * yauzl-promise module
21541
+ * Promisify yauzl
21542
+ * ------------------*/
21543
+
21544
+
21545
+
21546
+ // Modules
21547
+ const cloner = __webpack_require__(5011);
21548
+
21549
+ // Constants
21550
+ const STATE = Symbol(),
21551
+ STORED_ERROR = Symbol();
21552
+
21553
+ // Exports
21554
+ module.exports = (yauzl, Promise) => {
21555
+ const {ZipFile, Entry} = yauzl;
21556
+
21557
+ // Promisify open + from... methods
21558
+ promisifyMethod(yauzl, Promise, 'open');
21559
+ promisifyMethod(yauzl, Promise, 'fromFd');
21560
+ promisifyMethod(yauzl, Promise, 'fromBuffer');
21561
+ promisifyMethod(yauzl, Promise, 'fromRandomAccessReader');
21562
+
21563
+ // Promisify `close` method
21564
+ promisifyClose(ZipFile, Promise);
21565
+
21566
+ // Promisify ZipFile `readEntry` method
21567
+ promisifyReadEntry(ZipFile, Promise);
21568
+
21569
+ // Add ZipFile `readEntries` + `walkEntries` methods
21570
+ ZipFile.prototype.readEntries = readEntries;
21571
+ addWalkEntriesMethod(ZipFile, Promise);
21572
+
21573
+ // Promisify ZipFile `openReadStream` method
21574
+ promisifyOpenReadStream(ZipFile, Promise);
21575
+
21576
+ // Add Entry `openReadStream` method
21577
+ Entry.prototype.openReadStream = entryOpenReadStream;
21578
+
21579
+ // Add reference to Entry to ZipFile (used by `readEntries`)
21580
+ ZipFile.Entry = Entry;
21581
+ };
21582
+
21583
+ /*
21584
+ * Promisify open/from... method
21585
+ */
21586
+ function promisifyMethod(yauzl, Promise, fnName) {
21587
+ const fromBuffer = fnName == 'fromBuffer';
21588
+
21589
+ cloner.patch(yauzl, fnName, original => {
21590
+ return function(path, totalSize, options) {
21591
+ return new Promise((resolve, reject) => {
21592
+ options = Object.assign({}, options, {lazyEntries: true, autoClose: false});
21593
+
21594
+ original(path, totalSize, options, (err, zipFile) => {
21595
+ if (err) return reject(err);
21596
+ opened(zipFile, resolve, fromBuffer, yauzl);
21597
+ });
21598
+ });
21599
+ };
21600
+ });
21601
+ }
21602
+
21603
+ function opened(zipFile, resolve, fromBuffer, yauzl) {
21604
+ // For `.fromBuffer()` calls, adapt `reader` to emit close event
21605
+ if (fromBuffer) {
21606
+ zipFile.reader.unref = yauzl.RandomAccessReader.prototype.unref;
21607
+ zipFile.reader.close = cb => cb();
21608
+ }
21609
+
21610
+ // Init
21611
+ clearState(zipFile);
21612
+ clearError(zipFile);
21613
+
21614
+ // Intercept events
21615
+ zipFile.intercept('entry', emittedEntry);
21616
+ zipFile.intercept('end', emittedEnd);
21617
+ zipFile.intercept('close', emittedClose);
21618
+ zipFile.intercept('error', emittedError);
21619
+
21620
+ // Resolve promise with zip object
21621
+ resolve(zipFile);
21622
+ }
21623
+
21624
+ /*
21625
+ * Error event handler
21626
+ */
21627
+ function emittedError(err) {
21628
+ // jshint validthis:true
21629
+ // If operation in progress, reject its promise
21630
+ const state = getState(this);
21631
+ if (state) {
21632
+ clearState(this);
21633
+ return state.reject(err);
21634
+ }
21635
+
21636
+ // Store error to be returned on next call to
21637
+ // `.readEntry()`, `.close()` or `.openReadStream()`.
21638
+ if (!getError(this)) setError(this, err);
21639
+ }
21640
+
21641
+ function rejectWithStoredError(zipFile, reject) {
21642
+ const err = getError(zipFile);
21643
+ clearError(zipFile);
21644
+ reject(err);
21645
+ }
21646
+
21647
+ /*
21648
+ * Promisify ZipFile `close` method
21649
+ */
21650
+ function promisifyClose(ZipFile, Promise) {
21651
+ const close = ZipFile.prototype.close;
21652
+
21653
+ ZipFile.prototype.close = function() {
21654
+ return new Promise((resolve, reject) => {
21655
+ if (getError(this)) return rejectWithStoredError(this, reject);
21656
+ if (!this.isOpen) return resolve();
21657
+ if (getState(this)) return reject(new Error('Previous operation has not completed yet'));
21658
+
21659
+ setState(this, {action: 'close', resolve, reject});
21660
+ close.call(this);
21661
+ });
21662
+ };
21663
+ }
21664
+
21665
+ function emittedClose() {
21666
+ // jshint validthis:true
21667
+ // If not closing, emit error
21668
+ const state = getState(this);
21669
+ if (!state || state.action != 'close') return this.emit('error', new Error('Unexpected \'close\' event emitted'));
21670
+
21671
+ clearState(this);
21672
+
21673
+ // Resolve promise
21674
+ state.resolve();
21675
+ }
21676
+
21677
+ /*
21678
+ * Promisify ZipFile `readEntry` method
21679
+ */
21680
+ function promisifyReadEntry(ZipFile, Promise) {
21681
+ const readEntry = ZipFile.prototype.readEntry;
21682
+
21683
+ ZipFile.prototype.readEntry = function() {
21684
+ return new Promise((resolve, reject) => {
21685
+ if (getError(this)) return rejectWithStoredError(this, reject);
21686
+ if (!this.isOpen) return reject(new Error('ZipFile is not open'));
21687
+ if (getState(this)) return reject(new Error('Previous operation has not completed yet'));
21688
+
21689
+ setState(this, {action: 'read', resolve, reject});
21690
+ readEntry.call(this);
21691
+ });
21692
+ };
21693
+ }
21694
+
21695
+ function emittedEntry(entry) {
21696
+ // jshint validthis:true
21697
+ // If not reading, emit error
21698
+ const state = getState(this);
21699
+ if (!state || state.action != 'read') return this.emit('error', new Error(`Unexpected '${entry ? 'entry' : 'end'}' event emitted`));
21700
+
21701
+ clearState(this);
21702
+
21703
+ // Set reference to zipFile on entry (used by `entry.openReadStream()`)
21704
+ if (entry) entry.zipFile = this;
21705
+
21706
+ // Resolve promise with entry
21707
+ state.resolve(entry);
21708
+ }
21709
+
21710
+ function emittedEnd() {
21711
+ // jshint validthis:true
21712
+ emittedEntry.call(this, null);
21713
+ }
21714
+
21715
+ /*
21716
+ * Functions to access state
21717
+ */
21718
+ function getState(zipFile) {
21719
+ return zipFile[STATE];
21720
+ }
21721
+
21722
+ function setState(zipFile, state) {
21723
+ zipFile[STATE] = state;
21724
+ }
21725
+
21726
+ function clearState(zipFile) {
21727
+ zipFile[STATE] = undefined;
21728
+ }
21729
+
21730
+ function getError(zipFile) {
21731
+ return zipFile[STORED_ERROR];
21732
+ }
21733
+
21734
+ function setError(zipFile, state) {
21735
+ zipFile[STORED_ERROR] = state;
21736
+ }
21737
+
21738
+ function clearError(zipFile) {
21739
+ zipFile[STORED_ERROR] = undefined;
21740
+ }
21741
+
21742
+ /*
21743
+ * Read all ZipFile entries
21744
+ * Reads all entries and returns a promise which resolves with an array of entries
21745
+ * `options.max` limits number returned (default 100)
21746
+ * `options.max` can be set to `0` for no limit
21747
+ */
21748
+ function readEntries(numEntries) {
21749
+ // jshint validthis:true
21750
+ const entries = [];
21751
+ return this.walkEntries(entry => {
21752
+ entries.push(entry);
21753
+ }, numEntries).then(() => {
21754
+ return entries;
21755
+ });
21756
+ }
21757
+
21758
+ /*
21759
+ * Walk all ZipFile entries
21760
+ * Walks through each entry and calls `fn` with each.
21761
+ * Returns a promise which resolves when all have been read.
21762
+ */
21763
+ function addWalkEntriesMethod(ZipFile, Promise) {
21764
+ ZipFile.prototype.walkEntries = function(callback, numEntries) {
21765
+ callback = wrapFunctionToReturnPromise(callback, Promise);
21766
+
21767
+ return new Promise((resolve, reject) => {
21768
+ walkNextEntry(this, callback, numEntries, 0, err => {
21769
+ if (err) return reject(err);
21770
+ resolve();
21771
+ });
21772
+ });
21773
+ };
21774
+ }
21775
+
21776
+ function walkNextEntry(zipFile, fn, numEntries, count, cb) {
21777
+ if (numEntries && count == numEntries) return cb();
21778
+
21779
+ zipFile.readEntry().then(entry => {
21780
+ if (!entry) return cb();
21781
+
21782
+ return fn(entry).then(() => {
21783
+ walkNextEntry(zipFile, fn, numEntries, count + 1, cb);
21784
+ });
21785
+ }).catch(err => {
21786
+ cb(err);
21787
+ });
21788
+ }
21789
+
21790
+ /*
21791
+ * Promisify ZipFile `openReadStream` method
21792
+ */
21793
+ function promisifyOpenReadStream(ZipFile, Promise) {
21794
+ const openReadStream = ZipFile.prototype.openReadStream;
21795
+ ZipFile.prototype.openReadStream = function(entry, options) {
21796
+ return new Promise((resolve, reject) => {
21797
+ if (getError(this)) return rejectWithStoredError(this, reject);
21798
+ openReadStream.call(this, entry, options || {}, (err, stream) => {
21799
+ if (err) return reject(err);
21800
+ resolve(stream);
21801
+ });
21802
+ });
21803
+ };
21804
+ }
21805
+
21806
+ /*
21807
+ * Entry `openReadStream` method
21808
+ */
21809
+ function entryOpenReadStream(options) {
21810
+ // jshint validthis:true
21811
+ return this.zipFile.openReadStream(this, options);
21812
+ }
21813
+
21814
+ /*
21815
+ * Utility functions
21816
+ */
21817
+ function wrapFunctionToReturnPromise(fn, Promise) {
21818
+ return function() {
21819
+ try {
21820
+ const result = fn.apply(this, arguments);
21821
+ if (result instanceof Promise) return result;
21822
+ return Promise.resolve(result);
21823
+ } catch (err) {
21824
+ return new Promise((resolve, reject) => { // jshint ignore:line
21825
+ reject(err);
21826
+ });
21827
+ }
21828
+ };
21829
+ }
21830
+
21831
+
21832
+ /***/ }),
21833
+
21834
+ /***/ 2277:
21835
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
21836
+
21837
+ var fs = __webpack_require__(5747);
21838
+ var zlib = __webpack_require__(8761);
21839
+ var fd_slicer = __webpack_require__(402);
21840
+ var crc32 = __webpack_require__(7938);
21841
+ var util = __webpack_require__(1669);
21842
+ var EventEmitter = __webpack_require__(8614).EventEmitter;
21843
+ var Transform = __webpack_require__(2413).Transform;
21844
+ var PassThrough = __webpack_require__(2413).PassThrough;
21845
+ var Writable = __webpack_require__(2413).Writable;
21846
+
21847
+ exports.open = open;
21848
+ exports.fromFd = fromFd;
21849
+ exports.fromBuffer = fromBuffer;
21850
+ exports.fromRandomAccessReader = fromRandomAccessReader;
21851
+ exports.dosDateTimeToDate = dosDateTimeToDate;
21852
+ exports.validateFileName = validateFileName;
21853
+ exports.ZipFile = ZipFile;
21854
+ exports.Entry = Entry;
21855
+ exports.RandomAccessReader = RandomAccessReader;
21856
+
21857
+ function open(path, options, callback) {
21858
+ if (typeof options === "function") {
21859
+ callback = options;
21860
+ options = null;
21861
+ }
21862
+ if (options == null) options = {};
21863
+ if (options.autoClose == null) options.autoClose = true;
21864
+ if (options.lazyEntries == null) options.lazyEntries = false;
21865
+ if (options.decodeStrings == null) options.decodeStrings = true;
21866
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
21867
+ if (options.strictFileNames == null) options.strictFileNames = false;
21868
+ if (callback == null) callback = defaultCallback;
21869
+ fs.open(path, "r", function(err, fd) {
21870
+ if (err) return callback(err);
21871
+ fromFd(fd, options, function(err, zipfile) {
21872
+ if (err) fs.close(fd, defaultCallback);
21873
+ callback(err, zipfile);
21874
+ });
21875
+ });
21876
+ }
21877
+
21878
+ function fromFd(fd, options, callback) {
21879
+ if (typeof options === "function") {
21880
+ callback = options;
21881
+ options = null;
21882
+ }
21883
+ if (options == null) options = {};
21884
+ if (options.autoClose == null) options.autoClose = false;
21885
+ if (options.lazyEntries == null) options.lazyEntries = false;
21886
+ if (options.decodeStrings == null) options.decodeStrings = true;
21887
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
21888
+ if (options.strictFileNames == null) options.strictFileNames = false;
21889
+ if (callback == null) callback = defaultCallback;
21890
+ fs.fstat(fd, function(err, stats) {
21891
+ if (err) return callback(err);
21892
+ var reader = fd_slicer.createFromFd(fd, {autoClose: true});
21893
+ fromRandomAccessReader(reader, stats.size, options, callback);
21894
+ });
21895
+ }
21896
+
21897
+ function fromBuffer(buffer, options, callback) {
21898
+ if (typeof options === "function") {
21899
+ callback = options;
21900
+ options = null;
21901
+ }
21902
+ if (options == null) options = {};
21903
+ options.autoClose = false;
21904
+ if (options.lazyEntries == null) options.lazyEntries = false;
21905
+ if (options.decodeStrings == null) options.decodeStrings = true;
21906
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
21907
+ if (options.strictFileNames == null) options.strictFileNames = false;
21908
+ // limit the max chunk size. see https://github.com/thejoshwolfe/yauzl/issues/87
21909
+ var reader = fd_slicer.createFromBuffer(buffer, {maxChunkSize: 0x10000});
21910
+ fromRandomAccessReader(reader, buffer.length, options, callback);
21911
+ }
21912
+
21913
+ function fromRandomAccessReader(reader, totalSize, options, callback) {
21914
+ if (typeof options === "function") {
21915
+ callback = options;
21916
+ options = null;
21917
+ }
21918
+ if (options == null) options = {};
21919
+ if (options.autoClose == null) options.autoClose = true;
21920
+ if (options.lazyEntries == null) options.lazyEntries = false;
21921
+ if (options.decodeStrings == null) options.decodeStrings = true;
21922
+ var decodeStrings = !!options.decodeStrings;
21923
+ if (options.validateEntrySizes == null) options.validateEntrySizes = true;
21924
+ if (options.strictFileNames == null) options.strictFileNames = false;
21925
+ if (callback == null) callback = defaultCallback;
21926
+ if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
21927
+ if (totalSize > Number.MAX_SAFE_INTEGER) {
21928
+ throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
21929
+ }
21930
+
21931
+ // the matching unref() call is in zipfile.close()
21932
+ reader.ref();
21933
+
21934
+ // eocdr means End of Central Directory Record.
21935
+ // search backwards for the eocdr signature.
21936
+ // the last field of the eocdr is a variable-length comment.
21937
+ // the comment size is encoded in a 2-byte field in the eocdr, which we can't find without trudging backwards through the comment to find it.
21938
+ // as a consequence of this design decision, it's possible to have ambiguous zip file metadata if a coherent eocdr was in the comment.
21939
+ // we search backwards for a eocdr signature, and hope that whoever made the zip file was smart enough to forbid the eocdr signature in the comment.
21940
+ var eocdrWithoutCommentSize = 22;
21941
+ var maxCommentSize = 0xffff; // 2-byte size
21942
+ var bufferSize = Math.min(eocdrWithoutCommentSize + maxCommentSize, totalSize);
21943
+ var buffer = newBuffer(bufferSize);
21944
+ var bufferReadStart = totalSize - buffer.length;
21945
+ readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) {
21946
+ if (err) return callback(err);
21947
+ for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
21948
+ if (buffer.readUInt32LE(i) !== 0x06054b50) continue;
21949
+ // found eocdr
21950
+ var eocdrBuffer = buffer.slice(i);
21951
+
21952
+ // 0 - End of central directory signature = 0x06054b50
21953
+ // 4 - Number of this disk
21954
+ var diskNumber = eocdrBuffer.readUInt16LE(4);
21955
+ if (diskNumber !== 0) {
21956
+ return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
21957
+ }
21958
+ // 6 - Disk where central directory starts
21959
+ // 8 - Number of central directory records on this disk
21960
+ // 10 - Total number of central directory records
21961
+ var entryCount = eocdrBuffer.readUInt16LE(10);
21962
+ // 12 - Size of central directory (bytes)
21963
+ // 16 - Offset of start of central directory, relative to start of archive
21964
+ var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
21965
+ // 20 - Comment length
21966
+ var commentLength = eocdrBuffer.readUInt16LE(20);
21967
+ var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
21968
+ if (commentLength !== expectedCommentLength) {
21969
+ return callback(new Error("invalid comment length. expected: " + expectedCommentLength + ". found: " + commentLength));
21970
+ }
21971
+ // 22 - Comment
21972
+ // the encoding is always cp437.
21973
+ var comment = decodeStrings ? decodeBuffer(eocdrBuffer, 22, eocdrBuffer.length, false)
21974
+ : eocdrBuffer.slice(22);
21975
+
21976
+ if (!(entryCount === 0xffff || centralDirectoryOffset === 0xffffffff)) {
21977
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
21978
+ }
21979
+
21980
+ // ZIP64 format
21981
+
21982
+ // ZIP64 Zip64 end of central directory locator
21983
+ var zip64EocdlBuffer = newBuffer(20);
21984
+ var zip64EocdlOffset = bufferReadStart + i - zip64EocdlBuffer.length;
21985
+ readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err) {
21986
+ if (err) return callback(err);
21987
+
21988
+ // 0 - zip64 end of central dir locator signature = 0x07064b50
21989
+ if (zip64EocdlBuffer.readUInt32LE(0) !== 0x07064b50) {
21990
+ return callback(new Error("invalid zip64 end of central directory locator signature"));
21991
+ }
21992
+ // 4 - number of the disk with the start of the zip64 end of central directory
21993
+ // 8 - relative offset of the zip64 end of central directory record
21994
+ var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
21995
+ // 16 - total number of disks
21996
+
21997
+ // ZIP64 end of central directory record
21998
+ var zip64EocdrBuffer = newBuffer(56);
21999
+ readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err) {
22000
+ if (err) return callback(err);
22001
+
22002
+ // 0 - zip64 end of central dir signature 4 bytes (0x06064b50)
22003
+ if (zip64EocdrBuffer.readUInt32LE(0) !== 0x06064b50) {
22004
+ return callback(new Error("invalid zip64 end of central directory record signature"));
22005
+ }
22006
+ // 4 - size of zip64 end of central directory record 8 bytes
22007
+ // 12 - version made by 2 bytes
22008
+ // 14 - version needed to extract 2 bytes
22009
+ // 16 - number of this disk 4 bytes
22010
+ // 20 - number of the disk with the start of the central directory 4 bytes
22011
+ // 24 - total number of entries in the central directory on this disk 8 bytes
22012
+ // 32 - total number of entries in the central directory 8 bytes
22013
+ entryCount = readUInt64LE(zip64EocdrBuffer, 32);
22014
+ // 40 - size of the central directory 8 bytes
22015
+ // 48 - offset of start of central directory with respect to the starting disk number 8 bytes
22016
+ centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
22017
+ // 56 - zip64 extensible data sector (variable size)
22018
+ return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
22019
+ });
22020
+ });
22021
+ return;
22022
+ }
22023
+ callback(new Error("end of central directory record signature not found"));
22024
+ });
22025
+ }
22026
+
22027
+ util.inherits(ZipFile, EventEmitter);
22028
+ function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
22029
+ var self = this;
22030
+ EventEmitter.call(self);
22031
+ self.reader = reader;
22032
+ // forward close events
22033
+ self.reader.on("error", function(err) {
22034
+ // error closing the fd
22035
+ emitError(self, err);
22036
+ });
22037
+ self.reader.once("close", function() {
22038
+ self.emit("close");
22039
+ });
22040
+ self.readEntryCursor = centralDirectoryOffset;
22041
+ self.fileSize = fileSize;
22042
+ self.entryCount = entryCount;
22043
+ self.comment = comment;
22044
+ self.entriesRead = 0;
22045
+ self.autoClose = !!autoClose;
22046
+ self.lazyEntries = !!lazyEntries;
22047
+ self.decodeStrings = !!decodeStrings;
22048
+ self.validateEntrySizes = !!validateEntrySizes;
22049
+ self.strictFileNames = !!strictFileNames;
22050
+ self.isOpen = true;
22051
+ self.emittedError = false;
22052
+
22053
+ if (!self.lazyEntries) self._readEntry();
22054
+ }
22055
+ ZipFile.prototype.close = function() {
22056
+ if (!this.isOpen) return;
22057
+ this.isOpen = false;
22058
+ this.reader.unref();
22059
+ };
22060
+
22061
+ function emitErrorAndAutoClose(self, err) {
22062
+ if (self.autoClose) self.close();
22063
+ emitError(self, err);
22064
+ }
22065
+ function emitError(self, err) {
22066
+ if (self.emittedError) return;
22067
+ self.emittedError = true;
22068
+ self.emit("error", err);
22069
+ }
22070
+
22071
+ ZipFile.prototype.readEntry = function() {
22072
+ if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
22073
+ this._readEntry();
22074
+ };
22075
+ ZipFile.prototype._readEntry = function() {
22076
+ var self = this;
22077
+ if (self.entryCount === self.entriesRead) {
22078
+ // done with metadata
22079
+ setImmediate(function() {
22080
+ if (self.autoClose) self.close();
22081
+ if (self.emittedError) return;
22082
+ self.emit("end");
22083
+ });
22084
+ return;
22085
+ }
22086
+ if (self.emittedError) return;
22087
+ var buffer = newBuffer(46);
22088
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
22089
+ if (err) return emitErrorAndAutoClose(self, err);
22090
+ if (self.emittedError) return;
22091
+ var entry = new Entry();
22092
+ // 0 - Central directory file header signature
22093
+ var signature = buffer.readUInt32LE(0);
22094
+ if (signature !== 0x02014b50) return emitErrorAndAutoClose(self, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
22095
+ // 4 - Version made by
22096
+ entry.versionMadeBy = buffer.readUInt16LE(4);
22097
+ // 6 - Version needed to extract (minimum)
22098
+ entry.versionNeededToExtract = buffer.readUInt16LE(6);
22099
+ // 8 - General purpose bit flag
22100
+ entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
22101
+ // 10 - Compression method
22102
+ entry.compressionMethod = buffer.readUInt16LE(10);
22103
+ // 12 - File last modification time
22104
+ entry.lastModFileTime = buffer.readUInt16LE(12);
22105
+ // 14 - File last modification date
22106
+ entry.lastModFileDate = buffer.readUInt16LE(14);
22107
+ // 16 - CRC-32
22108
+ entry.crc32 = buffer.readUInt32LE(16);
22109
+ // 20 - Compressed size
22110
+ entry.compressedSize = buffer.readUInt32LE(20);
22111
+ // 24 - Uncompressed size
22112
+ entry.uncompressedSize = buffer.readUInt32LE(24);
22113
+ // 28 - File name length (n)
22114
+ entry.fileNameLength = buffer.readUInt16LE(28);
22115
+ // 30 - Extra field length (m)
22116
+ entry.extraFieldLength = buffer.readUInt16LE(30);
22117
+ // 32 - File comment length (k)
22118
+ entry.fileCommentLength = buffer.readUInt16LE(32);
22119
+ // 34 - Disk number where file starts
22120
+ // 36 - Internal file attributes
22121
+ entry.internalFileAttributes = buffer.readUInt16LE(36);
22122
+ // 38 - External file attributes
22123
+ entry.externalFileAttributes = buffer.readUInt32LE(38);
22124
+ // 42 - Relative offset of local file header
22125
+ entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
22126
+
22127
+ if (entry.generalPurposeBitFlag & 0x40) return emitErrorAndAutoClose(self, new Error("strong encryption is not supported"));
22128
+
22129
+ self.readEntryCursor += 46;
22130
+
22131
+ buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
22132
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, self.readEntryCursor, function(err) {
22133
+ if (err) return emitErrorAndAutoClose(self, err);
22134
+ if (self.emittedError) return;
22135
+ // 46 - File name
22136
+ var isUtf8 = (entry.generalPurposeBitFlag & 0x800) !== 0;
22137
+ entry.fileName = self.decodeStrings ? decodeBuffer(buffer, 0, entry.fileNameLength, isUtf8)
22138
+ : buffer.slice(0, entry.fileNameLength);
22139
+
22140
+ // 46+n - Extra field
22141
+ var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
22142
+ var extraFieldBuffer = buffer.slice(entry.fileNameLength, fileCommentStart);
22143
+ entry.extraFields = [];
22144
+ var i = 0;
22145
+ while (i < extraFieldBuffer.length - 3) {
22146
+ var headerId = extraFieldBuffer.readUInt16LE(i + 0);
22147
+ var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
22148
+ var dataStart = i + 4;
22149
+ var dataEnd = dataStart + dataSize;
22150
+ if (dataEnd > extraFieldBuffer.length) return emitErrorAndAutoClose(self, new Error("extra field length exceeds extra field buffer size"));
22151
+ var dataBuffer = newBuffer(dataSize);
22152
+ extraFieldBuffer.copy(dataBuffer, 0, dataStart, dataEnd);
22153
+ entry.extraFields.push({
22154
+ id: headerId,
22155
+ data: dataBuffer,
22156
+ });
22157
+ i = dataEnd;
22158
+ }
22159
+
22160
+ // 46+n+m - File comment
22161
+ entry.fileComment = self.decodeStrings ? decodeBuffer(buffer, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf8)
22162
+ : buffer.slice(fileCommentStart, fileCommentStart + entry.fileCommentLength);
22163
+ // compatibility hack for https://github.com/thejoshwolfe/yauzl/issues/47
22164
+ entry.comment = entry.fileComment;
22165
+
22166
+ self.readEntryCursor += buffer.length;
22167
+ self.entriesRead += 1;
22168
+
22169
+ if (entry.uncompressedSize === 0xffffffff ||
22170
+ entry.compressedSize === 0xffffffff ||
22171
+ entry.relativeOffsetOfLocalHeader === 0xffffffff) {
22172
+ // ZIP64 format
22173
+ // find the Zip64 Extended Information Extra Field
22174
+ var zip64EiefBuffer = null;
22175
+ for (var i = 0; i < entry.extraFields.length; i++) {
22176
+ var extraField = entry.extraFields[i];
22177
+ if (extraField.id === 0x0001) {
22178
+ zip64EiefBuffer = extraField.data;
22179
+ break;
22180
+ }
22181
+ }
22182
+ if (zip64EiefBuffer == null) {
22183
+ return emitErrorAndAutoClose(self, new Error("expected zip64 extended information extra field"));
22184
+ }
22185
+ var index = 0;
22186
+ // 0 - Original Size 8 bytes
22187
+ if (entry.uncompressedSize === 0xffffffff) {
22188
+ if (index + 8 > zip64EiefBuffer.length) {
22189
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include uncompressed size"));
22190
+ }
22191
+ entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
22192
+ index += 8;
22193
+ }
22194
+ // 8 - Compressed Size 8 bytes
22195
+ if (entry.compressedSize === 0xffffffff) {
22196
+ if (index + 8 > zip64EiefBuffer.length) {
22197
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include compressed size"));
22198
+ }
22199
+ entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
22200
+ index += 8;
22201
+ }
22202
+ // 16 - Relative Header Offset 8 bytes
22203
+ if (entry.relativeOffsetOfLocalHeader === 0xffffffff) {
22204
+ if (index + 8 > zip64EiefBuffer.length) {
22205
+ return emitErrorAndAutoClose(self, new Error("zip64 extended information extra field does not include relative header offset"));
22206
+ }
22207
+ entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
22208
+ index += 8;
22209
+ }
22210
+ // 24 - Disk Start Number 4 bytes
22211
+ }
22212
+
22213
+ // check for Info-ZIP Unicode Path Extra Field (0x7075)
22214
+ // see https://github.com/thejoshwolfe/yauzl/issues/33
22215
+ if (self.decodeStrings) {
22216
+ for (var i = 0; i < entry.extraFields.length; i++) {
22217
+ var extraField = entry.extraFields[i];
22218
+ if (extraField.id === 0x7075) {
22219
+ if (extraField.data.length < 6) {
22220
+ // too short to be meaningful
22221
+ continue;
22222
+ }
22223
+ // Version 1 byte version of this extra field, currently 1
22224
+ if (extraField.data.readUInt8(0) !== 1) {
22225
+ // > Changes may not be backward compatible so this extra
22226
+ // > field should not be used if the version is not recognized.
22227
+ continue;
22228
+ }
22229
+ // NameCRC32 4 bytes File Name Field CRC32 Checksum
22230
+ var oldNameCrc32 = extraField.data.readUInt32LE(1);
22231
+ if (crc32.unsigned(buffer.slice(0, entry.fileNameLength)) !== oldNameCrc32) {
22232
+ // > If the CRC check fails, this UTF-8 Path Extra Field should be
22233
+ // > ignored and the File Name field in the header should be used instead.
22234
+ continue;
22235
+ }
22236
+ // UnicodeName Variable UTF-8 version of the entry File Name
22237
+ entry.fileName = decodeBuffer(extraField.data, 5, extraField.data.length, true);
22238
+ break;
22239
+ }
22240
+ }
22241
+ }
22242
+
22243
+ // validate file size
22244
+ if (self.validateEntrySizes && entry.compressionMethod === 0) {
22245
+ var expectedCompressedSize = entry.uncompressedSize;
22246
+ if (entry.isEncrypted()) {
22247
+ // traditional encryption prefixes the file data with a header
22248
+ expectedCompressedSize += 12;
22249
+ }
22250
+ if (entry.compressedSize !== expectedCompressedSize) {
22251
+ var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
22252
+ return emitErrorAndAutoClose(self, new Error(msg));
22253
+ }
22254
+ }
22255
+
22256
+ if (self.decodeStrings) {
22257
+ if (!self.strictFileNames) {
22258
+ // allow backslash
22259
+ entry.fileName = entry.fileName.replace(/\\/g, "/");
22260
+ }
22261
+ var errorMessage = validateFileName(entry.fileName, self.validateFileNameOptions);
22262
+ if (errorMessage != null) return emitErrorAndAutoClose(self, new Error(errorMessage));
22263
+ }
22264
+ self.emit("entry", entry);
22265
+
22266
+ if (!self.lazyEntries) self._readEntry();
22267
+ });
22268
+ });
22269
+ };
22270
+
22271
+ ZipFile.prototype.openReadStream = function(entry, options, callback) {
22272
+ var self = this;
22273
+ // parameter validation
22274
+ var relativeStart = 0;
22275
+ var relativeEnd = entry.compressedSize;
22276
+ if (callback == null) {
22277
+ callback = options;
22278
+ options = {};
22279
+ } else {
22280
+ // validate options that the caller has no excuse to get wrong
22281
+ if (options.decrypt != null) {
22282
+ if (!entry.isEncrypted()) {
22283
+ throw new Error("options.decrypt can only be specified for encrypted entries");
22284
+ }
22285
+ if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt);
22286
+ if (entry.isCompressed()) {
22287
+ if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false");
22288
+ }
22289
+ }
22290
+ if (options.decompress != null) {
22291
+ if (!entry.isCompressed()) {
22292
+ throw new Error("options.decompress can only be specified for compressed entries");
22293
+ }
22294
+ if (!(options.decompress === false || options.decompress === true)) {
22295
+ throw new Error("invalid options.decompress value: " + options.decompress);
22296
+ }
22297
+ }
22298
+ if (options.start != null || options.end != null) {
22299
+ if (entry.isCompressed() && options.decompress !== false) {
22300
+ throw new Error("start/end range not allowed for compressed entry without options.decompress === false");
22301
+ }
22302
+ if (entry.isEncrypted() && options.decrypt !== false) {
22303
+ throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false");
22304
+ }
22305
+ }
22306
+ if (options.start != null) {
22307
+ relativeStart = options.start;
22308
+ if (relativeStart < 0) throw new Error("options.start < 0");
22309
+ if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
22310
+ }
22311
+ if (options.end != null) {
22312
+ relativeEnd = options.end;
22313
+ if (relativeEnd < 0) throw new Error("options.end < 0");
22314
+ if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
22315
+ if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
22316
+ }
22317
+ }
22318
+ // any further errors can either be caused by the zipfile,
22319
+ // or were introduced in a minor version of yauzl,
22320
+ // so should be passed to the client rather than thrown.
22321
+ if (!self.isOpen) return callback(new Error("closed"));
22322
+ if (entry.isEncrypted()) {
22323
+ if (options.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false"));
22324
+ }
22325
+ // make sure we don't lose the fd before we open the actual read stream
22326
+ self.reader.ref();
22327
+ var buffer = newBuffer(30);
22328
+ readAndAssertNoEof(self.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
22329
+ try {
22330
+ if (err) return callback(err);
22331
+ // 0 - Local file header signature = 0x04034b50
22332
+ var signature = buffer.readUInt32LE(0);
22333
+ if (signature !== 0x04034b50) {
22334
+ return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
22335
+ }
22336
+ // all this should be redundant
22337
+ // 4 - Version needed to extract (minimum)
22338
+ // 6 - General purpose bit flag
22339
+ // 8 - Compression method
22340
+ // 10 - File last modification time
22341
+ // 12 - File last modification date
22342
+ // 14 - CRC-32
22343
+ // 18 - Compressed size
22344
+ // 22 - Uncompressed size
22345
+ // 26 - File name length (n)
22346
+ var fileNameLength = buffer.readUInt16LE(26);
22347
+ // 28 - Extra field length (m)
22348
+ var extraFieldLength = buffer.readUInt16LE(28);
22349
+ // 30 - File name
22350
+ // 30+n - Extra field
22351
+ var localFileHeaderEnd = entry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength;
22352
+ var decompress;
22353
+ if (entry.compressionMethod === 0) {
22354
+ // 0 - The file is stored (no compression)
22355
+ decompress = false;
22356
+ } else if (entry.compressionMethod === 8) {
22357
+ // 8 - The file is Deflated
22358
+ decompress = options.decompress != null ? options.decompress : true;
22359
+ } else {
22360
+ return callback(new Error("unsupported compression method: " + entry.compressionMethod));
22361
+ }
22362
+ var fileDataStart = localFileHeaderEnd;
22363
+ var fileDataEnd = fileDataStart + entry.compressedSize;
22364
+ if (entry.compressedSize !== 0) {
22365
+ // bounds check now, because the read streams will probably not complain loud enough.
22366
+ // since we're dealing with an unsigned offset plus an unsigned size,
22367
+ // we only have 1 thing to check for.
22368
+ if (fileDataEnd > self.fileSize) {
22369
+ return callback(new Error("file data overflows file bounds: " +
22370
+ fileDataStart + " + " + entry.compressedSize + " > " + self.fileSize));
22371
+ }
22372
+ }
22373
+ var readStream = self.reader.createReadStream({
22374
+ start: fileDataStart + relativeStart,
22375
+ end: fileDataStart + relativeEnd,
22376
+ });
22377
+ var endpointStream = readStream;
22378
+ if (decompress) {
22379
+ var destroyed = false;
22380
+ var inflateFilter = zlib.createInflateRaw();
22381
+ readStream.on("error", function(err) {
22382
+ // setImmediate here because errors can be emitted during the first call to pipe()
22383
+ setImmediate(function() {
22384
+ if (!destroyed) inflateFilter.emit("error", err);
22385
+ });
22386
+ });
22387
+ readStream.pipe(inflateFilter);
22388
+
22389
+ if (self.validateEntrySizes) {
22390
+ endpointStream = new AssertByteCountStream(entry.uncompressedSize);
22391
+ inflateFilter.on("error", function(err) {
22392
+ // forward zlib errors to the client-visible stream
22393
+ setImmediate(function() {
22394
+ if (!destroyed) endpointStream.emit("error", err);
22395
+ });
22396
+ });
22397
+ inflateFilter.pipe(endpointStream);
22398
+ } else {
22399
+ // the zlib filter is the client-visible stream
22400
+ endpointStream = inflateFilter;
22401
+ }
22402
+ // this is part of yauzl's API, so implement this function on the client-visible stream
22403
+ endpointStream.destroy = function() {
22404
+ destroyed = true;
22405
+ if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
22406
+ readStream.unpipe(inflateFilter);
22407
+ // TODO: the inflateFilter may cause a memory leak. see Issue #27.
22408
+ readStream.destroy();
22409
+ };
22410
+ }
22411
+ callback(null, endpointStream);
22412
+ } finally {
22413
+ self.reader.unref();
22414
+ }
22415
+ });
22416
+ };
22417
+
22418
+ function Entry() {
22419
+ }
22420
+ Entry.prototype.getLastModDate = function() {
22421
+ return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime);
22422
+ };
22423
+ Entry.prototype.isEncrypted = function() {
22424
+ return (this.generalPurposeBitFlag & 0x1) !== 0;
22425
+ };
22426
+ Entry.prototype.isCompressed = function() {
22427
+ return this.compressionMethod === 8;
22428
+ };
22429
+
22430
+ function dosDateTimeToDate(date, time) {
22431
+ var day = date & 0x1f; // 1-31
22432
+ var month = (date >> 5 & 0xf) - 1; // 1-12, 0-11
22433
+ var year = (date >> 9 & 0x7f) + 1980; // 0-128, 1980-2108
22434
+
22435
+ var millisecond = 0;
22436
+ var second = (time & 0x1f) * 2; // 0-29, 0-58 (even numbers)
22437
+ var minute = time >> 5 & 0x3f; // 0-59
22438
+ var hour = time >> 11 & 0x1f; // 0-23
22439
+
22440
+ return new Date(year, month, day, hour, minute, second, millisecond);
22441
+ }
22442
+
22443
+ function validateFileName(fileName) {
22444
+ if (fileName.indexOf("\\") !== -1) {
22445
+ return "invalid characters in fileName: " + fileName;
22446
+ }
22447
+ if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) {
22448
+ return "absolute path: " + fileName;
22449
+ }
22450
+ if (fileName.split("/").indexOf("..") !== -1) {
22451
+ return "invalid relative path: " + fileName;
22452
+ }
22453
+ // all good
22454
+ return null;
22455
+ }
22456
+
22457
+ function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
22458
+ if (length === 0) {
22459
+ // fs.read will throw an out-of-bounds error if you try to read 0 bytes from a 0 byte file
22460
+ return setImmediate(function() { callback(null, newBuffer(0)); });
22461
+ }
22462
+ reader.read(buffer, offset, length, position, function(err, bytesRead) {
22463
+ if (err) return callback(err);
22464
+ if (bytesRead < length) {
22465
+ return callback(new Error("unexpected EOF"));
22466
+ }
22467
+ callback();
22468
+ });
22469
+ }
22470
+
22471
+ util.inherits(AssertByteCountStream, Transform);
22472
+ function AssertByteCountStream(byteCount) {
22473
+ Transform.call(this);
22474
+ this.actualByteCount = 0;
22475
+ this.expectedByteCount = byteCount;
22476
+ }
22477
+ AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
22478
+ this.actualByteCount += chunk.length;
22479
+ if (this.actualByteCount > this.expectedByteCount) {
22480
+ var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
22481
+ return cb(new Error(msg));
22482
+ }
22483
+ cb(null, chunk);
22484
+ };
22485
+ AssertByteCountStream.prototype._flush = function(cb) {
22486
+ if (this.actualByteCount < this.expectedByteCount) {
22487
+ var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
22488
+ return cb(new Error(msg));
22489
+ }
22490
+ cb();
22491
+ };
22492
+
22493
+ util.inherits(RandomAccessReader, EventEmitter);
22494
+ function RandomAccessReader() {
22495
+ EventEmitter.call(this);
22496
+ this.refCount = 0;
22497
+ }
22498
+ RandomAccessReader.prototype.ref = function() {
22499
+ this.refCount += 1;
22500
+ };
22501
+ RandomAccessReader.prototype.unref = function() {
22502
+ var self = this;
22503
+ self.refCount -= 1;
22504
+
22505
+ if (self.refCount > 0) return;
22506
+ if (self.refCount < 0) throw new Error("invalid unref");
22507
+
22508
+ self.close(onCloseDone);
22509
+
22510
+ function onCloseDone(err) {
22511
+ if (err) return self.emit('error', err);
22512
+ self.emit('close');
22513
+ }
22514
+ };
22515
+ RandomAccessReader.prototype.createReadStream = function(options) {
22516
+ var start = options.start;
22517
+ var end = options.end;
22518
+ if (start === end) {
22519
+ var emptyStream = new PassThrough();
22520
+ setImmediate(function() {
22521
+ emptyStream.end();
22522
+ });
22523
+ return emptyStream;
22524
+ }
22525
+ var stream = this._readStreamForRange(start, end);
22526
+
22527
+ var destroyed = false;
22528
+ var refUnrefFilter = new RefUnrefFilter(this);
22529
+ stream.on("error", function(err) {
22530
+ setImmediate(function() {
22531
+ if (!destroyed) refUnrefFilter.emit("error", err);
22532
+ });
22533
+ });
22534
+ refUnrefFilter.destroy = function() {
22535
+ stream.unpipe(refUnrefFilter);
22536
+ refUnrefFilter.unref();
22537
+ stream.destroy();
22538
+ };
22539
+
22540
+ var byteCounter = new AssertByteCountStream(end - start);
22541
+ refUnrefFilter.on("error", function(err) {
22542
+ setImmediate(function() {
22543
+ if (!destroyed) byteCounter.emit("error", err);
22544
+ });
22545
+ });
22546
+ byteCounter.destroy = function() {
22547
+ destroyed = true;
22548
+ refUnrefFilter.unpipe(byteCounter);
22549
+ refUnrefFilter.destroy();
22550
+ };
22551
+
22552
+ return stream.pipe(refUnrefFilter).pipe(byteCounter);
22553
+ };
22554
+ RandomAccessReader.prototype._readStreamForRange = function(start, end) {
22555
+ throw new Error("not implemented");
22556
+ };
22557
+ RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
22558
+ var readStream = this.createReadStream({start: position, end: position + length});
22559
+ var writeStream = new Writable();
22560
+ var written = 0;
22561
+ writeStream._write = function(chunk, encoding, cb) {
22562
+ chunk.copy(buffer, offset + written, 0, chunk.length);
22563
+ written += chunk.length;
22564
+ cb();
22565
+ };
22566
+ writeStream.on("finish", callback);
22567
+ readStream.on("error", function(error) {
22568
+ callback(error);
22569
+ });
22570
+ readStream.pipe(writeStream);
22571
+ };
22572
+ RandomAccessReader.prototype.close = function(callback) {
22573
+ setImmediate(callback);
22574
+ };
22575
+
22576
+ util.inherits(RefUnrefFilter, PassThrough);
22577
+ function RefUnrefFilter(context) {
22578
+ PassThrough.call(this);
22579
+ this.context = context;
22580
+ this.context.ref();
22581
+ this.unreffedYet = false;
22582
+ }
22583
+ RefUnrefFilter.prototype._flush = function(cb) {
22584
+ this.unref();
22585
+ cb();
22586
+ };
22587
+ RefUnrefFilter.prototype.unref = function(cb) {
22588
+ if (this.unreffedYet) return;
22589
+ this.unreffedYet = true;
22590
+ this.context.unref();
22591
+ };
22592
+
22593
+ var cp437 = '\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ';
22594
+ function decodeBuffer(buffer, start, end, isUtf8) {
22595
+ if (isUtf8) {
22596
+ return buffer.toString("utf8", start, end);
22597
+ } else {
22598
+ var result = "";
22599
+ for (var i = start; i < end; i++) {
22600
+ result += cp437[buffer[i]];
22601
+ }
22602
+ return result;
22603
+ }
22604
+ }
22605
+
22606
+ function readUInt64LE(buffer, offset) {
22607
+ // there is no native function for this, because we can't actually store 64-bit integers precisely.
22608
+ // after 53 bits, JavaScript's Number type (IEEE 754 double) can't store individual integers anymore.
22609
+ // but since 53 bits is a whole lot more than 32 bits, we do our best anyway.
22610
+ var lower32 = buffer.readUInt32LE(offset);
22611
+ var upper32 = buffer.readUInt32LE(offset + 4);
22612
+ // we can't use bitshifting here, because JavaScript bitshifting only works on 32-bit integers.
22613
+ return upper32 * 0x100000000 + lower32;
22614
+ // as long as we're bounds checking the result of this function against the total file size,
22615
+ // we'll catch any overflow errors, because we already made sure the total file size was within reason.
22616
+ }
22617
+
22618
+ // Node 10 deprecated new Buffer().
22619
+ var newBuffer;
22620
+ if (typeof Buffer.allocUnsafe === "function") {
22621
+ newBuffer = function(len) {
22622
+ return Buffer.allocUnsafe(len);
22623
+ };
22624
+ } else {
22625
+ newBuffer = function(len) {
22626
+ return new Buffer(len);
22627
+ };
22628
+ }
22629
+
22630
+ function defaultCallback(err) {
22631
+ if (err) throw err;
22632
+ }
22633
+
22634
+
22635
+ /***/ }),
22636
+
22637
+ /***/ 3097:
22638
+ /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
22639
+
22640
+ "use strict";
22641
+
22642
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22643
+ return (mod && mod.__esModule) ? mod : { "default": mod };
22644
+ };
22645
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
22646
+ exports.createGo = exports.getAnalyzedEntrypoint = exports.OUT_EXTENSION = exports.goGlobalCachePath = exports.cacheDir = void 0;
22647
+ const tar_1 = __importDefault(__webpack_require__(6758));
22648
+ const execa_1 = __importDefault(__webpack_require__(389));
22649
+ const node_fetch_1 = __importDefault(__webpack_require__(779));
22650
+ const fs_extra_1 = __webpack_require__(7692);
22651
+ const path_1 = __webpack_require__(5622);
22652
+ const string_argv_1 = __importDefault(__webpack_require__(2534));
22653
+ const build_utils_1 = __webpack_require__(3445);
22654
+ const stream_1 = __webpack_require__(2413);
22655
+ const util_1 = __webpack_require__(1669);
22656
+ const os_1 = __webpack_require__(2087);
22657
+ const yauzl_promise_1 = __importDefault(__webpack_require__(7542));
22658
+ const xdg_app_paths_1 = __importDefault(__webpack_require__(4925));
22659
+ const streamPipeline = util_1.promisify(stream_1.pipeline);
22660
+ const versionMap = new Map([
22661
+ ['1.20', '1.20.1'],
22662
+ ['1.19', '1.19.6'],
22663
+ ['1.18', '1.18.10'],
22664
+ ['1.17', '1.17.13'],
22665
+ ['1.16', '1.16.15'],
22666
+ ['1.15', '1.15.15'],
22667
+ ['1.14', '1.14.15'],
22668
+ ['1.13', '1.13.15'],
22669
+ ]);
22670
+ const archMap = new Map([
22671
+ ['x64', 'amd64'],
22672
+ ['x86', '386'],
22673
+ ]);
22674
+ const platformMap = new Map([['win32', 'windows']]);
22675
+ exports.cacheDir = path_1.join('.vercel', 'cache', 'golang');
22676
+ const GO_FLAGS = process.platform === 'win32' ? [] : ['-ldflags', '-s -w'];
22677
+ const GO_MIN_VERSION = 13;
22678
+ const getPlatform = (p) => platformMap.get(p) || p;
22679
+ const getArch = (a) => archMap.get(a) || a;
22680
+ function getGoUrl(version) {
22681
+ const { arch, platform } = process;
22682
+ const goArch = getArch(arch);
22683
+ const goPlatform = getPlatform(platform);
22684
+ const ext = platform === 'win32' ? 'zip' : 'tar.gz';
22685
+ const filename = `go${version}.${goPlatform}-${goArch}.${ext}`;
22686
+ return {
22687
+ filename,
22688
+ url: `https://dl.google.com/go/${filename}`,
22689
+ };
22690
+ }
22691
+ exports.goGlobalCachePath = path_1.join(xdg_app_paths_1.default('com.vercel.cli').cache(), 'golang');
22692
+ exports.OUT_EXTENSION = process.platform === 'win32' ? '.exe' : '';
22693
+ async function getAnalyzedEntrypoint(workPath, filePath, modulePath) {
22694
+ const bin = path_1.join(__dirname, `analyze${exports.OUT_EXTENSION}`);
22695
+ const isAnalyzeExist = await fs_extra_1.pathExists(bin);
22696
+ if (!isAnalyzeExist) {
22697
+ build_utils_1.debug(`Building analyze bin: ${bin}`);
22698
+ const src = __webpack_require__.ab + "analyze.go";
22699
+ const go = await createGo({
22700
+ modulePath,
22701
+ workPath,
22702
+ });
22703
+ await go.build(__webpack_require__.ab + "analyze.go", bin);
22704
+ }
22705
+ build_utils_1.debug(`Analyzing entrypoint ${filePath} with modulePath ${modulePath}`);
22706
+ const args = [`-modpath=${modulePath}`, filePath];
22707
+ const analyzed = await execa_1.default.stdout(bin, args);
22708
+ build_utils_1.debug(`Analyzed entrypoint ${analyzed}`);
20138
22709
  return analyzed;
20139
22710
  }
20140
22711
  exports.getAnalyzedEntrypoint = getAnalyzedEntrypoint;
20141
- // Creates a `$GOPATH` directory tree, as per `go help gopath` instructions.
20142
- // Without this, `go` won't recognize the `$GOPATH`.
20143
- function createGoPathTree(goPath, platform, arch) {
20144
- const tuple = `${getPlatform(platform)}_${getArch(arch)}`;
20145
- build_utils_1.debug('Creating GOPATH directory structure for %o (%s)', goPath, tuple);
20146
- return Promise.all([
20147
- fs_extra_1.mkdirp(path_1.join(goPath, 'bin')),
20148
- fs_extra_1.mkdirp(path_1.join(goPath, 'pkg', tuple)),
20149
- ]);
20150
- }
20151
22712
  class GoWrapper {
20152
22713
  constructor(env, opts = {}) {
20153
22714
  if (!opts.cwd) {
@@ -20158,8 +22719,10 @@ class GoWrapper {
20158
22719
  }
20159
22720
  execute(...args) {
20160
22721
  const { opts, env } = this;
20161
- build_utils_1.debug('Exec %o', `go ${args.join(' ')}`);
20162
- return execa_1.default('go', args, { stdio: 'pipe', ...opts, env });
22722
+ build_utils_1.debug(`Exec: go ${args
22723
+ .map(a => (a.includes(' ') ? `"${a}"` : a))
22724
+ .join(' ')} CWD=${opts.cwd}`);
22725
+ return execa_1.default('go', args, { stdio: 'inherit', ...opts, env });
20163
22726
  }
20164
22727
  mod() {
20165
22728
  return this.execute('mod', 'tidy');
@@ -20167,16 +22730,16 @@ class GoWrapper {
20167
22730
  get(src) {
20168
22731
  const args = ['get'];
20169
22732
  if (src) {
20170
- build_utils_1.debug('Fetching `go` dependencies for file %o', src);
22733
+ build_utils_1.debug(`Fetching 'go' dependencies for file ${src}`);
20171
22734
  args.push(src);
20172
22735
  }
20173
22736
  else {
20174
- build_utils_1.debug('Fetching `go` dependencies for cwd %o', this.opts.cwd);
22737
+ build_utils_1.debug(`Fetching 'go' dependencies for cwd ${this.opts.cwd}`);
20175
22738
  }
20176
22739
  return this.execute(...args);
20177
22740
  }
20178
22741
  build(src, dest) {
20179
- build_utils_1.debug('Building optimized `go` binary %o -> %o', src, dest);
22742
+ build_utils_1.debug(`Building optimized 'go' binary ${src} -> ${dest}`);
20180
22743
  const sources = Array.isArray(src) ? src : [src];
20181
22744
  const flags = process.env.GO_BUILD_FLAGS
20182
22745
  ? string_argv_1.default(process.env.GO_BUILD_FLAGS)
@@ -20184,59 +22747,184 @@ class GoWrapper {
20184
22747
  return this.execute('build', ...flags, '-o', dest, ...sources);
20185
22748
  }
20186
22749
  }
20187
- async function createGo(workPath, goPath, platform = process.platform, arch = process.arch, opts = {}, goMod = false) {
20188
- const binPath = path_1.join(getGoDir(workPath), 'bin');
20189
- build_utils_1.debug(`Adding ${binPath} to PATH`);
20190
- const path = `${binPath}${path_1.delimiter}${process.env.PATH}`;
20191
- const env = {
20192
- ...process.env,
20193
- PATH: path,
20194
- GOPATH: goPath,
20195
- ...opts.env,
20196
- };
20197
- if (goMod) {
22750
+ /**
22751
+ * Initializes a `GoWrapper` instance.
22752
+ *
22753
+ * This function determines the Go version to use by first looking in the
22754
+ * `go.mod`, if exists, otherwise uses the latest version from the version
22755
+ * map.
22756
+ *
22757
+ * Next it will attempt to find the desired Go version by checking the
22758
+ * following locations:
22759
+ * 1. The "local" project cache directory (e.g. `.vercel/cache/golang`)
22760
+ * 2. The "global" cache directory (e.g. `~/.cache/com.vercel.com/golang`)
22761
+ * 3. The system PATH
22762
+ *
22763
+ * If the Go version is not found, it's downloaded and installed in the
22764
+ * global cache directory so it can be shared across projects. When using
22765
+ * Linux or macOS, it creates a symlink from the global cache to the local
22766
+ * cache directory so that `prepareCache` will persist it.
22767
+ *
22768
+ * @param modulePath The path possibly containing a `go.mod` file
22769
+ * @param opts `execa` options (`cwd`, `env`, `stdio`, etc)
22770
+ * @param workPath The path to the project to be built
22771
+ * @returns An initialized `GoWrapper` instance
22772
+ */
22773
+ async function createGo({ modulePath, opts = {}, workPath, }) {
22774
+ // parse the `go.mod`, if exists
22775
+ let goPreferredVersion;
22776
+ if (modulePath) {
22777
+ goPreferredVersion = await parseGoModVersion(modulePath);
22778
+ }
22779
+ // default to newest (first) supported go version
22780
+ const goSelectedVersion = goPreferredVersion || Array.from(versionMap.values())[0];
22781
+ const env = build_utils_1.cloneEnv(process.env, opts.env);
22782
+ const { PATH } = env;
22783
+ const { platform } = process;
22784
+ const goGlobalCacheDir = path_1.join(exports.goGlobalCachePath, `${goSelectedVersion}_${platform}_${process.arch}`);
22785
+ const goCacheDir = path_1.join(workPath, exports.cacheDir);
22786
+ if (goPreferredVersion) {
22787
+ build_utils_1.debug(`Preferred go version ${goPreferredVersion} (from go.mod)`);
20198
22788
  env.GO111MODULE = 'on';
20199
22789
  }
20200
- await createGoPathTree(goPath, platform, arch);
22790
+ else {
22791
+ build_utils_1.debug(`Preferred go version ${goSelectedVersion} (latest from version map)`);
22792
+ }
22793
+ const setGoEnv = async (goDir) => {
22794
+ if (platform !== 'win32' && goDir === goGlobalCacheDir) {
22795
+ build_utils_1.debug(`Symlinking ${goDir} -> ${goCacheDir}`);
22796
+ await fs_extra_1.remove(goCacheDir);
22797
+ await fs_extra_1.mkdirp(path_1.dirname(goCacheDir));
22798
+ await fs_extra_1.symlink(goDir, goCacheDir);
22799
+ goDir = goCacheDir;
22800
+ }
22801
+ env.GOROOT = goDir || undefined;
22802
+ env.PATH = goDir ? `${path_1.join(goDir, 'bin')}${path_1.delimiter}${PATH}` : PATH;
22803
+ };
22804
+ // try each of these Go directories looking for the version we need
22805
+ const goDirs = {
22806
+ 'local cache': goCacheDir,
22807
+ 'global cache': goGlobalCacheDir,
22808
+ 'system PATH': null,
22809
+ };
22810
+ for (const [label, goDir] of Object.entries(goDirs)) {
22811
+ try {
22812
+ const goBinDir = goDir && path_1.join(goDir, 'bin');
22813
+ if (goBinDir && !(await fs_extra_1.pathExists(goBinDir))) {
22814
+ build_utils_1.debug(`Go not found in ${label}`);
22815
+ continue;
22816
+ }
22817
+ env.GOROOT = goDir || undefined;
22818
+ env.PATH = goBinDir || PATH;
22819
+ const { stdout } = await execa_1.default('go', ['version'], { env });
22820
+ const { minor, short, version } = parseGoVersionString(stdout);
22821
+ if (minor < GO_MIN_VERSION) {
22822
+ build_utils_1.debug(`Found go ${version} in ${label}, but version is unsupported`);
22823
+ }
22824
+ if (version === goSelectedVersion || short === goSelectedVersion) {
22825
+ console.log(`Selected go ${version} (from ${label})`);
22826
+ await setGoEnv(goDir);
22827
+ return new GoWrapper(env, opts);
22828
+ }
22829
+ else {
22830
+ build_utils_1.debug(`Found go ${version} in ${label}, but need ${goSelectedVersion}`);
22831
+ }
22832
+ }
22833
+ catch {
22834
+ build_utils_1.debug(`Go not found in ${label}`);
22835
+ }
22836
+ }
22837
+ // we need to download and cache the desired `go` version
22838
+ await download({
22839
+ dest: goGlobalCacheDir,
22840
+ version: goSelectedVersion,
22841
+ });
22842
+ await setGoEnv(goGlobalCacheDir);
20201
22843
  return new GoWrapper(env, opts);
20202
22844
  }
20203
22845
  exports.createGo = createGo;
20204
- async function downloadGo(workPath, modulePath) {
20205
- const dir = getGoDir(workPath);
20206
- const { platform, arch } = process;
20207
- const version = await parseGoVersion(modulePath);
20208
- // Check if `go` is already installed in user's `$PATH`
20209
- const { failed, stdout } = await execa_1.default('go', ['version'], { reject: false });
20210
- if (!failed && parseInt(stdout.split('.')[1]) >= GO_MIN_VERSION) {
20211
- build_utils_1.debug('Using system installed version of `go`: %o', stdout.trim());
20212
- return createGo(workPath, dir, platform, arch);
20213
- }
20214
- // Check `go` bin in cacheDir
20215
- const isGoExist = await fs_extra_1.pathExists(path_1.join(dir, 'bin'));
20216
- if (!isGoExist) {
20217
- build_utils_1.debug('Installing `go` v%s to %o for %s %s', version, dir, platform, arch);
20218
- const url = getGoUrl(version, platform, arch);
20219
- build_utils_1.debug('Downloading `go` URL: %o', url);
20220
- const res = await node_fetch_1.default(url);
20221
- if (!res.ok) {
20222
- throw new Error(`Failed to download: ${url} (${res.status})`);
22846
+ /**
22847
+ * Download and installs the Go distribution.
22848
+ *
22849
+ * @param dest The directory to install Go into. If directory exists, it is
22850
+ * first deleted before installing.
22851
+ * @param version The Go version to download
22852
+ */
22853
+ async function download({ dest, version }) {
22854
+ const { filename, url } = getGoUrl(version);
22855
+ console.log(`Downloading go: ${url}`);
22856
+ const res = await node_fetch_1.default(url);
22857
+ if (!res.ok) {
22858
+ throw new Error(`Failed to download: ${url} (${res.status})`);
22859
+ }
22860
+ build_utils_1.debug(`Installing go ${version} to ${dest}`);
22861
+ await fs_extra_1.remove(dest);
22862
+ await fs_extra_1.mkdirp(dest);
22863
+ if (/\.zip$/.test(filename)) {
22864
+ const zipFile = path_1.join(os_1.tmpdir(), filename);
22865
+ try {
22866
+ await streamPipeline(res.body, fs_extra_1.createWriteStream(zipFile));
22867
+ const zip = await yauzl_promise_1.default.open(zipFile);
22868
+ let entry = await zip.readEntry();
22869
+ while (entry) {
22870
+ const fileName = entry.fileName.split('/').slice(1).join('/');
22871
+ if (fileName) {
22872
+ const destPath = path_1.join(dest, fileName);
22873
+ if (/\/$/.test(fileName)) {
22874
+ await fs_extra_1.mkdirp(destPath);
22875
+ }
22876
+ else {
22877
+ const [entryStream] = await Promise.all([
22878
+ entry.openReadStream(),
22879
+ fs_extra_1.mkdirp(path_1.dirname(destPath)),
22880
+ ]);
22881
+ const out = fs_extra_1.createWriteStream(destPath);
22882
+ await streamPipeline(entryStream, out);
22883
+ }
22884
+ }
22885
+ entry = await zip.readEntry();
22886
+ }
20223
22887
  }
20224
- // TODO: use a zip extractor when `ext === "zip"`
20225
- await fs_extra_1.mkdirp(dir);
20226
- await new Promise((resolve, reject) => {
20227
- res.body
20228
- .on('error', reject)
20229
- .pipe(tar_1.default.extract({ cwd: dir, strip: 1 }))
20230
- .on('error', reject)
20231
- .on('finish', resolve);
20232
- });
22888
+ finally {
22889
+ await fs_extra_1.remove(zipFile);
22890
+ }
22891
+ return;
20233
22892
  }
20234
- return createGo(workPath, dir, platform, arch);
22893
+ await new Promise((resolve, reject) => {
22894
+ res.body
22895
+ .on('error', reject)
22896
+ .pipe(tar_1.default.extract({ cwd: dest, strip: 1 }))
22897
+ .on('error', reject)
22898
+ .on('finish', resolve);
22899
+ });
22900
+ }
22901
+ const goVersionRegExp = /(\d+)\.(\d+)(?:\.(\d+))?/;
22902
+ /**
22903
+ * Parses the raw output from `go version` and returns the version parts.
22904
+ *
22905
+ * @param goVersionOutput The output from `go version`
22906
+ */
22907
+ function parseGoVersionString(goVersionOutput) {
22908
+ const matches = goVersionOutput.match(goVersionRegExp) || [];
22909
+ const major = parseInt(matches[1], 10);
22910
+ const minor = parseInt(matches[2], 10);
22911
+ const patch = parseInt(matches[3] || '0', 10);
22912
+ return {
22913
+ version: `${major}.${minor}.${patch}`,
22914
+ short: `${major}.${minor}`,
22915
+ major,
22916
+ minor,
22917
+ patch,
22918
+ };
20235
22919
  }
20236
- exports.downloadGo = downloadGo;
20237
- async function parseGoVersion(modulePath) {
20238
- // default to newest (first)
20239
- let version = Array.from(versionMap.values())[0];
22920
+ /**
22921
+ * Attempts to parse the preferred Go version from the `go.mod` file.
22922
+ *
22923
+ * @param modulePath The directory containing the `go.mod` file
22924
+ * @returns
22925
+ */
22926
+ async function parseGoModVersion(modulePath) {
22927
+ let version;
20240
22928
  const file = path_1.join(modulePath, 'go.mod');
20241
22929
  try {
20242
22930
  const content = await fs_extra_1.readFile(file, 'utf8');
@@ -20259,7 +22947,6 @@ async function parseGoVersion(modulePath) {
20259
22947
  throw err;
20260
22948
  }
20261
22949
  }
20262
- build_utils_1.debug(`Selected Go version ${version}`);
20263
22950
  return version;
20264
22951
  }
20265
22952
 
@@ -20354,7 +23041,7 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20354
23041
  entrypoint = renamedEntrypoint;
20355
23042
  }
20356
23043
  const entrypointAbsolute = path_1.join(workPath, entrypoint);
20357
- const entrypointArr = entrypoint.split(path_1.sep);
23044
+ const entrypointArr = entrypoint.split(path_1.posix.sep);
20358
23045
  build_utils_1.debug(`Parsing AST for "${entrypoint}"`);
20359
23046
  let analyzed;
20360
23047
  try {
@@ -20365,14 +23052,14 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20365
23052
  analyzed = await go_helpers_1.getAnalyzedEntrypoint(workPath, entrypointAbsolute, path_1.dirname(goModAbsPath));
20366
23053
  }
20367
23054
  catch (err) {
20368
- console.log(`Failed to parse AST for "${entrypoint}"`);
23055
+ console.error(`Failed to parse AST for "${entrypoint}"`);
20369
23056
  throw err;
20370
23057
  }
20371
23058
  if (!analyzed) {
20372
23059
  const err = new Error(`Could not find an exported function in "${entrypoint}"
20373
23060
  Learn more: https://vercel.com/docs/runtimes#official-runtimes/go
20374
23061
  `);
20375
- console.log(err.message);
23062
+ console.error(err.message);
20376
23063
  throw err;
20377
23064
  }
20378
23065
  const parsedAnalyzed = JSON.parse(analyzed);
@@ -20464,11 +23151,18 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20464
23151
  // in order to allow the user to have `main.go`,
20465
23152
  // we need our `main.go` to be called something else
20466
23153
  const mainGoFileName = 'main__vc__go__.go';
20467
- if (packageName !== 'main') {
20468
- const go = await go_helpers_1.createGo(workPath, goPath, process.platform, process.arch, {
23154
+ const go = await go_helpers_1.createGo({
23155
+ modulePath: goModPath,
23156
+ opts: {
20469
23157
  cwd: entrypointDirname,
20470
- stdio: 'inherit',
20471
- }, true);
23158
+ env: {
23159
+ GOARCH: 'amd64',
23160
+ GOOS: 'linux',
23161
+ },
23162
+ },
23163
+ workPath,
23164
+ });
23165
+ if (packageName !== 'main') {
20472
23166
  if (!isGoModExist) {
20473
23167
  try {
20474
23168
  const defaultGoModContent = `module ${packageName}`;
@@ -20484,7 +23178,7 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20484
23178
  });
20485
23179
  }
20486
23180
  catch (err) {
20487
- console.log(`Failed to create default go.mod for ${packageName}`);
23181
+ console.error(`Failed to create default go.mod for ${packageName}`);
20488
23182
  throw err;
20489
23183
  }
20490
23184
  }
@@ -20549,7 +23243,7 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20549
23243
  }
20550
23244
  }
20551
23245
  catch (err) {
20552
- console.log('Failed to move entry to package folder');
23246
+ console.error('Failed to move entry to package folder');
20553
23247
  throw err;
20554
23248
  }
20555
23249
  let baseGoModPath = '';
@@ -20568,7 +23262,7 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20568
23262
  await go.mod();
20569
23263
  }
20570
23264
  catch (err) {
20571
- console.log('failed to `go mod tidy`');
23265
+ console.error('failed to `go mod tidy`');
20572
23266
  throw err;
20573
23267
  }
20574
23268
  build_utils_1.debug('Running `go build`...');
@@ -20578,7 +23272,7 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20578
23272
  await go.build(src, destPath);
20579
23273
  }
20580
23274
  catch (err) {
20581
- console.log('failed to `go build`');
23275
+ console.error('failed to `go build`');
20582
23276
  throw err;
20583
23277
  }
20584
23278
  }
@@ -20586,9 +23280,6 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20586
23280
  // legacy mode
20587
23281
  // we need `main.go` in the same dir as the entrypoint,
20588
23282
  // otherwise `go build` will refuse to build
20589
- const go = await go_helpers_1.createGo(workPath, goPath, process.platform, process.arch, {
20590
- cwd: entrypointDirname,
20591
- }, false);
20592
23283
  const originalMainGoContents = await fs_extra_1.readFile(__webpack_require__.ab + "main.go", 'utf8');
20593
23284
  const mainGoContents = originalMainGoContents
20594
23285
  .replace('"__VC_HANDLER_PACKAGE_NAME"', '')
@@ -20607,7 +23298,7 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20607
23298
  await go.get();
20608
23299
  }
20609
23300
  catch (err) {
20610
- console.log('Failed to `go get`');
23301
+ console.error('Failed to `go get`');
20611
23302
  throw err;
20612
23303
  }
20613
23304
  build_utils_1.debug('Running `go build`...');
@@ -20620,7 +23311,7 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20620
23311
  await go.build(src, destPath);
20621
23312
  }
20622
23313
  catch (err) {
20623
- console.log('failed to `go build`');
23314
+ console.error('failed to `go build`');
20624
23315
  throw err;
20625
23316
  }
20626
23317
  }
@@ -20644,7 +23335,9 @@ async function build({ files, entrypoint, config, workPath, meta = {}, }) {
20644
23335
  await cleanupFileSystem(undoFileActions, undoDirectoryCreation, undoFunctionRenames);
20645
23336
  }
20646
23337
  catch (error) {
20647
- console.log(`Build cleanup failed: ${error.message}`);
23338
+ if (error instanceof Error) {
23339
+ console.error(`Build cleanup failed: ${error.message}`);
23340
+ }
20648
23341
  build_utils_1.debug('Cleanup Error: ' + error);
20649
23342
  }
20650
23343
  }
@@ -20734,6 +23427,10 @@ async function copyDevServer(functionName, dest) {
20734
23427
  const patched = data.replace('__HANDLER_FUNC_NAME', functionName);
20735
23428
  await fs_extra_1.writeFile(path_1.join(dest, 'vercel-dev-server-main.go'), patched);
20736
23429
  }
23430
+ async function writeDefaultGoMod(entrypointDirname, packageName) {
23431
+ const defaultGoModContent = `module ${packageName}`;
23432
+ await fs_extra_1.writeFile(path_1.join(entrypointDirname, 'go.mod'), defaultGoModContent, 'utf-8');
23433
+ }
20737
23434
  async function startDevServer(opts) {
20738
23435
  const { entrypoint, workPath, meta = {} } = opts;
20739
23436
  const { devCacheDir = path_1.join(workPath, '.vercel', 'cache') } = meta;
@@ -20760,18 +23457,27 @@ Learn more: https://vercel.com/docs/runtimes#official-runtimes/go`);
20760
23457
  await Promise.all([
20761
23458
  copyEntrypoint(entrypointWithExt, tmpPackage),
20762
23459
  copyDevServer(analyzed.functionName, tmpPackage),
23460
+ goModAbsPathDir ? null : writeDefaultGoMod(tmp, analyzed.packageName),
20763
23461
  ]);
20764
23462
  const portFile = path_1.join(TMP, `vercel-dev-port-${Math.random().toString(32).substring(2)}`);
20765
23463
  const env = build_utils_1.cloneEnv(process.env, meta.env, {
20766
23464
  VERCEL_DEV_PORT_FILE: portFile,
20767
23465
  });
20768
23466
  const executable = `./vercel-dev-server-go${process.platform === 'win32' ? '.exe' : ''}`;
20769
- build_utils_1.debug(`SPAWNING go build -o ${executable} ./... CWD=${tmp}`);
20770
- child_process_1.execFileSync('go', ['build', '-o', executable, './...'], {
20771
- cwd: tmp,
20772
- env,
20773
- stdio: 'inherit',
23467
+ // Note: We must run `go build`, then manually spawn the dev server instead
23468
+ // of spawning `go run`. See https://github.com/vercel/vercel/pull/8718 for
23469
+ // more info.
23470
+ // build the dev server
23471
+ const go = await go_helpers_1.createGo({
23472
+ modulePath: goModAbsPathDir,
23473
+ opts: {
23474
+ cwd: tmp,
23475
+ env,
23476
+ },
23477
+ workPath,
20774
23478
  });
23479
+ await go.build('./...', executable);
23480
+ // run the dev server
20775
23481
  build_utils_1.debug(`SPAWNING ${executable} CWD=${tmp}`);
20776
23482
  const child = child_process_1.spawn(executable, [], {
20777
23483
  cwd: tmp,
@@ -20833,7 +23539,7 @@ async function waitForPortFile_(opts) {
20833
23539
  try {
20834
23540
  const port = Number(await fs_extra_1.readFile(opts.portFile, 'ascii'));
20835
23541
  async_retry_1.default(() => fs_extra_1.remove(opts.portFile)).catch((err) => {
20836
- console.error('Could not delete port file: %j: %s', opts.portFile, err);
23542
+ console.error(`Could not delete port file: ${opts.portFile}: ${err}`);
20837
23543
  });
20838
23544
  return { port };
20839
23545
  }
@@ -20845,6 +23551,24 @@ async function waitForPortFile_(opts) {
20845
23551
  }
20846
23552
  }
20847
23553
  async function prepareCache({ workPath, }) {
23554
+ // When building the project for the first time, there won't be a cache and
23555
+ // `createGo()` will have downloaded Go to the global cache directory, then
23556
+ // symlinked it to the local `cacheDir`.
23557
+ //
23558
+ // If we detect the `cacheDir` is a symlink, unlink it, then move the global
23559
+ // cache directory into the local cache directory so that it can be
23560
+ // persisted.
23561
+ //
23562
+ // On the next build, the local cache will be restored and `createGo()` will
23563
+ // use it unless the preferred Go version changed in the `go.mod`.
23564
+ const goCacheDir = path_1.join(workPath, go_helpers_1.cacheDir);
23565
+ const stat = await fs_extra_1.lstat(goCacheDir);
23566
+ if (stat.isSymbolicLink()) {
23567
+ const goGlobalCacheDir = await fs_extra_1.readlink(goCacheDir);
23568
+ build_utils_1.debug(`Preparing cache by moving ${goGlobalCacheDir} -> ${goCacheDir}`);
23569
+ await fs_extra_1.unlink(goCacheDir);
23570
+ await fs_extra_1.move(goGlobalCacheDir, goCacheDir);
23571
+ }
20848
23572
  const cache = await build_utils_1.glob(`${go_helpers_1.cacheDir}/**`, workPath);
20849
23573
  return cache;
20850
23574
  }