@glowlabs-org/utils 0.1.5 → 0.2.1

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.
package/dist/cjs/index.js CHANGED
@@ -7,7 +7,7 @@ var require$$3 = require('http');
7
7
  var require$$4 = require('https');
8
8
  var require$$0$1 = require('url');
9
9
  var require$$6 = require('fs');
10
- var crypto = require('crypto');
10
+ var require$$8 = require('crypto');
11
11
  var require$$4$1 = require('assert');
12
12
  var zlib = require('zlib');
13
13
  var events$1 = require('events');
@@ -18,7 +18,7 @@ var Decimal = require('decimal.js');
18
18
 
19
19
  const GENESIS_TIMESTAMP = 1700352000;
20
20
 
21
- function bind$1(fn, thisArg) {
21
+ function bind$2(fn, thisArg) {
22
22
  return function wrap() {
23
23
  return fn.apply(thisArg, arguments);
24
24
  };
@@ -158,6 +158,27 @@ const isPlainObject = (val) => {
158
158
  return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag$1 in val) && !(iterator in val);
159
159
  };
160
160
 
161
+ /**
162
+ * Determine if a value is an empty object (safely handles Buffers)
163
+ *
164
+ * @param {*} val The value to test
165
+ *
166
+ * @returns {boolean} True if value is an empty object, otherwise false
167
+ */
168
+ const isEmptyObject = (val) => {
169
+ // Early return for non-objects or Buffers to prevent RangeError
170
+ if (!isObject(val) || isBuffer$1(val)) {
171
+ return false;
172
+ }
173
+
174
+ try {
175
+ return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
176
+ } catch (e) {
177
+ // Fallback for any other objects that might cause RangeError with Object.keys()
178
+ return false;
179
+ }
180
+ };
181
+
161
182
  /**
162
183
  * Determine if a value is a Date
163
184
  *
@@ -280,6 +301,11 @@ function forEach(obj, fn, {allOwnKeys = false} = {}) {
280
301
  fn.call(null, obj[i], i, obj);
281
302
  }
282
303
  } else {
304
+ // Buffer check
305
+ if (isBuffer$1(obj)) {
306
+ return;
307
+ }
308
+
283
309
  // Iterate over object keys
284
310
  const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
285
311
  const len = keys.length;
@@ -293,6 +319,10 @@ function forEach(obj, fn, {allOwnKeys = false} = {}) {
293
319
  }
294
320
 
295
321
  function findKey(obj, key) {
322
+ if (isBuffer$1(obj)){
323
+ return null;
324
+ }
325
+
296
326
  key = key.toLowerCase();
297
327
  const keys = Object.keys(obj);
298
328
  let i = keys.length;
@@ -367,7 +397,7 @@ function merge(/* obj1, obj2, obj3, ... */) {
367
397
  const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
368
398
  forEach(b, (val, key) => {
369
399
  if (thisArg && isFunction$1(val)) {
370
- a[key] = bind$1(val, thisArg);
400
+ a[key] = bind$2(val, thisArg);
371
401
  } else {
372
402
  a[key] = val;
373
403
  }
@@ -646,6 +676,11 @@ const toJSONObject = (obj) => {
646
676
  return;
647
677
  }
648
678
 
679
+ //Buffer check
680
+ if (isBuffer$1(source)) {
681
+ return source;
682
+ }
683
+
649
684
  if(!('toJSON' in source)) {
650
685
  stack[i] = source;
651
686
  const target = isArray(source) ? [] : {};
@@ -717,6 +752,7 @@ var utils$1 = {
717
752
  isBoolean,
718
753
  isObject,
719
754
  isPlainObject,
755
+ isEmptyObject,
720
756
  isReadableStream,
721
757
  isRequest,
722
758
  isResponse,
@@ -12517,7 +12553,7 @@ var abs$1 = Math.abs;
12517
12553
  var floor$1 = Math.floor;
12518
12554
 
12519
12555
  /** @type {import('./max')} */
12520
- var max$1 = Math.max;
12556
+ var max$2 = Math.max;
12521
12557
 
12522
12558
  /** @type {import('./min')} */
12523
12559
  var min$1 = Math.min;
@@ -12674,110 +12710,92 @@ function requireObject_getPrototypeOf () {
12674
12710
  return Object_getPrototypeOf;
12675
12711
  }
12676
12712
 
12677
- var implementation;
12678
- var hasRequiredImplementation;
12679
-
12680
- function requireImplementation () {
12681
- if (hasRequiredImplementation) return implementation;
12682
- hasRequiredImplementation = 1;
12683
-
12684
- /* eslint no-invalid-this: 1 */
12685
-
12686
- var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
12687
- var toStr = Object.prototype.toString;
12688
- var max = Math.max;
12689
- var funcType = '[object Function]';
12690
-
12691
- var concatty = function concatty(a, b) {
12692
- var arr = [];
12713
+ /* eslint no-invalid-this: 1 */
12693
12714
 
12694
- for (var i = 0; i < a.length; i += 1) {
12695
- arr[i] = a[i];
12696
- }
12697
- for (var j = 0; j < b.length; j += 1) {
12698
- arr[j + a.length] = b[j];
12699
- }
12715
+ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
12716
+ var toStr = Object.prototype.toString;
12717
+ var max$1 = Math.max;
12718
+ var funcType = '[object Function]';
12700
12719
 
12701
- return arr;
12702
- };
12720
+ var concatty = function concatty(a, b) {
12721
+ var arr = [];
12703
12722
 
12704
- var slicy = function slicy(arrLike, offset) {
12705
- var arr = [];
12706
- for (var i = offset, j = 0; i < arrLike.length; i += 1, j += 1) {
12707
- arr[j] = arrLike[i];
12708
- }
12709
- return arr;
12710
- };
12723
+ for (var i = 0; i < a.length; i += 1) {
12724
+ arr[i] = a[i];
12725
+ }
12726
+ for (var j = 0; j < b.length; j += 1) {
12727
+ arr[j + a.length] = b[j];
12728
+ }
12711
12729
 
12712
- var joiny = function (arr, joiner) {
12713
- var str = '';
12714
- for (var i = 0; i < arr.length; i += 1) {
12715
- str += arr[i];
12716
- if (i + 1 < arr.length) {
12717
- str += joiner;
12718
- }
12719
- }
12720
- return str;
12721
- };
12730
+ return arr;
12731
+ };
12722
12732
 
12723
- implementation = function bind(that) {
12724
- var target = this;
12725
- if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
12726
- throw new TypeError(ERROR_MESSAGE + target);
12727
- }
12728
- var args = slicy(arguments, 1);
12729
-
12730
- var bound;
12731
- var binder = function () {
12732
- if (this instanceof bound) {
12733
- var result = target.apply(
12734
- this,
12735
- concatty(args, arguments)
12736
- );
12737
- if (Object(result) === result) {
12738
- return result;
12739
- }
12740
- return this;
12741
- }
12742
- return target.apply(
12743
- that,
12744
- concatty(args, arguments)
12745
- );
12733
+ var slicy = function slicy(arrLike, offset) {
12734
+ var arr = [];
12735
+ for (var i = offset, j = 0; i < arrLike.length; i += 1, j += 1) {
12736
+ arr[j] = arrLike[i];
12737
+ }
12738
+ return arr;
12739
+ };
12746
12740
 
12747
- };
12741
+ var joiny = function (arr, joiner) {
12742
+ var str = '';
12743
+ for (var i = 0; i < arr.length; i += 1) {
12744
+ str += arr[i];
12745
+ if (i + 1 < arr.length) {
12746
+ str += joiner;
12747
+ }
12748
+ }
12749
+ return str;
12750
+ };
12748
12751
 
12749
- var boundLength = max(0, target.length - args.length);
12750
- var boundArgs = [];
12751
- for (var i = 0; i < boundLength; i++) {
12752
- boundArgs[i] = '$' + i;
12753
- }
12752
+ var implementation$1 = function bind(that) {
12753
+ var target = this;
12754
+ if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
12755
+ throw new TypeError(ERROR_MESSAGE + target);
12756
+ }
12757
+ var args = slicy(arguments, 1);
12758
+
12759
+ var bound;
12760
+ var binder = function () {
12761
+ if (this instanceof bound) {
12762
+ var result = target.apply(
12763
+ this,
12764
+ concatty(args, arguments)
12765
+ );
12766
+ if (Object(result) === result) {
12767
+ return result;
12768
+ }
12769
+ return this;
12770
+ }
12771
+ return target.apply(
12772
+ that,
12773
+ concatty(args, arguments)
12774
+ );
12754
12775
 
12755
- bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
12776
+ };
12756
12777
 
12757
- if (target.prototype) {
12758
- var Empty = function Empty() {};
12759
- Empty.prototype = target.prototype;
12760
- bound.prototype = new Empty();
12761
- Empty.prototype = null;
12762
- }
12778
+ var boundLength = max$1(0, target.length - args.length);
12779
+ var boundArgs = [];
12780
+ for (var i = 0; i < boundLength; i++) {
12781
+ boundArgs[i] = '$' + i;
12782
+ }
12763
12783
 
12764
- return bound;
12765
- };
12766
- return implementation;
12767
- }
12784
+ bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
12768
12785
 
12769
- var functionBind;
12770
- var hasRequiredFunctionBind;
12786
+ if (target.prototype) {
12787
+ var Empty = function Empty() {};
12788
+ Empty.prototype = target.prototype;
12789
+ bound.prototype = new Empty();
12790
+ Empty.prototype = null;
12791
+ }
12771
12792
 
12772
- function requireFunctionBind () {
12773
- if (hasRequiredFunctionBind) return functionBind;
12774
- hasRequiredFunctionBind = 1;
12793
+ return bound;
12794
+ };
12775
12795
 
12776
- var implementation = requireImplementation();
12796
+ var implementation = implementation$1;
12777
12797
 
12778
- functionBind = Function.prototype.bind || implementation;
12779
- return functionBind;
12780
- }
12798
+ var functionBind = Function.prototype.bind || implementation;
12781
12799
 
12782
12800
  var functionCall;
12783
12801
  var hasRequiredFunctionCall;
@@ -12822,7 +12840,7 @@ function requireActualApply () {
12822
12840
  if (hasRequiredActualApply) return actualApply;
12823
12841
  hasRequiredActualApply = 1;
12824
12842
 
12825
- var bind = requireFunctionBind();
12843
+ var bind = functionBind;
12826
12844
 
12827
12845
  var $apply = requireFunctionApply();
12828
12846
  var $call = requireFunctionCall();
@@ -12840,7 +12858,7 @@ function requireCallBindApplyHelpers () {
12840
12858
  if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers;
12841
12859
  hasRequiredCallBindApplyHelpers = 1;
12842
12860
 
12843
- var bind = requireFunctionBind();
12861
+ var bind = functionBind;
12844
12862
  var $TypeError = requireType();
12845
12863
 
12846
12864
  var $call = requireFunctionCall();
@@ -12929,21 +12947,12 @@ function requireGetProto () {
12929
12947
  return getProto$1;
12930
12948
  }
12931
12949
 
12932
- var hasown;
12933
- var hasRequiredHasown;
12934
-
12935
- function requireHasown () {
12936
- if (hasRequiredHasown) return hasown;
12937
- hasRequiredHasown = 1;
12950
+ var call = Function.prototype.call;
12951
+ var $hasOwn = Object.prototype.hasOwnProperty;
12952
+ var bind$1 = functionBind;
12938
12953
 
12939
- var call = Function.prototype.call;
12940
- var $hasOwn = Object.prototype.hasOwnProperty;
12941
- var bind = requireFunctionBind();
12942
-
12943
- /** @type {import('.')} */
12944
- hasown = bind.call(call, $hasOwn);
12945
- return hasown;
12946
- }
12954
+ /** @type {import('.')} */
12955
+ var hasown = bind$1.call(call, $hasOwn);
12947
12956
 
12948
12957
  var undefined$1;
12949
12958
 
@@ -12959,7 +12968,7 @@ var $URIError = uri;
12959
12968
 
12960
12969
  var abs = abs$1;
12961
12970
  var floor = floor$1;
12962
- var max = max$1;
12971
+ var max = max$2;
12963
12972
  var min = min$1;
12964
12973
  var pow = pow$1;
12965
12974
  var round = round$1;
@@ -13185,8 +13194,8 @@ var LEGACY_ALIASES = {
13185
13194
  '%WeakSetPrototype%': ['WeakSet', 'prototype']
13186
13195
  };
13187
13196
 
13188
- var bind = requireFunctionBind();
13189
- var hasOwn$1 = requireHasown();
13197
+ var bind = functionBind;
13198
+ var hasOwn$2 = hasown;
13190
13199
  var $concat = bind.call($call, Array.prototype.concat);
13191
13200
  var $spliceApply = bind.call($apply, Array.prototype.splice);
13192
13201
  var $replace = bind.call($call, String.prototype.replace);
@@ -13215,12 +13224,12 @@ var stringToPath = function stringToPath(string) {
13215
13224
  var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
13216
13225
  var intrinsicName = name;
13217
13226
  var alias;
13218
- if (hasOwn$1(LEGACY_ALIASES, intrinsicName)) {
13227
+ if (hasOwn$2(LEGACY_ALIASES, intrinsicName)) {
13219
13228
  alias = LEGACY_ALIASES[intrinsicName];
13220
13229
  intrinsicName = '%' + alias[0] + '%';
13221
13230
  }
13222
13231
 
13223
- if (hasOwn$1(INTRINSICS, intrinsicName)) {
13232
+ if (hasOwn$2(INTRINSICS, intrinsicName)) {
13224
13233
  var value = INTRINSICS[intrinsicName];
13225
13234
  if (value === needsEval) {
13226
13235
  value = doEval(intrinsicName);
@@ -13284,14 +13293,14 @@ var getIntrinsic = function GetIntrinsic(name, allowMissing) {
13284
13293
  intrinsicBaseName += '.' + part;
13285
13294
  intrinsicRealName = '%' + intrinsicBaseName + '%';
13286
13295
 
13287
- if (hasOwn$1(INTRINSICS, intrinsicRealName)) {
13296
+ if (hasOwn$2(INTRINSICS, intrinsicRealName)) {
13288
13297
  value = INTRINSICS[intrinsicRealName];
13289
13298
  } else if (value != null) {
13290
13299
  if (!(part in value)) {
13291
13300
  if (!allowMissing) {
13292
13301
  throw new $TypeError$1('base intrinsic for ' + name + ' exists, but the property is not available.');
13293
13302
  }
13294
- return void 0;
13303
+ return void undefined$1;
13295
13304
  }
13296
13305
  if ($gOPD && (i + 1) >= parts.length) {
13297
13306
  var desc = $gOPD(value, part);
@@ -13310,7 +13319,7 @@ var getIntrinsic = function GetIntrinsic(name, allowMissing) {
13310
13319
  value = value[part];
13311
13320
  }
13312
13321
  } else {
13313
- isOwn = hasOwn$1(value, part);
13322
+ isOwn = hasOwn$2(value, part);
13314
13323
  value = value[part];
13315
13324
  }
13316
13325
 
@@ -13343,7 +13352,7 @@ var GetIntrinsic = getIntrinsic;
13343
13352
  var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
13344
13353
 
13345
13354
  var hasToStringTag = requireShams()();
13346
- var hasOwn = requireHasown();
13355
+ var hasOwn$1 = hasown;
13347
13356
  var $TypeError = requireType();
13348
13357
 
13349
13358
  var toStringTag = hasToStringTag ? Symbol.toStringTag : null;
@@ -13358,7 +13367,7 @@ var esSetTostringtag = function setToStringTag(object, value) {
13358
13367
  ) {
13359
13368
  throw new $TypeError('if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans');
13360
13369
  }
13361
- if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) {
13370
+ if (toStringTag && (overrideIfSet || !hasOwn$1(object, toStringTag))) {
13362
13371
  if ($defineProperty) {
13363
13372
  $defineProperty(object, toStringTag, {
13364
13373
  configurable: !nonConfigurable,
@@ -13373,11 +13382,9 @@ var esSetTostringtag = function setToStringTag(object, value) {
13373
13382
  };
13374
13383
 
13375
13384
  // populates missing values
13376
- var populate$1 = function(dst, src) {
13377
-
13378
- Object.keys(src).forEach(function(prop)
13379
- {
13380
- dst[prop] = dst[prop] || src[prop];
13385
+ var populate$1 = function (dst, src) {
13386
+ Object.keys(src).forEach(function (prop) {
13387
+ dst[prop] = dst[prop] || src[prop]; // eslint-disable-line no-param-reassign
13381
13388
  });
13382
13389
 
13383
13390
  return dst;
@@ -13391,24 +13398,20 @@ var https$1 = require$$4;
13391
13398
  var parseUrl$2 = require$$0$1.parse;
13392
13399
  var fs = require$$6;
13393
13400
  var Stream = stream.Stream;
13401
+ var crypto = require$$8;
13394
13402
  var mime = mimeTypes;
13395
13403
  var asynckit = asynckit$1;
13396
13404
  var setToStringTag = esSetTostringtag;
13405
+ var hasOwn = hasown;
13397
13406
  var populate = populate$1;
13398
13407
 
13399
- // Public API
13400
- var form_data = FormData$1;
13401
-
13402
- // make it a Stream
13403
- util.inherits(FormData$1, CombinedStream);
13404
-
13405
13408
  /**
13406
13409
  * Create readable "multipart/form-data" streams.
13407
13410
  * Can be used to submit forms
13408
13411
  * and file uploads to other web applications.
13409
13412
  *
13410
13413
  * @constructor
13411
- * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream
13414
+ * @param {object} options - Properties to be added/overriden for FormData and CombinedStream
13412
13415
  */
13413
13416
  function FormData$1(options) {
13414
13417
  if (!(this instanceof FormData$1)) {
@@ -13421,35 +13424,39 @@ function FormData$1(options) {
13421
13424
 
13422
13425
  CombinedStream.call(this);
13423
13426
 
13424
- options = options || {};
13425
- for (var option in options) {
13427
+ options = options || {}; // eslint-disable-line no-param-reassign
13428
+ for (var option in options) { // eslint-disable-line no-restricted-syntax
13426
13429
  this[option] = options[option];
13427
13430
  }
13428
13431
  }
13429
13432
 
13433
+ // make it a Stream
13434
+ util.inherits(FormData$1, CombinedStream);
13435
+
13430
13436
  FormData$1.LINE_BREAK = '\r\n';
13431
13437
  FormData$1.DEFAULT_CONTENT_TYPE = 'application/octet-stream';
13432
13438
 
13433
- FormData$1.prototype.append = function(field, value, options) {
13434
-
13435
- options = options || {};
13439
+ FormData$1.prototype.append = function (field, value, options) {
13440
+ options = options || {}; // eslint-disable-line no-param-reassign
13436
13441
 
13437
13442
  // allow filename as single option
13438
- if (typeof options == 'string') {
13439
- options = {filename: options};
13443
+ if (typeof options === 'string') {
13444
+ options = { filename: options }; // eslint-disable-line no-param-reassign
13440
13445
  }
13441
13446
 
13442
13447
  var append = CombinedStream.prototype.append.bind(this);
13443
13448
 
13444
13449
  // all that streamy business can't handle numbers
13445
- if (typeof value == 'number') {
13446
- value = '' + value;
13450
+ if (typeof value === 'number' || value == null) {
13451
+ value = String(value); // eslint-disable-line no-param-reassign
13447
13452
  }
13448
13453
 
13449
13454
  // https://github.com/felixge/node-form-data/issues/38
13450
13455
  if (Array.isArray(value)) {
13451
- // Please convert your array into string
13452
- // the way web server expects it
13456
+ /*
13457
+ * Please convert your array into string
13458
+ * the way web server expects it
13459
+ */
13453
13460
  this._error(new Error('Arrays are not supported.'));
13454
13461
  return;
13455
13462
  }
@@ -13465,15 +13472,17 @@ FormData$1.prototype.append = function(field, value, options) {
13465
13472
  this._trackLength(header, value, options);
13466
13473
  };
13467
13474
 
13468
- FormData$1.prototype._trackLength = function(header, value, options) {
13475
+ FormData$1.prototype._trackLength = function (header, value, options) {
13469
13476
  var valueLength = 0;
13470
13477
 
13471
- // used w/ getLengthSync(), when length is known.
13472
- // e.g. for streaming directly from a remote server,
13473
- // w/ a known file a size, and not wanting to wait for
13474
- // incoming file to finish to get its size.
13478
+ /*
13479
+ * used w/ getLengthSync(), when length is known.
13480
+ * e.g. for streaming directly from a remote server,
13481
+ * w/ a known file a size, and not wanting to wait for
13482
+ * incoming file to finish to get its size.
13483
+ */
13475
13484
  if (options.knownLength != null) {
13476
- valueLength += +options.knownLength;
13485
+ valueLength += Number(options.knownLength);
13477
13486
  } else if (Buffer.isBuffer(value)) {
13478
13487
  valueLength = value.length;
13479
13488
  } else if (typeof value === 'string') {
@@ -13483,12 +13492,10 @@ FormData$1.prototype._trackLength = function(header, value, options) {
13483
13492
  this._valueLength += valueLength;
13484
13493
 
13485
13494
  // @check why add CRLF? does this account for custom/multiple CRLFs?
13486
- this._overheadLength +=
13487
- Buffer.byteLength(header) +
13488
- FormData$1.LINE_BREAK.length;
13495
+ this._overheadLength += Buffer.byteLength(header) + FormData$1.LINE_BREAK.length;
13489
13496
 
13490
13497
  // empty or either doesn't have path or not an http response or not a stream
13491
- if (!value || ( !value.path && !(value.readable && Object.prototype.hasOwnProperty.call(value, 'httpVersion')) && !(value instanceof Stream))) {
13498
+ if (!value || (!value.path && !(value.readable && hasOwn(value, 'httpVersion')) && !(value instanceof Stream))) {
13492
13499
  return;
13493
13500
  }
13494
13501
 
@@ -13498,9 +13505,8 @@ FormData$1.prototype._trackLength = function(header, value, options) {
13498
13505
  }
13499
13506
  };
13500
13507
 
13501
- FormData$1.prototype._lengthRetriever = function(value, callback) {
13502
- if (Object.prototype.hasOwnProperty.call(value, 'fd')) {
13503
-
13508
+ FormData$1.prototype._lengthRetriever = function (value, callback) {
13509
+ if (hasOwn(value, 'fd')) {
13504
13510
  // take read range into a account
13505
13511
  // `end` = Infinity –> read file till the end
13506
13512
  //
@@ -13509,54 +13515,52 @@ FormData$1.prototype._lengthRetriever = function(value, callback) {
13509
13515
  // Fix it when node fixes it.
13510
13516
  // https://github.com/joyent/node/issues/7819
13511
13517
  if (value.end != undefined && value.end != Infinity && value.start != undefined) {
13512
-
13513
13518
  // when end specified
13514
13519
  // no need to calculate range
13515
13520
  // inclusive, starts with 0
13516
- callback(null, value.end + 1 - (value.start ? value.start : 0));
13521
+ callback(null, value.end + 1 - (value.start ? value.start : 0)); // eslint-disable-line callback-return
13517
13522
 
13518
- // not that fast snoopy
13523
+ // not that fast snoopy
13519
13524
  } else {
13520
13525
  // still need to fetch file size from fs
13521
- fs.stat(value.path, function(err, stat) {
13522
-
13523
- var fileSize;
13524
-
13526
+ fs.stat(value.path, function (err, stat) {
13525
13527
  if (err) {
13526
13528
  callback(err);
13527
13529
  return;
13528
13530
  }
13529
13531
 
13530
13532
  // update final size based on the range options
13531
- fileSize = stat.size - (value.start ? value.start : 0);
13533
+ var fileSize = stat.size - (value.start ? value.start : 0);
13532
13534
  callback(null, fileSize);
13533
13535
  });
13534
13536
  }
13535
13537
 
13536
- // or http response
13537
- } else if (Object.prototype.hasOwnProperty.call(value, 'httpVersion')) {
13538
- callback(null, +value.headers['content-length']);
13538
+ // or http response
13539
+ } else if (hasOwn(value, 'httpVersion')) {
13540
+ callback(null, Number(value.headers['content-length'])); // eslint-disable-line callback-return
13539
13541
 
13540
- // or request stream http://github.com/mikeal/request
13541
- } else if (Object.prototype.hasOwnProperty.call(value, 'httpModule')) {
13542
+ // or request stream http://github.com/mikeal/request
13543
+ } else if (hasOwn(value, 'httpModule')) {
13542
13544
  // wait till response come back
13543
- value.on('response', function(response) {
13545
+ value.on('response', function (response) {
13544
13546
  value.pause();
13545
- callback(null, +response.headers['content-length']);
13547
+ callback(null, Number(response.headers['content-length']));
13546
13548
  });
13547
13549
  value.resume();
13548
13550
 
13549
- // something else
13551
+ // something else
13550
13552
  } else {
13551
- callback('Unknown stream');
13553
+ callback('Unknown stream'); // eslint-disable-line callback-return
13552
13554
  }
13553
13555
  };
13554
13556
 
13555
- FormData$1.prototype._multiPartHeader = function(field, value, options) {
13556
- // custom header specified (as string)?
13557
- // it becomes responsible for boundary
13558
- // (e.g. to handle extra CRLFs on .NET servers)
13559
- if (typeof options.header == 'string') {
13557
+ FormData$1.prototype._multiPartHeader = function (field, value, options) {
13558
+ /*
13559
+ * custom header specified (as string)?
13560
+ * it becomes responsible for boundary
13561
+ * (e.g. to handle extra CRLFs on .NET servers)
13562
+ */
13563
+ if (typeof options.header === 'string') {
13560
13564
  return options.header;
13561
13565
  }
13562
13566
 
@@ -13564,7 +13568,7 @@ FormData$1.prototype._multiPartHeader = function(field, value, options) {
13564
13568
  var contentType = this._getContentType(value, options);
13565
13569
 
13566
13570
  var contents = '';
13567
- var headers = {
13571
+ var headers = {
13568
13572
  // add custom disposition as third element or keep it two elements if not
13569
13573
  'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
13570
13574
  // if no content type. allow it to be empty array
@@ -13572,18 +13576,18 @@ FormData$1.prototype._multiPartHeader = function(field, value, options) {
13572
13576
  };
13573
13577
 
13574
13578
  // allow custom headers.
13575
- if (typeof options.header == 'object') {
13579
+ if (typeof options.header === 'object') {
13576
13580
  populate(headers, options.header);
13577
13581
  }
13578
13582
 
13579
13583
  var header;
13580
- for (var prop in headers) {
13581
- if (Object.prototype.hasOwnProperty.call(headers, prop)) {
13584
+ for (var prop in headers) { // eslint-disable-line no-restricted-syntax
13585
+ if (hasOwn(headers, prop)) {
13582
13586
  header = headers[prop];
13583
13587
 
13584
13588
  // skip nullish headers.
13585
13589
  if (header == null) {
13586
- continue;
13590
+ continue; // eslint-disable-line no-restricted-syntax, no-continue
13587
13591
  }
13588
13592
 
13589
13593
  // convert all headers to arrays.
@@ -13601,49 +13605,45 @@ FormData$1.prototype._multiPartHeader = function(field, value, options) {
13601
13605
  return '--' + this.getBoundary() + FormData$1.LINE_BREAK + contents + FormData$1.LINE_BREAK;
13602
13606
  };
13603
13607
 
13604
- FormData$1.prototype._getContentDisposition = function(value, options) {
13605
-
13606
- var filename
13607
- , contentDisposition
13608
- ;
13608
+ FormData$1.prototype._getContentDisposition = function (value, options) { // eslint-disable-line consistent-return
13609
+ var filename;
13609
13610
 
13610
13611
  if (typeof options.filepath === 'string') {
13611
13612
  // custom filepath for relative paths
13612
13613
  filename = path.normalize(options.filepath).replace(/\\/g, '/');
13613
- } else if (options.filename || value.name || value.path) {
13614
- // custom filename take precedence
13615
- // formidable and the browser add a name property
13616
- // fs- and request- streams have path property
13617
- filename = path.basename(options.filename || value.name || value.path);
13618
- } else if (value.readable && Object.prototype.hasOwnProperty.call(value, 'httpVersion')) {
13614
+ } else if (options.filename || (value && (value.name || value.path))) {
13615
+ /*
13616
+ * custom filename take precedence
13617
+ * formidable and the browser add a name property
13618
+ * fs- and request- streams have path property
13619
+ */
13620
+ filename = path.basename(options.filename || (value && (value.name || value.path)));
13621
+ } else if (value && value.readable && hasOwn(value, 'httpVersion')) {
13619
13622
  // or try http response
13620
13623
  filename = path.basename(value.client._httpMessage.path || '');
13621
13624
  }
13622
13625
 
13623
13626
  if (filename) {
13624
- contentDisposition = 'filename="' + filename + '"';
13627
+ return 'filename="' + filename + '"';
13625
13628
  }
13626
-
13627
- return contentDisposition;
13628
13629
  };
13629
13630
 
13630
- FormData$1.prototype._getContentType = function(value, options) {
13631
-
13631
+ FormData$1.prototype._getContentType = function (value, options) {
13632
13632
  // use custom content-type above all
13633
13633
  var contentType = options.contentType;
13634
13634
 
13635
13635
  // or try `name` from formidable, browser
13636
- if (!contentType && value.name) {
13636
+ if (!contentType && value && value.name) {
13637
13637
  contentType = mime.lookup(value.name);
13638
13638
  }
13639
13639
 
13640
13640
  // or try `path` from fs-, request- streams
13641
- if (!contentType && value.path) {
13641
+ if (!contentType && value && value.path) {
13642
13642
  contentType = mime.lookup(value.path);
13643
13643
  }
13644
13644
 
13645
13645
  // or if it's http-reponse
13646
- if (!contentType && value.readable && Object.prototype.hasOwnProperty.call(value, 'httpVersion')) {
13646
+ if (!contentType && value && value.readable && hasOwn(value, 'httpVersion')) {
13647
13647
  contentType = value.headers['content-type'];
13648
13648
  }
13649
13649
 
@@ -13653,18 +13653,18 @@ FormData$1.prototype._getContentType = function(value, options) {
13653
13653
  }
13654
13654
 
13655
13655
  // fallback to the default content type if `value` is not simple value
13656
- if (!contentType && typeof value == 'object') {
13656
+ if (!contentType && value && typeof value === 'object') {
13657
13657
  contentType = FormData$1.DEFAULT_CONTENT_TYPE;
13658
13658
  }
13659
13659
 
13660
13660
  return contentType;
13661
13661
  };
13662
13662
 
13663
- FormData$1.prototype._multiPartFooter = function() {
13664
- return function(next) {
13663
+ FormData$1.prototype._multiPartFooter = function () {
13664
+ return function (next) {
13665
13665
  var footer = FormData$1.LINE_BREAK;
13666
13666
 
13667
- var lastPart = (this._streams.length === 0);
13667
+ var lastPart = this._streams.length === 0;
13668
13668
  if (lastPart) {
13669
13669
  footer += this._lastBoundary();
13670
13670
  }
@@ -13673,18 +13673,18 @@ FormData$1.prototype._multiPartFooter = function() {
13673
13673
  }.bind(this);
13674
13674
  };
13675
13675
 
13676
- FormData$1.prototype._lastBoundary = function() {
13676
+ FormData$1.prototype._lastBoundary = function () {
13677
13677
  return '--' + this.getBoundary() + '--' + FormData$1.LINE_BREAK;
13678
13678
  };
13679
13679
 
13680
- FormData$1.prototype.getHeaders = function(userHeaders) {
13680
+ FormData$1.prototype.getHeaders = function (userHeaders) {
13681
13681
  var header;
13682
13682
  var formHeaders = {
13683
13683
  'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
13684
13684
  };
13685
13685
 
13686
- for (header in userHeaders) {
13687
- if (Object.prototype.hasOwnProperty.call(userHeaders, header)) {
13686
+ for (header in userHeaders) { // eslint-disable-line no-restricted-syntax
13687
+ if (hasOwn(userHeaders, header)) {
13688
13688
  formHeaders[header.toLowerCase()] = userHeaders[header];
13689
13689
  }
13690
13690
  }
@@ -13692,11 +13692,14 @@ FormData$1.prototype.getHeaders = function(userHeaders) {
13692
13692
  return formHeaders;
13693
13693
  };
13694
13694
 
13695
- FormData$1.prototype.setBoundary = function(boundary) {
13695
+ FormData$1.prototype.setBoundary = function (boundary) {
13696
+ if (typeof boundary !== 'string') {
13697
+ throw new TypeError('FormData boundary must be a string');
13698
+ }
13696
13699
  this._boundary = boundary;
13697
13700
  };
13698
13701
 
13699
- FormData$1.prototype.getBoundary = function() {
13702
+ FormData$1.prototype.getBoundary = function () {
13700
13703
  if (!this._boundary) {
13701
13704
  this._generateBoundary();
13702
13705
  }
@@ -13704,60 +13707,55 @@ FormData$1.prototype.getBoundary = function() {
13704
13707
  return this._boundary;
13705
13708
  };
13706
13709
 
13707
- FormData$1.prototype.getBuffer = function() {
13708
- var dataBuffer = new Buffer.alloc(0);
13710
+ FormData$1.prototype.getBuffer = function () {
13711
+ var dataBuffer = new Buffer.alloc(0); // eslint-disable-line new-cap
13709
13712
  var boundary = this.getBoundary();
13710
13713
 
13711
13714
  // Create the form content. Add Line breaks to the end of data.
13712
13715
  for (var i = 0, len = this._streams.length; i < len; i++) {
13713
13716
  if (typeof this._streams[i] !== 'function') {
13714
-
13715
13717
  // Add content to the buffer.
13716
- if(Buffer.isBuffer(this._streams[i])) {
13717
- dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]);
13718
- }else {
13719
- dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]);
13718
+ if (Buffer.isBuffer(this._streams[i])) {
13719
+ dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]);
13720
+ } else {
13721
+ dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]);
13720
13722
  }
13721
13723
 
13722
13724
  // Add break after content.
13723
- if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) {
13724
- dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData$1.LINE_BREAK)] );
13725
+ if (typeof this._streams[i] !== 'string' || this._streams[i].substring(2, boundary.length + 2) !== boundary) {
13726
+ dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData$1.LINE_BREAK)]);
13725
13727
  }
13726
13728
  }
13727
13729
  }
13728
13730
 
13729
13731
  // Add the footer and return the Buffer object.
13730
- return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] );
13732
+ return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
13731
13733
  };
13732
13734
 
13733
- FormData$1.prototype._generateBoundary = function() {
13735
+ FormData$1.prototype._generateBoundary = function () {
13734
13736
  // This generates a 50 character boundary similar to those used by Firefox.
13735
- // They are optimized for boyer-moore parsing.
13736
- var boundary = '--------------------------';
13737
- for (var i = 0; i < 24; i++) {
13738
- boundary += Math.floor(Math.random() * 10).toString(16);
13739
- }
13740
13737
 
13741
- this._boundary = boundary;
13738
+ // They are optimized for boyer-moore parsing.
13739
+ this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex');
13742
13740
  };
13743
13741
 
13744
13742
  // Note: getLengthSync DOESN'T calculate streams length
13745
- // As workaround one can calculate file size manually
13746
- // and add it as knownLength option
13747
- FormData$1.prototype.getLengthSync = function() {
13743
+ // As workaround one can calculate file size manually and add it as knownLength option
13744
+ FormData$1.prototype.getLengthSync = function () {
13748
13745
  var knownLength = this._overheadLength + this._valueLength;
13749
13746
 
13750
- // Don't get confused, there are 3 "internal" streams for each keyval pair
13751
- // so it basically checks if there is any value added to the form
13747
+ // Don't get confused, there are 3 "internal" streams for each keyval pair so it basically checks if there is any value added to the form
13752
13748
  if (this._streams.length) {
13753
13749
  knownLength += this._lastBoundary().length;
13754
13750
  }
13755
13751
 
13756
13752
  // https://github.com/form-data/form-data/issues/40
13757
13753
  if (!this.hasKnownLength()) {
13758
- // Some async length retrievers are present
13759
- // therefore synchronous length calculation is false.
13760
- // Please use getLength(callback) to get proper length
13754
+ /*
13755
+ * Some async length retrievers are present
13756
+ * therefore synchronous length calculation is false.
13757
+ * Please use getLength(callback) to get proper length
13758
+ */
13761
13759
  this._error(new Error('Cannot calculate proper length in synchronous way.'));
13762
13760
  }
13763
13761
 
@@ -13767,7 +13765,7 @@ FormData$1.prototype.getLengthSync = function() {
13767
13765
  // Public API to check if length of added values is known
13768
13766
  // https://github.com/form-data/form-data/issues/196
13769
13767
  // https://github.com/form-data/form-data/issues/262
13770
- FormData$1.prototype.hasKnownLength = function() {
13768
+ FormData$1.prototype.hasKnownLength = function () {
13771
13769
  var hasKnownLength = true;
13772
13770
 
13773
13771
  if (this._valuesToMeasure.length) {
@@ -13777,7 +13775,7 @@ FormData$1.prototype.hasKnownLength = function() {
13777
13775
  return hasKnownLength;
13778
13776
  };
13779
13777
 
13780
- FormData$1.prototype.getLength = function(cb) {
13778
+ FormData$1.prototype.getLength = function (cb) {
13781
13779
  var knownLength = this._overheadLength + this._valueLength;
13782
13780
 
13783
13781
  if (this._streams.length) {
@@ -13789,13 +13787,13 @@ FormData$1.prototype.getLength = function(cb) {
13789
13787
  return;
13790
13788
  }
13791
13789
 
13792
- asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
13790
+ asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function (err, values) {
13793
13791
  if (err) {
13794
13792
  cb(err);
13795
13793
  return;
13796
13794
  }
13797
13795
 
13798
- values.forEach(function(length) {
13796
+ values.forEach(function (length) {
13799
13797
  knownLength += length;
13800
13798
  });
13801
13799
 
@@ -13803,31 +13801,26 @@ FormData$1.prototype.getLength = function(cb) {
13803
13801
  });
13804
13802
  };
13805
13803
 
13806
- FormData$1.prototype.submit = function(params, cb) {
13807
- var request
13808
- , options
13809
- , defaults = {method: 'post'}
13810
- ;
13811
-
13812
- // parse provided url if it's string
13813
- // or treat it as options object
13814
- if (typeof params == 'string') {
13804
+ FormData$1.prototype.submit = function (params, cb) {
13805
+ var request;
13806
+ var options;
13807
+ var defaults = { method: 'post' };
13815
13808
 
13816
- params = parseUrl$2(params);
13809
+ // parse provided url if it's string or treat it as options object
13810
+ if (typeof params === 'string') {
13811
+ params = parseUrl$2(params); // eslint-disable-line no-param-reassign
13812
+ /* eslint sort-keys: 0 */
13817
13813
  options = populate({
13818
13814
  port: params.port,
13819
13815
  path: params.pathname,
13820
13816
  host: params.hostname,
13821
13817
  protocol: params.protocol
13822
13818
  }, defaults);
13823
-
13824
- // use custom params
13825
- } else {
13826
-
13819
+ } else { // use custom params
13827
13820
  options = populate(params, defaults);
13828
13821
  // if no port provided use default one
13829
13822
  if (!options.port) {
13830
- options.port = options.protocol == 'https:' ? 443 : 80;
13823
+ options.port = options.protocol === 'https:' ? 443 : 80;
13831
13824
  }
13832
13825
  }
13833
13826
 
@@ -13835,14 +13828,14 @@ FormData$1.prototype.submit = function(params, cb) {
13835
13828
  options.headers = this.getHeaders(params.headers);
13836
13829
 
13837
13830
  // https if specified, fallback to http in any other case
13838
- if (options.protocol == 'https:') {
13831
+ if (options.protocol === 'https:') {
13839
13832
  request = https$1.request(options);
13840
13833
  } else {
13841
13834
  request = http$1.request(options);
13842
13835
  }
13843
13836
 
13844
13837
  // get content length and fire away
13845
- this.getLength(function(err, length) {
13838
+ this.getLength(function (err, length) {
13846
13839
  if (err && err !== 'Unknown stream') {
13847
13840
  this._error(err);
13848
13841
  return;
@@ -13861,7 +13854,7 @@ FormData$1.prototype.submit = function(params, cb) {
13861
13854
  request.removeListener('error', callback);
13862
13855
  request.removeListener('response', onResponse);
13863
13856
 
13864
- return cb.call(this, error, responce);
13857
+ return cb.call(this, error, responce); // eslint-disable-line no-invalid-this
13865
13858
  };
13866
13859
 
13867
13860
  onResponse = callback.bind(this, null);
@@ -13874,7 +13867,7 @@ FormData$1.prototype.submit = function(params, cb) {
13874
13867
  return request;
13875
13868
  };
13876
13869
 
13877
- FormData$1.prototype._error = function(err) {
13870
+ FormData$1.prototype._error = function (err) {
13878
13871
  if (!this.error) {
13879
13872
  this.error = err;
13880
13873
  this.pause();
@@ -13887,6 +13880,9 @@ FormData$1.prototype.toString = function () {
13887
13880
  };
13888
13881
  setToStringTag(FormData$1, 'FormData');
13889
13882
 
13883
+ // Public API
13884
+ var form_data = FormData$1;
13885
+
13890
13886
  var FormData$2 = /*@__PURE__*/getDefaultExportFromCjs(form_data);
13891
13887
 
13892
13888
  /**
@@ -14004,6 +14000,10 @@ function toFormData$1(obj, formData, options) {
14004
14000
  return value.toISOString();
14005
14001
  }
14006
14002
 
14003
+ if (utils$1.isBoolean(value)) {
14004
+ return value.toString();
14005
+ }
14006
+
14007
14007
  if (!useBlob && utils$1.isBlob(value)) {
14008
14008
  throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
14009
14009
  }
@@ -14306,7 +14306,7 @@ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
14306
14306
  let str = '';
14307
14307
  const {length} = alphabet;
14308
14308
  const randomValues = new Uint32Array(size);
14309
- crypto.randomFillSync(randomValues);
14309
+ require$$8.randomFillSync(randomValues);
14310
14310
  for (let i = 0; i < size; i++) {
14311
14311
  str += alphabet[randomValues[i] % length];
14312
14312
  }
@@ -14386,7 +14386,7 @@ var platform = {
14386
14386
  };
14387
14387
 
14388
14388
  function toURLEncodedForm(data, options) {
14389
- return toFormData$1(data, new platform.classes.URLSearchParams(), Object.assign({
14389
+ return toFormData$1(data, new platform.classes.URLSearchParams(), {
14390
14390
  visitor: function(value, key, path, helpers) {
14391
14391
  if (platform.isNode && utils$1.isBuffer(value)) {
14392
14392
  this.append(key, value.toString('base64'));
@@ -14394,8 +14394,9 @@ function toURLEncodedForm(data, options) {
14394
14394
  }
14395
14395
 
14396
14396
  return helpers.defaultVisitor.apply(this, arguments);
14397
- }
14398
- }, options));
14397
+ },
14398
+ ...options
14399
+ });
14399
14400
  }
14400
14401
 
14401
14402
  /**
@@ -15931,7 +15932,7 @@ followRedirects$1.exports.wrap = wrap;
15931
15932
  var followRedirectsExports = followRedirects$1.exports;
15932
15933
  var followRedirects = /*@__PURE__*/getDefaultExportFromCjs(followRedirectsExports);
15933
15934
 
15934
- const VERSION$1 = "1.9.0";
15935
+ const VERSION$1 = "1.11.0";
15935
15936
 
15936
15937
  function parseProtocol(url) {
15937
15938
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
@@ -16349,7 +16350,7 @@ function throttle(fn, freq) {
16349
16350
  clearTimeout(timer);
16350
16351
  timer = null;
16351
16352
  }
16352
- fn.apply(null, args);
16353
+ fn(...args);
16353
16354
  };
16354
16355
 
16355
16356
  const throttled = (...args) => {
@@ -17223,7 +17224,7 @@ function mergeConfig$1(config1, config2) {
17223
17224
  headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)
17224
17225
  };
17225
17226
 
17226
- utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
17227
+ utils$1.forEach(Object.keys({...config1, ...config2}), function computeConfigValue(prop) {
17227
17228
  const merge = mergeMap[prop] || mergeDeepProperties;
17228
17229
  const configValue = merge(config1[prop], config2[prop], prop);
17229
17230
  (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
@@ -17756,7 +17757,7 @@ var fetchAdapter = isFetchSupported && (async (config) => {
17756
17757
  credentials: isCredentialsSupported ? withCredentials : undefined
17757
17758
  });
17758
17759
 
17759
- let response = await fetch(request);
17760
+ let response = await fetch(request, fetchOptions);
17760
17761
 
17761
17762
  const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
17762
17763
 
@@ -18199,8 +18200,8 @@ let Axios$1 = class Axios {
18199
18200
 
18200
18201
  if (!synchronousRequestInterceptors) {
18201
18202
  const chain = [dispatchRequest.bind(this), undefined];
18202
- chain.unshift.apply(chain, requestInterceptorChain);
18203
- chain.push.apply(chain, responseInterceptorChain);
18203
+ chain.unshift(...requestInterceptorChain);
18204
+ chain.push(...responseInterceptorChain);
18204
18205
  len = chain.length;
18205
18206
 
18206
18207
  promise = Promise.resolve(config);
@@ -18532,7 +18533,7 @@ Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
18532
18533
  */
18533
18534
  function createInstance(defaultConfig) {
18534
18535
  const context = new Axios$1(defaultConfig);
18535
- const instance = bind$1(Axios$1.prototype.request, context);
18536
+ const instance = bind$2(Axios$1.prototype.request, context);
18536
18537
 
18537
18538
  // Copy axios.prototype to instance
18538
18539
  utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
@@ -19166,7 +19167,560 @@ async function createWeeklyReport({ week, gcaUrls, apiUrl, }) {
19166
19167
  };
19167
19168
  }
19168
19169
 
19170
+ const FORWARDER_ABI = [
19171
+ {
19172
+ inputs: [{ internalType: "address", name: "_forwarder", type: "address" }],
19173
+ stateMutability: "nonpayable",
19174
+ type: "constructor",
19175
+ },
19176
+ {
19177
+ inputs: [{ internalType: "address", name: "target", type: "address" }],
19178
+ name: "AddressEmptyCode",
19179
+ type: "error",
19180
+ },
19181
+ {
19182
+ inputs: [{ internalType: "address", name: "account", type: "address" }],
19183
+ name: "AddressInsufficientBalance",
19184
+ type: "error",
19185
+ },
19186
+ { inputs: [], name: "FailedInnerCall", type: "error" },
19187
+ {
19188
+ inputs: [{ internalType: "address", name: "token", type: "address" }],
19189
+ name: "SafeERC20FailedOperation",
19190
+ type: "error",
19191
+ },
19192
+ {
19193
+ anonymous: false,
19194
+ inputs: [
19195
+ { indexed: true, internalType: "address", name: "from", type: "address" },
19196
+ { indexed: true, internalType: "address", name: "to", type: "address" },
19197
+ {
19198
+ indexed: true,
19199
+ internalType: "address",
19200
+ name: "token",
19201
+ type: "address",
19202
+ },
19203
+ {
19204
+ indexed: false,
19205
+ internalType: "uint256",
19206
+ name: "amount",
19207
+ type: "uint256",
19208
+ },
19209
+ {
19210
+ indexed: false,
19211
+ internalType: "string",
19212
+ name: "message",
19213
+ type: "string",
19214
+ },
19215
+ ],
19216
+ name: "Forward",
19217
+ type: "event",
19218
+ },
19219
+ {
19220
+ inputs: [],
19221
+ name: "FORWARD_ADDRESS",
19222
+ outputs: [{ internalType: "address", name: "", type: "address" }],
19223
+ stateMutability: "view",
19224
+ type: "function",
19225
+ },
19226
+ {
19227
+ inputs: [
19228
+ { internalType: "address", name: "token", type: "address" },
19229
+ { internalType: "address", name: "to", type: "address" },
19230
+ { internalType: "uint256", name: "amount", type: "uint256" },
19231
+ { internalType: "string", name: "message", type: "string" },
19232
+ ],
19233
+ name: "forward",
19234
+ outputs: [],
19235
+ stateMutability: "nonpayable",
19236
+ type: "function",
19237
+ },
19238
+ ];
19239
+
19240
+ const ERC20_ABI = [
19241
+ {
19242
+ inputs: [
19243
+ { name: "spender", type: "address" },
19244
+ { name: "amount", type: "uint256" },
19245
+ ],
19246
+ name: "approve",
19247
+ outputs: [{ name: "", type: "bool" }],
19248
+ stateMutability: "nonpayable",
19249
+ type: "function",
19250
+ },
19251
+ {
19252
+ inputs: [
19253
+ { name: "owner", type: "address" },
19254
+ { name: "spender", type: "address" },
19255
+ ],
19256
+ name: "allowance",
19257
+ outputs: [{ name: "", type: "uint256" }],
19258
+ stateMutability: "view",
19259
+ type: "function",
19260
+ },
19261
+ {
19262
+ inputs: [
19263
+ { name: "to", type: "address" },
19264
+ { name: "amount", type: "uint256" },
19265
+ ],
19266
+ name: "transfer",
19267
+ outputs: [{ name: "", type: "bool" }],
19268
+ stateMutability: "nonpayable",
19269
+ type: "function",
19270
+ },
19271
+ {
19272
+ inputs: [{ name: "account", type: "address" }],
19273
+ name: "balanceOf",
19274
+ outputs: [{ name: "", type: "uint256" }],
19275
+ stateMutability: "view",
19276
+ type: "function",
19277
+ },
19278
+ {
19279
+ inputs: [
19280
+ { name: "account", type: "address" },
19281
+ { name: "amount", type: "uint256" },
19282
+ ],
19283
+ name: "mint",
19284
+ outputs: [{ name: "", type: "bool" }],
19285
+ stateMutability: "nonpayable",
19286
+ type: "function",
19287
+ },
19288
+ ];
19289
+
19290
+ // Contract-specific addresses
19291
+ const mainnetAddresses = {
19292
+ USDG: "0xe010ec500720bE9EF3F82129E7eD2Ee1FB7955F2",
19293
+ GLW: "0xf4fbC617A5733EAAF9af08E1Ab816B103388d8B6",
19294
+ USDC: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
19295
+ FORWARDER: "0x0000000000000000000000000000000000000000", // TODO: Update with actual mainnet address
19296
+ FOUNDATION_WALLET: "0x0000000000000000000000000000000000000000", // TODO: Update with actual mainnet foundation wallet
19297
+ };
19298
+ const sepoliaAddresses = {
19299
+ USDG: "0xda78313A3fF949890112c1B746AB1c75d1b1c17B",
19300
+ GLW: "0x2039161fcE4C8e5CF5FE64e17Fd290E8dFF3c9BD",
19301
+ USDC: "0x93c898be98cd2618ba84a6dccf5003d3bbe40356",
19302
+ FORWARDER: "0x9c1d61303D46BFAb1eC5F25c12A1Bf4cB3d06416",
19303
+ FOUNDATION_WALLET: "0x5e230FED487c86B90f6508104149F087d9B1B0A7",
19304
+ };
19305
+ const getAddresses = (CHAIN_ID) => {
19306
+ switch (CHAIN_ID) {
19307
+ case 1:
19308
+ return mainnetAddresses;
19309
+ case 11155111:
19310
+ return sepoliaAddresses;
19311
+ default:
19312
+ console.warn(`Unsupported chain ID: ${CHAIN_ID}, falling back to mainnet addresses`);
19313
+ return mainnetAddresses;
19314
+ }
19315
+ };
19316
+
19317
+ var ForwarderError;
19318
+ (function (ForwarderError) {
19319
+ ForwarderError["CONTRACT_NOT_AVAILABLE"] = "Contract not available";
19320
+ ForwarderError["SIGNER_NOT_AVAILABLE"] = "Signer not available";
19321
+ ForwarderError["UNKNOWN_ERROR"] = "Unknown error";
19322
+ ForwarderError["INVALID_FORWARD_TYPE"] = "Invalid forward type";
19323
+ ForwarderError["MISSING_REQUIRED_PARAMS"] = "Missing required parameters";
19324
+ })(ForwarderError || (ForwarderError = {}));
19325
+ // Utility to extract the most useful revert reason from an ethers error object
19326
+ function parseEthersError(error) {
19327
+ if (!error)
19328
+ return "Unknown error";
19329
+ const possibleError = error;
19330
+ // If the error originates from a callStatic it will often be found at `error?.error?.body`
19331
+ if (possibleError?.error?.body) {
19332
+ try {
19333
+ const body = JSON.parse(possibleError.error.body);
19334
+ // Hardhat style errors
19335
+ if (body?.error?.message)
19336
+ return body.error.message;
19337
+ }
19338
+ catch { }
19339
+ }
19340
+ // Found on MetaMask/Alchemy shape errors
19341
+ if (possibleError?.data?.message)
19342
+ return possibleError.data.message;
19343
+ if (possibleError?.error?.message)
19344
+ return possibleError.error.message;
19345
+ // Standard ethers v5 message
19346
+ if (possibleError?.reason)
19347
+ return possibleError.reason;
19348
+ if (possibleError?.message)
19349
+ return possibleError.message;
19350
+ return ForwarderError.UNKNOWN_ERROR;
19351
+ }
19352
+ // Type-guard style helper to ensure a signer exists throughout the rest of the function.
19353
+ function assertSigner(maybeSigner) {
19354
+ if (!maybeSigner) {
19355
+ throw new Error(ForwarderError.SIGNER_NOT_AVAILABLE);
19356
+ }
19357
+ }
19358
+ function useForwarder(signer, CHAIN_ID) {
19359
+ // Use dynamic addresses based on chain configuration
19360
+ const ADDRESSES = getAddresses(CHAIN_ID);
19361
+ // Framework-agnostic processing flag
19362
+ let isProcessing = false;
19363
+ const setIsProcessing = (value) => {
19364
+ isProcessing = value;
19365
+ };
19366
+ // Returns a contract instance for Forwarder
19367
+ function getForwarderContract() {
19368
+ assertSigner(signer);
19369
+ return new ethers.ethers.Contract(ADDRESSES.FORWARDER, FORWARDER_ABI, signer);
19370
+ }
19371
+ /**
19372
+ * Construct the message for the forward call based on type and parameters
19373
+ */
19374
+ function constructForwardMessage(params) {
19375
+ const { type, applicationId, farmId, regionId, userAddress } = params;
19376
+ switch (type) {
19377
+ case "PayProtocolFeeAndMintGCTLAndStake":
19378
+ if (!applicationId) {
19379
+ throw new Error(ForwarderError.MISSING_REQUIRED_PARAMS);
19380
+ }
19381
+ return `PayProtocolFeeAndMintGCTLAndStake::${applicationId}`;
19382
+ case "PayProtocolFee":
19383
+ if (!applicationId) {
19384
+ throw new Error(ForwarderError.MISSING_REQUIRED_PARAMS);
19385
+ }
19386
+ return `PayProtocolFee::${applicationId}`;
19387
+ case "MintGCTLAndStake":
19388
+ if (!regionId) {
19389
+ throw new Error(ForwarderError.MISSING_REQUIRED_PARAMS);
19390
+ }
19391
+ return `MintGCTLAndStake::${regionId}`;
19392
+ case "MintGCTL":
19393
+ if (!userAddress) {
19394
+ throw new Error(ForwarderError.MISSING_REQUIRED_PARAMS);
19395
+ }
19396
+ return `MintGCTL::${userAddress}`;
19397
+ case "BuySolarFarm":
19398
+ if (!farmId) {
19399
+ throw new Error(ForwarderError.MISSING_REQUIRED_PARAMS);
19400
+ }
19401
+ return `BuySolarFarm::${farmId}`;
19402
+ default:
19403
+ throw new Error(ForwarderError.INVALID_FORWARD_TYPE);
19404
+ }
19405
+ }
19406
+ /**
19407
+ * Get the appropriate token contract based on currency
19408
+ */
19409
+ function getTokenContract(currency = "USDC") {
19410
+ assertSigner(signer);
19411
+ let tokenAddress;
19412
+ switch (currency) {
19413
+ case "USDC":
19414
+ tokenAddress = ADDRESSES.USDC;
19415
+ break;
19416
+ case "GLW":
19417
+ tokenAddress = ADDRESSES.GLW;
19418
+ break;
19419
+ case "USDG":
19420
+ tokenAddress = ADDRESSES.USDG;
19421
+ break;
19422
+ default:
19423
+ throw new Error(`Currency ${currency} not yet supported. Only USDC, GLW, and USDG are currently supported.`);
19424
+ }
19425
+ return new ethers.ethers.Contract(tokenAddress, ERC20_ABI, signer);
19426
+ }
19427
+ /**
19428
+ * Check current token allowance for the forwarder contract
19429
+ * @param owner The wallet address to check allowance for
19430
+ * @param currency The currency to check allowance for
19431
+ */
19432
+ async function checkTokenAllowance(owner, currency = "USDC") {
19433
+ assertSigner(signer);
19434
+ try {
19435
+ const tokenContract = getTokenContract(currency);
19436
+ if (!tokenContract)
19437
+ throw new Error(ForwarderError.CONTRACT_NOT_AVAILABLE);
19438
+ const allowance = await tokenContract.allowance(owner, ADDRESSES.FORWARDER);
19439
+ return allowance;
19440
+ }
19441
+ catch (error) {
19442
+ throw new Error(parseEthersError(error));
19443
+ }
19444
+ }
19445
+ /**
19446
+ * Check user's token balance
19447
+ * @param owner The wallet address to check balance for
19448
+ * @param currency The currency to check balance for
19449
+ */
19450
+ async function checkTokenBalance(owner, currency = "USDC") {
19451
+ assertSigner(signer);
19452
+ try {
19453
+ const tokenContract = getTokenContract(currency);
19454
+ if (!tokenContract)
19455
+ throw new Error(ForwarderError.CONTRACT_NOT_AVAILABLE);
19456
+ const balance = await tokenContract.balanceOf(owner);
19457
+ return balance;
19458
+ }
19459
+ catch (error) {
19460
+ throw new Error(parseEthersError(error));
19461
+ }
19462
+ }
19463
+ /**
19464
+ * Approve tokens for the forwarder contract
19465
+ * @param amount Amount to approve (BigNumber)
19466
+ * @param currency The currency to approve
19467
+ */
19468
+ async function approveToken(amount, currency = "USDC") {
19469
+ assertSigner(signer);
19470
+ try {
19471
+ const tokenContract = getTokenContract(currency);
19472
+ if (!tokenContract)
19473
+ throw new Error(ForwarderError.CONTRACT_NOT_AVAILABLE);
19474
+ setIsProcessing(true);
19475
+ // Approve only the specific amount needed
19476
+ const approveTx = await tokenContract.approve(ADDRESSES.FORWARDER, amount);
19477
+ await approveTx.wait();
19478
+ return true;
19479
+ }
19480
+ catch (error) {
19481
+ throw new Error(parseEthersError(error));
19482
+ }
19483
+ finally {
19484
+ setIsProcessing(false);
19485
+ }
19486
+ }
19487
+ /**
19488
+ * Forward tokens through the forwarder contract with type-specific handling
19489
+ * @param params Forward parameters including type, amount, and required fields
19490
+ */
19491
+ async function forwardTokens(params) {
19492
+ assertSigner(signer);
19493
+ try {
19494
+ const forwarderContract = getForwarderContract();
19495
+ if (!forwarderContract)
19496
+ throw new Error(ForwarderError.CONTRACT_NOT_AVAILABLE);
19497
+ setIsProcessing(true);
19498
+ const { amount, currency = "USDC" } = params;
19499
+ const tokenContract = getTokenContract(currency);
19500
+ if (!tokenContract)
19501
+ throw new Error(ForwarderError.CONTRACT_NOT_AVAILABLE);
19502
+ const owner = await signer.getAddress();
19503
+ // Construct the appropriate message for this forward type
19504
+ const message = constructForwardMessage(params);
19505
+ // Check allowance and approve if necessary
19506
+ const allowance = await tokenContract.allowance(owner, ADDRESSES.FORWARDER);
19507
+ if (allowance.lt(amount)) {
19508
+ try {
19509
+ const approveTx = await tokenContract.approve(ADDRESSES.FORWARDER, ethers.ethers.constants.MaxUint256);
19510
+ await approveTx.wait();
19511
+ }
19512
+ catch (approveError) {
19513
+ throw new Error(parseEthersError(approveError) || "Token approval failed");
19514
+ }
19515
+ }
19516
+ // Get the token address based on currency
19517
+ let tokenAddress;
19518
+ switch (currency) {
19519
+ case "USDC":
19520
+ tokenAddress = ADDRESSES.USDC;
19521
+ break;
19522
+ case "USDG":
19523
+ tokenAddress = ADDRESSES.USDG;
19524
+ break;
19525
+ case "GLW":
19526
+ tokenAddress = ADDRESSES.GLW;
19527
+ break;
19528
+ default:
19529
+ throw new Error(`Unsupported currency for forwarding: ${currency}`);
19530
+ }
19531
+ // Run a static call first to surface any revert reason
19532
+ try {
19533
+ await forwarderContract.callStatic.forward(tokenAddress, ADDRESSES.FOUNDATION_WALLET, amount, message, { from: owner });
19534
+ }
19535
+ catch (staticError) {
19536
+ throw new Error(parseEthersError(staticError));
19537
+ }
19538
+ // Execute the forward transaction
19539
+ const tx = await forwarderContract.forward(tokenAddress, ADDRESSES.FOUNDATION_WALLET, amount, message);
19540
+ await tx.wait();
19541
+ return tx.hash;
19542
+ }
19543
+ catch (txError) {
19544
+ throw new Error(parseEthersError(txError));
19545
+ }
19546
+ finally {
19547
+ setIsProcessing(false);
19548
+ }
19549
+ }
19550
+ /**
19551
+ * Forward tokens for protocol fee payment and GCTL minting with staking
19552
+ */
19553
+ async function payProtocolFeeAndMintGCTLAndStake(amount, userAddress, applicationId, regionId, currency = "USDC") {
19554
+ assertSigner(signer);
19555
+ // GCTL minting only supports USDC and USDG
19556
+ if (currency === "GLW") {
19557
+ throw new Error("GCTL minting is not supported with GLW payment. Use USDC or USDG.");
19558
+ }
19559
+ return forwardTokens({
19560
+ amount,
19561
+ userAddress,
19562
+ type: "PayProtocolFeeAndMintGCTLAndStake",
19563
+ currency,
19564
+ applicationId,
19565
+ regionId,
19566
+ });
19567
+ }
19568
+ /**
19569
+ * Forward tokens for protocol fee payment only
19570
+ */
19571
+ async function payProtocolFee(amount, userAddress, applicationId, currency = "USDC") {
19572
+ assertSigner(signer);
19573
+ return forwardTokens({
19574
+ amount,
19575
+ userAddress,
19576
+ type: "PayProtocolFee",
19577
+ currency,
19578
+ applicationId,
19579
+ });
19580
+ }
19581
+ /**
19582
+ * Forward USDC to mint GCTL and stake to a region
19583
+ */
19584
+ async function mintGCTLAndStake(amount, userAddress, regionId) {
19585
+ assertSigner(signer);
19586
+ return forwardTokens({
19587
+ amount,
19588
+ userAddress,
19589
+ type: "MintGCTLAndStake",
19590
+ currency: "USDC",
19591
+ regionId,
19592
+ });
19593
+ }
19594
+ /**
19595
+ * Forward USDC to mint GCTL (existing functionality, keeping for compatibility)
19596
+ */
19597
+ async function mintGCTL(amount, userAddress) {
19598
+ assertSigner(signer);
19599
+ return forwardTokens({
19600
+ amount,
19601
+ userAddress,
19602
+ type: "MintGCTL",
19603
+ currency: "USDC",
19604
+ });
19605
+ }
19606
+ /**
19607
+ * Forward tokens to buy a solar farm
19608
+ */
19609
+ async function buySolarFarm(amount, userAddress, farmId, currency = "USDC") {
19610
+ assertSigner(signer);
19611
+ return forwardTokens({
19612
+ amount,
19613
+ userAddress,
19614
+ type: "BuySolarFarm",
19615
+ currency,
19616
+ farmId,
19617
+ });
19618
+ }
19619
+ /**
19620
+ * Estimate gas for forwarding with type-specific handling
19621
+ * @param params Forward parameters
19622
+ * @param ethPriceInUSD Current ETH price in USD (for cost estimation)
19623
+ */
19624
+ async function estimateGasForForward(params, ethPriceInUSD) {
19625
+ assertSigner(signer);
19626
+ try {
19627
+ const forwarderContract = getForwarderContract();
19628
+ if (!forwarderContract)
19629
+ throw new Error(ForwarderError.CONTRACT_NOT_AVAILABLE);
19630
+ const { amount, currency = "USDC" } = params;
19631
+ // Construct the appropriate message for this forward type
19632
+ const message = constructForwardMessage(params);
19633
+ // Get token address
19634
+ let tokenAddress;
19635
+ switch (currency) {
19636
+ case "USDC":
19637
+ tokenAddress = ADDRESSES.USDC;
19638
+ break;
19639
+ case "USDG":
19640
+ tokenAddress = ADDRESSES.USDG;
19641
+ break;
19642
+ case "GLW":
19643
+ tokenAddress = ADDRESSES.GLW;
19644
+ break;
19645
+ default:
19646
+ throw new Error(`Unsupported currency for gas estimation: ${currency}`);
19647
+ }
19648
+ const gasPrice = await signer.getGasPrice();
19649
+ const estimatedGas = await forwarderContract.estimateGas.forward(tokenAddress, ADDRESSES.FOUNDATION_WALLET, amount, message);
19650
+ const estimatedCost = estimatedGas.mul(gasPrice);
19651
+ if (ethPriceInUSD) {
19652
+ const estimatedCostInEth = ethers.ethers.utils.formatEther(estimatedCost);
19653
+ const estimatedCostInUSD = (parseFloat(estimatedCostInEth) * ethPriceInUSD).toFixed(2);
19654
+ return estimatedCostInUSD;
19655
+ }
19656
+ else {
19657
+ throw new Error("Could not fetch the ETH price to calculate cost in USD.");
19658
+ }
19659
+ }
19660
+ catch (error) {
19661
+ throw new Error(parseEthersError(error));
19662
+ }
19663
+ }
19664
+ /**
19665
+ * Mint test USDC (only works on testnets with mintable USDC contracts)
19666
+ * @param amount Amount of USDC to mint (BigNumber, 6 decimals)
19667
+ * @param recipient Address to mint USDC to
19668
+ */
19669
+ async function mintTestUSDC(amount, recipient) {
19670
+ assertSigner(signer);
19671
+ if (CHAIN_ID !== 11155111) {
19672
+ throw new Error("Minting test USDC is only supported on Sepolia");
19673
+ }
19674
+ try {
19675
+ const usdcContract = getTokenContract("USDC"); // Use getTokenContract for consistency
19676
+ if (!usdcContract)
19677
+ throw new Error(ForwarderError.CONTRACT_NOT_AVAILABLE);
19678
+ setIsProcessing(true);
19679
+ // Try to call mint function (common for test tokens)
19680
+ const tx = await usdcContract.mint(recipient, amount);
19681
+ await tx.wait();
19682
+ return tx.hash;
19683
+ }
19684
+ catch (error) {
19685
+ // If mint function doesn't exist or fails, provide helpful error
19686
+ const errorMessage = parseEthersError(error);
19687
+ if (errorMessage.includes("mint")) {
19688
+ throw new Error("This USDC contract doesn't support minting");
19689
+ }
19690
+ throw new Error(errorMessage);
19691
+ }
19692
+ finally {
19693
+ setIsProcessing(false);
19694
+ }
19695
+ }
19696
+ return {
19697
+ // New methods for different forward types
19698
+ forwardTokens,
19699
+ payProtocolFeeAndMintGCTLAndStake,
19700
+ payProtocolFee,
19701
+ mintGCTLAndStake,
19702
+ mintGCTL,
19703
+ buySolarFarm,
19704
+ // Token operations
19705
+ approveToken,
19706
+ checkTokenAllowance,
19707
+ checkTokenBalance,
19708
+ // Utility methods
19709
+ estimateGasForForward,
19710
+ mintTestUSDC,
19711
+ constructForwardMessage,
19712
+ // State
19713
+ get isProcessing() {
19714
+ return isProcessing;
19715
+ },
19716
+ addresses: ADDRESSES,
19717
+ // Signer availability
19718
+ isSignerAvailable: !!signer,
19719
+ };
19720
+ }
19721
+
19169
19722
  exports.GENESIS_TIMESTAMP = GENESIS_TIMESTAMP;
19170
19723
  exports.createWeeklyReport = createWeeklyReport;
19171
19724
  exports.createWeeklyReportLegacy = createWeeklyReportLegacy;
19725
+ exports.useForwarder = useForwarder;
19172
19726
  //# sourceMappingURL=index.js.map