@apify/utilities 2.10.4 → 2.10.6

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/cjs/index.cjs CHANGED
@@ -28,10 +28,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  mod
29
29
  ));
30
30
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
- var __publicField = (obj, key, value) => {
32
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
33
- return value;
34
- };
31
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
35
32
 
36
33
  // src/index.ts
37
34
  var src_exports = {};
@@ -95,8 +92,8 @@ module.exports = __toCommonJS(src_exports);
95
92
 
96
93
  // src/utilities.ts
97
94
  var import_crypto = __toESM(require("crypto"));
98
- var import_log = __toESM(require("@apify/log"));
99
95
  var import_consts = require("@apify/consts");
96
+ var import_log = __toESM(require("@apify/log"));
100
97
  function cryptoRandomObjectId(length = 17) {
101
98
  const chars = "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ0123456789";
102
99
  const bytes = import_crypto.default.randomBytes(length);
@@ -123,7 +120,7 @@ function parseDateFromJson(date) {
123
120
  return date;
124
121
  }
125
122
  __name(parseDateFromJson, "parseDateFromJson");
126
- function delayPromise(millis) {
123
+ async function delayPromise(millis) {
127
124
  return new Promise((resolve) => {
128
125
  if (millis > 0) {
129
126
  setTimeout(() => resolve(), millis);
@@ -164,8 +161,7 @@ function betterSetInterval(func, delay) {
164
161
  func(callback);
165
162
  }, "funcWrapper");
166
163
  callback = /* @__PURE__ */ __name(function() {
167
- if (isRunning)
168
- timeoutId = setTimeout(funcWrapper, delay);
164
+ if (isRunning) timeoutId = setTimeout(funcWrapper, delay);
169
165
  }, "callback");
170
166
  funcWrapper();
171
167
  return {
@@ -193,8 +189,7 @@ __name(escapeRegExp, "escapeRegExp");
193
189
  function leftpad(str, len, ch = " ") {
194
190
  str = String(str);
195
191
  let i = -1;
196
- if (!ch && ch !== 0)
197
- ch = " ";
192
+ if (!ch && ch !== 0) ch = " ";
198
193
  len -= str.length;
199
194
  while (++i < len) {
200
195
  str = ch + str;
@@ -1022,8 +1017,7 @@ function isForbiddenUsername(username) {
1022
1017
  }
1023
1018
  __name(isForbiddenUsername, "isForbiddenUsername");
1024
1019
  async function sequentializePromises(promises) {
1025
- if (!promises.length)
1026
- return [];
1020
+ if (!promises.length) return [];
1027
1021
  const results = [];
1028
1022
  for (const promiseOrFunc of promises) {
1029
1023
  const promise = promiseOrFunc instanceof Function ? promiseOrFunc() : promiseOrFunc;
@@ -1033,15 +1027,13 @@ async function sequentializePromises(promises) {
1033
1027
  }
1034
1028
  __name(sequentializePromises, "sequentializePromises");
1035
1029
  function checkParamPrototypeOrThrow(paramVal, paramName, prototypes, prototypeName, isOptional = false) {
1036
- if (isOptional && (paramVal === void 0 || paramVal === null))
1037
- return;
1030
+ if (isOptional && (paramVal === void 0 || paramVal === null)) return;
1038
1031
  const hasCorrectPrototype = prototypes instanceof Array ? prototypes.some((prototype) => paramVal instanceof prototype) : paramVal instanceof prototypes;
1039
- if (!hasCorrectPrototype)
1040
- throw new Error(`Parameter "${paramName}" must be an instance of ${prototypeName}`);
1032
+ if (!hasCorrectPrototype) throw new Error(`Parameter "${paramName}" must be an instance of ${prototypeName}`);
1041
1033
  }
1042
1034
  __name(checkParamPrototypeOrThrow, "checkParamPrototypeOrThrow");
1043
1035
  function promisifyServerListen(server) {
1044
- return (port) => {
1036
+ return async (port) => {
1045
1037
  return new Promise((resolve, reject) => {
1046
1038
  const onError = /* @__PURE__ */ __name((err) => {
1047
1039
  removeListeners();
@@ -1073,17 +1065,15 @@ function configureLogger(givenLog, isProduction) {
1073
1065
  }
1074
1066
  }
1075
1067
  __name(configureLogger, "configureLogger");
1076
- function timeoutPromise(promise, timeoutMillis, errorMessage = "Promise has timed-out") {
1068
+ async function timeoutPromise(promise, timeoutMillis, errorMessage = "Promise has timed-out") {
1077
1069
  return new Promise((resolve, reject) => {
1078
1070
  let timeout;
1079
1071
  let hasFulfilled = false;
1080
1072
  const callback = /* @__PURE__ */ __name((err, result) => {
1081
- if (hasFulfilled)
1082
- return;
1073
+ if (hasFulfilled) return;
1083
1074
  clearTimeout(timeout);
1084
1075
  hasFulfilled = true;
1085
- if (err)
1086
- return reject(err);
1076
+ if (err) return reject(err);
1087
1077
  resolve(result);
1088
1078
  }, "callback");
1089
1079
  promise.then((result) => callback(null, result), callback);
@@ -1138,8 +1128,7 @@ function getOrdinalSuffix(num) {
1138
1128
  }
1139
1129
  __name(getOrdinalSuffix, "getOrdinalSuffix");
1140
1130
  function parseUrl(str) {
1141
- if (typeof str !== "string")
1142
- return {};
1131
+ if (typeof str !== "string") return {};
1143
1132
  const o = {
1144
1133
  strictMode: false,
1145
1134
  key: [
@@ -1172,18 +1161,15 @@ function parseUrl(str) {
1172
1161
  const m = o.parser[o.strictMode ? "strict" : "loose"].exec(str);
1173
1162
  const uri = {};
1174
1163
  let i = o.key.length;
1175
- while (i--)
1176
- uri[o.key[i]] = m[i] || "";
1164
+ while (i--) uri[o.key[i]] = m[i] || "";
1177
1165
  uri[o.q.name] = {};
1178
1166
  uri[o.key[12]].replace(o.q.parser, ($0, $1, $2) => {
1179
- if ($1)
1180
- uri[o.q.name][$1] = $2;
1167
+ if ($1) uri[o.q.name][$1] = $2;
1181
1168
  });
1182
1169
  uri.fragmentKey = {};
1183
1170
  if (uri.fragment) {
1184
1171
  uri.fragment.replace(o.q.parser, ($0, $1, $2) => {
1185
- if ($1)
1186
- uri.fragmentKey[$1] = $2;
1172
+ if ($1) uri.fragmentKey[$1] = $2;
1187
1173
  });
1188
1174
  }
1189
1175
  return uri;
@@ -1230,15 +1216,13 @@ function markedDecreaseHeadsLevel(text, level) {
1230
1216
  }
1231
1217
  __name(markedDecreaseHeadsLevel, "markedDecreaseHeadsLevel");
1232
1218
  function buildOrVersionNumberIntToStr(int) {
1233
- if (typeof int !== "number" || !(int >= 0))
1234
- return null;
1219
+ if (typeof int !== "number" || !(int >= 0)) return null;
1235
1220
  const major = Math.floor(int / import_consts2.VERSION_INT_MAJOR_BASE);
1236
1221
  const remainder = int % import_consts2.VERSION_INT_MAJOR_BASE;
1237
1222
  const minor = Math.floor(remainder / import_consts2.VERSION_INT_MINOR_BASE);
1238
1223
  const build = remainder % import_consts2.VERSION_INT_MINOR_BASE;
1239
1224
  let str = `${major}.${minor}`;
1240
- if (build > 0)
1241
- str += `.${build}`;
1225
+ if (build > 0) str += `.${build}`;
1242
1226
  return str;
1243
1227
  }
1244
1228
  __name(buildOrVersionNumberIntToStr, "buildOrVersionNumberIntToStr");
@@ -1278,15 +1262,13 @@ function unescapePropertyName(name) {
1278
1262
  }
1279
1263
  __name(unescapePropertyName, "unescapePropertyName");
1280
1264
  function traverseObject(obj, clone, transformFunc) {
1281
- if (obj === null || typeof obj !== "object" || Object.prototype.toString.call(obj) === "[object Date]" || isBuffer(obj))
1282
- return obj;
1265
+ if (obj === null || typeof obj !== "object" || Object.prototype.toString.call(obj) === "[object Date]" || isBuffer(obj)) return obj;
1283
1266
  let result;
1284
1267
  if (Array.isArray(obj)) {
1285
1268
  result = clone ? new Array(obj.length) : obj;
1286
1269
  for (let i = 0; i < obj.length; i++) {
1287
1270
  const val = traverseObject(obj[i], clone, transformFunc);
1288
- if (clone)
1289
- result[i] = val;
1271
+ if (clone) result[i] = val;
1290
1272
  }
1291
1273
  return result;
1292
1274
  }
@@ -1295,12 +1277,10 @@ function traverseObject(obj, clone, transformFunc) {
1295
1277
  const val = traverseObject(obj[key], clone, transformFunc);
1296
1278
  const [transformedKey, transformedVal] = transformFunc(key, val);
1297
1279
  if (key === transformedKey) {
1298
- if (clone || val !== transformedVal)
1299
- result[key] = transformedVal;
1280
+ if (clone || val !== transformedVal) result[key] = transformedVal;
1300
1281
  } else {
1301
1282
  result[transformedKey] = transformedVal;
1302
- if (!clone)
1303
- delete obj[key];
1283
+ if (!clone) delete obj[key];
1304
1284
  }
1305
1285
  }
1306
1286
  return result;
@@ -1326,8 +1306,7 @@ function isBadForMongo(obj) {
1326
1306
  return [key, value];
1327
1307
  });
1328
1308
  } catch (e) {
1329
- if (!isBad)
1330
- throw e;
1309
+ if (!isBad) throw e;
1331
1310
  }
1332
1311
  return isBad;
1333
1312
  }
@@ -1343,13 +1322,11 @@ var _JsonVariable = class _JsonVariable {
1343
1322
  __name(_JsonVariable, "JsonVariable");
1344
1323
  var JsonVariable = _JsonVariable;
1345
1324
  function jsonStringifyExtended(value, replacer, space = 0) {
1346
- if (replacer && !(replacer instanceof Function))
1347
- throw new Error('Parameter "replacer" of jsonStringifyExtended() must be a function!');
1325
+ if (replacer && !(replacer instanceof Function)) throw new Error('Parameter "replacer" of jsonStringifyExtended() must be a function!');
1348
1326
  const replacements = {};
1349
1327
  const extendedReplacer = /* @__PURE__ */ __name((key, val) => {
1350
1328
  val = replacer ? replacer(key, val) : val;
1351
- if (val instanceof Function)
1352
- return val.toString();
1329
+ if (val instanceof Function) return val.toString();
1353
1330
  if (val instanceof JsonVariable) {
1354
1331
  const randomToken = `<<<REPLACEMENT_TOKEN::${Math.random()}>>>`;
1355
1332
  replacements[randomToken] = val.getToken();
@@ -1365,8 +1342,7 @@ function jsonStringifyExtended(value, replacer, space = 0) {
1365
1342
  }
1366
1343
  __name(jsonStringifyExtended, "jsonStringifyExtended");
1367
1344
  function splitFullName(fullName) {
1368
- if (typeof fullName !== "string")
1369
- return [null, null];
1345
+ if (typeof fullName !== "string") return [null, null];
1370
1346
  const names = (fullName || "").trim().split(" ");
1371
1347
  const nonEmptyNames = names.filter((val) => val);
1372
1348
  if (nonEmptyNames.length === 0) {
@@ -1459,8 +1435,7 @@ var _HealthChecker = class _HealthChecker {
1459
1435
  mongoDbWriteTestCollection = "healthCheckPlayground",
1460
1436
  mongoDbWriteTestRemoveOlderThanSecs = 15
1461
1437
  } = options;
1462
- if (!Array.isArray(checks))
1463
- throw new Error('Parameter "check" must be an array');
1438
+ if (!Array.isArray(checks)) throw new Error('Parameter "check" must be an array');
1464
1439
  checks.map((check) => this._validateCheck(check));
1465
1440
  this.checks = checks;
1466
1441
  this.redisPrefix = redisPrefix;
@@ -1481,12 +1456,10 @@ var _HealthChecker = class _HealthChecker {
1481
1456
  }
1482
1457
  }
1483
1458
  _validateCheck(check) {
1484
- if (!(check.type in CHECK_TYPES))
1485
- throw new Error(`Check type "${check.type}" is invalid`);
1486
- if (typeof check.client !== "object")
1487
- throw new Error(`Check client must be an object got "${typeof check.client}" instead`);
1459
+ if (!(check.type in CHECK_TYPES)) throw new Error(`Check type "${check.type}" is invalid`);
1460
+ if (typeof check.client !== "object") throw new Error(`Check client must be an object got "${typeof check.client}" instead`);
1488
1461
  }
1489
- _performCheck(check) {
1462
+ async _performCheck(check) {
1490
1463
  switch (check.type) {
1491
1464
  case "MONGODB_PING" /* MONGODB_PING */:
1492
1465
  return this._testMongoDbPing(check);
@@ -1505,13 +1478,11 @@ var _HealthChecker = class _HealthChecker {
1505
1478
  }
1506
1479
  async _testMongoDbPing({ client }) {
1507
1480
  const response = await client.command({ ping: 1 });
1508
- if (response.ok !== 1)
1509
- throw new Error(`Got ${response.ok} instead of 1!`);
1481
+ if (response.ok !== 1) throw new Error(`Got ${response.ok} instead of 1!`);
1510
1482
  }
1511
1483
  async _testMongoDbRead({ client }) {
1512
1484
  const response = await client.listCollections().toArray();
1513
- if (!Array.isArray(response))
1514
- throw new Error(`Got ${typeof response} instead of an array!`);
1485
+ if (!Array.isArray(response)) throw new Error(`Got ${typeof response} instead of an array!`);
1515
1486
  }
1516
1487
  async _testMongoDbWrite({ client }) {
1517
1488
  const id = cryptoRandomObjectId();
@@ -1526,21 +1497,18 @@ var _HealthChecker = class _HealthChecker {
1526
1497
  createdAt: /* @__PURE__ */ new Date()
1527
1498
  });
1528
1499
  const retrieved = await collection.findOne({ _id: id });
1529
- if (!retrieved)
1530
- throw new Error(`Item with ID "${id}" not found!`);
1500
+ if (!retrieved) throw new Error(`Item with ID "${id}" not found!`);
1531
1501
  }
1532
1502
  async _testRedisPing({ client }) {
1533
1503
  const response = await client.ping();
1534
- if (response !== "PONG")
1535
- throw new Error(`Got "${response}" instead of "PONG"!`);
1504
+ if (response !== "PONG") throw new Error(`Got "${response}" instead of "PONG"!`);
1536
1505
  }
1537
1506
  async _testRedisWrite({ client }) {
1538
1507
  const key = `${this.redisPrefix}:${cryptoRandomObjectId()}`;
1539
1508
  const expected = "OK";
1540
1509
  await client.set(key, expected, "EX", this.redisTtlSecs);
1541
1510
  const given = await client.get(key);
1542
- if (given !== expected)
1543
- throw new Error(`Returned value "${given}" is not equal to "${expected}"!`);
1511
+ if (given !== expected) throw new Error(`Returned value "${given}" is not equal to "${expected}"!`);
1544
1512
  }
1545
1513
  };
1546
1514
  __name(_HealthChecker, "HealthChecker");
@@ -1669,8 +1637,7 @@ var _WebhookPayloadTemplate = class _WebhookPayloadTemplate {
1669
1637
  */
1670
1638
  static parse(payloadTemplate, allowedVariables = null, context = {}, options = {}) {
1671
1639
  const type = typeof payloadTemplate;
1672
- if (type !== "string")
1673
- throw new Error(`Cannot parse a ${type} payload template.`);
1640
+ if (type !== "string") throw new Error(`Cannot parse a ${type} payload template.`);
1674
1641
  const template = new _WebhookPayloadTemplate(payloadTemplate, allowedVariables, context);
1675
1642
  const data = template._parse();
1676
1643
  if (options.interpolateStrings) {
@@ -1685,8 +1652,7 @@ var _WebhookPayloadTemplate = class _WebhookPayloadTemplate {
1685
1652
  */
1686
1653
  static stringify(objectTemplate, replacer, indent = 2) {
1687
1654
  const type = typeof objectTemplate;
1688
- if (!objectTemplate || type !== "object")
1689
- throw new Error(`Cannot stringify a ${type} payload template.`);
1655
+ if (!objectTemplate || type !== "object") throw new Error(`Cannot stringify a ${type} payload template.`);
1690
1656
  return jsonStringifyExtended(objectTemplate, replacer, indent);
1691
1657
  }
1692
1658
  /**
@@ -1772,8 +1738,7 @@ var _WebhookPayloadTemplate = class _WebhookPayloadTemplate {
1772
1738
  const openBraceIndex = this.payload.indexOf("{{", startIndex);
1773
1739
  const closeBraceIndex = this.payload.indexOf("}}", openBraceIndex) + 1;
1774
1740
  const someVariableMaybeExists = openBraceIndex > -1 && closeBraceIndex > -1;
1775
- if (!someVariableMaybeExists)
1776
- return null;
1741
+ if (!someVariableMaybeExists) return null;
1777
1742
  const isInsideString = this._isVariableInsideString(openBraceIndex);
1778
1743
  return { isInsideString, openBraceIndex, closeBraceIndex };
1779
1744
  }
@@ -1801,19 +1766,16 @@ var _WebhookPayloadTemplate = class _WebhookPayloadTemplate {
1801
1766
  this.payload = this.payload.substring(0, openBraceIndex) + replacement + this.payload.substring(closeBraceIndex + 1);
1802
1767
  }
1803
1768
  _validateVariableName(variableName) {
1804
- if (this.allowedVariables === null)
1805
- return;
1769
+ if (this.allowedVariables === null) return;
1806
1770
  const [variable] = variableName.split(".");
1807
1771
  const isVariableValid = this.allowedVariables.has(variable);
1808
- if (!isVariableValid)
1809
- throw new InvalidVariableError(variableName);
1772
+ if (!isVariableValid) throw new InvalidVariableError(variableName);
1810
1773
  }
1811
1774
  _getVariableValue(variableName) {
1812
1775
  const [variable, ...properties] = variableName.split(".");
1813
1776
  const context = this.context[variable];
1814
1777
  const value = properties.reduce((ctx, prop) => {
1815
- if (!ctx || typeof ctx !== "object")
1816
- return null;
1778
+ if (!ctx || typeof ctx !== "object") return null;
1817
1779
  return ctx[prop];
1818
1780
  }, context);
1819
1781
  return value;