Beta 7 with some repo names changed.

This commit is contained in:
Luis Fernando Molina committed 2020-11-15 13:05:19 +01:00
1 parent 0f7b40cca7
commit 963c19493a
3408 files changed
+462217 -15516

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
export const version = "web/5.0.9";
//# sourceMappingURL=_version.js.map
+48
View File
@@ -0,0 +1,48 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { arrayify } from "@ethersproject/bytes";
export function getUrl(href, options) {
return __awaiter(this, void 0, void 0, function* () {
if (options == null) {
options = {};
}
const request = {
method: (options.method || "GET"),
headers: (options.headers || {}),
body: (options.body || undefined),
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
redirect: "follow",
referrer: "client",
};
const response = yield fetch(href, request);
const body = yield response.arrayBuffer();
const headers = {};
if (response.headers.forEach) {
response.headers.forEach((value, key) => {
headers[key.toLowerCase()] = value;
});
}
else {
((response.headers).keys)().forEach((key) => {
headers[key.toLowerCase()] = response.headers.get(key);
});
}
return {
headers: headers,
statusCode: response.status,
statusMessage: response.statusText,
body: arrayify(new Uint8Array(body)),
};
});
}
//# sourceMappingURL=browser-geturl.js.map
+110
View File
@@ -0,0 +1,110 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import http from "http";
import https from "https";
import { gunzipSync } from "zlib";
import { parse } from "url";
import { arrayify, concat } from "@ethersproject/bytes";
import { shallowCopy } from "@ethersproject/properties";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
function getResponse(request) {
return new Promise((resolve, reject) => {
request.once("response", (resp) => {
const response = {
statusCode: resp.statusCode,
statusMessage: resp.statusMessage,
headers: Object.keys(resp.headers).reduce((accum, name) => {
let value = resp.headers[name];
if (Array.isArray(value)) {
value = value.join(", ");
}
accum[name] = value;
return accum;
}, {}),
body: null
};
//resp.setEncoding("utf8");
resp.on("data", (chunk) => {
if (response.body == null) {
response.body = new Uint8Array(0);
}
response.body = concat([response.body, chunk]);
});
resp.on("end", () => {
if (response.headers["content-encoding"] === "gzip") {
//const size = response.body.length;
response.body = arrayify(gunzipSync(response.body));
//console.log("Delta:", response.body.length - size, Buffer.from(response.body).toString());
}
resolve(response);
});
resp.on("error", (error) => {
/* istanbul ignore next */
error.response = response;
reject(error);
});
});
request.on("error", (error) => { reject(error); });
});
}
// The URL.parse uses null instead of the empty string
function nonnull(value) {
if (value == null) {
return "";
}
return value;
}
export function getUrl(href, options) {
return __awaiter(this, void 0, void 0, function* () {
if (options == null) {
options = {};
}
// @TODO: Once we drop support for node 8, we can pass the href
// firectly into request and skip adding the components
// to this request object
const url = parse(href);
const request = {
protocol: nonnull(url.protocol),
hostname: nonnull(url.hostname),
port: nonnull(url.port),
path: (nonnull(url.pathname) + nonnull(url.search)),
method: (options.method || "GET"),
headers: shallowCopy(options.headers || {}),
};
if (options.allowGzip) {
request.headers["accept-encoding"] = "gzip";
}
let req = null;
switch (nonnull(url.protocol)) {
case "http:":
req = http.request(request);
break;
case "https:":
req = https.request(request);
break;
default:
/* istanbul ignore next */
logger.throwError(`unsupported protocol ${url.protocol}`, Logger.errors.UNSUPPORTED_OPERATION, {
protocol: url.protocol,
operation: "request"
});
}
if (options.body) {
req.write(Buffer.from(options.body));
}
req.end();
const response = yield getResponse(req);
return response;
});
}
//# sourceMappingURL=geturl.js.map
+356
View File
@@ -0,0 +1,356 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { encode as base64Encode } from "@ethersproject/base64";
import { hexlify, isBytesLike } from "@ethersproject/bytes";
import { shallowCopy } from "@ethersproject/properties";
import { toUtf8Bytes, toUtf8String } from "@ethersproject/strings";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
import { getUrl } from "./geturl";
function staller(duration) {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}
function bodyify(value, type) {
if (value == null) {
return null;
}
if (typeof (value) === "string") {
return value;
}
if (isBytesLike(value)) {
if (type && (type.split("/")[0] === "text" || type.split(";")[0].trim() === "application/json")) {
try {
return toUtf8String(value);
}
catch (error) { }
;
}
return hexlify(value);
}
return value;
}
// This API is still a work in progress; the future changes will likely be:
// - ConnectionInfo => FetchDataRequest<T = any>
// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }
// - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified)
// - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T
// For this reason, it should be considered internal until the API is finalized
export function _fetchData(connection, body, processFunc) {
// How many times to retry in the event of a throttle
const attemptLimit = (typeof (connection) === "object" && connection.throttleLimit != null) ? connection.throttleLimit : 12;
logger.assertArgument((attemptLimit > 0 && (attemptLimit % 1) === 0), "invalid connection throttle limit", "connection.throttleLimit", attemptLimit);
const throttleCallback = ((typeof (connection) === "object") ? connection.throttleCallback : null);
const throttleSlotInterval = ((typeof (connection) === "object" && typeof (connection.throttleSlotInterval) === "number") ? connection.throttleSlotInterval : 100);
logger.assertArgument((throttleSlotInterval > 0 && (throttleSlotInterval % 1) === 0), "invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval);
const headers = {};
let url = null;
// @TODO: Allow ConnectionInfo to override some of these values
const options = {
method: "GET",
};
let allow304 = false;
let timeout = 2 * 60 * 1000;
if (typeof (connection) === "string") {
url = connection;
}
else if (typeof (connection) === "object") {
if (connection == null || connection.url == null) {
logger.throwArgumentError("missing URL", "connection.url", connection);
}
url = connection.url;
if (typeof (connection.timeout) === "number" && connection.timeout > 0) {
timeout = connection.timeout;
}
if (connection.headers) {
for (const key in connection.headers) {
headers[key.toLowerCase()] = { key: key, value: String(connection.headers[key]) };
if (["if-none-match", "if-modified-since"].indexOf(key.toLowerCase()) >= 0) {
allow304 = true;
}
}
}
options.allowGzip = !!connection.allowGzip;
if (connection.user != null && connection.password != null) {
if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) {
logger.throwError("basic authentication requires a secure https url", Logger.errors.INVALID_ARGUMENT, { argument: "url", url: url, user: connection.user, password: "[REDACTED]" });
}
const authorization = connection.user + ":" + connection.password;
headers["authorization"] = {
key: "Authorization",
value: "Basic " + base64Encode(toUtf8Bytes(authorization))
};
}
}
if (body) {
options.method = "POST";
options.body = body;
if (headers["content-type"] == null) {
headers["content-type"] = { key: "Content-Type", value: "application/octet-stream" };
}
if (headers["content-length"] == null) {
headers["content-length"] = { key: "Content-Length", value: String(body.length) };
}
}
const flatHeaders = {};
Object.keys(headers).forEach((key) => {
const header = headers[key];
flatHeaders[header.key] = header.value;
});
options.headers = flatHeaders;
const runningTimeout = (function () {
let timer = null;
const promise = new Promise(function (resolve, reject) {
if (timeout) {
timer = setTimeout(() => {
if (timer == null) {
return;
}
timer = null;
reject(logger.makeError("timeout", Logger.errors.TIMEOUT, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
timeout: timeout,
url: url
}));
}, timeout);
}
});
const cancel = function () {
if (timer == null) {
return;
}
clearTimeout(timer);
timer = null;
};
return { promise, cancel };
})();
const runningFetch = (function () {
return __awaiter(this, void 0, void 0, function* () {
for (let attempt = 0; attempt < attemptLimit; attempt++) {
let response = null;
try {
response = yield getUrl(url, options);
// Exponential back-off throttling
if (response.statusCode === 429 && attempt < attemptLimit) {
let tryAgain = true;
if (throttleCallback) {
tryAgain = yield throttleCallback(attempt, url);
}
if (tryAgain) {
let stall = 0;
const retryAfter = response.headers["retry-after"];
if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
stall = parseInt(retryAfter) * 1000;
}
else {
stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
}
//console.log("Stalling 429");
yield staller(stall);
continue;
}
}
}
catch (error) {
response = error.response;
if (response == null) {
runningTimeout.cancel();
logger.throwError("missing response", Logger.errors.SERVER_ERROR, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
serverError: error,
url: url
});
}
}
let body = response.body;
if (allow304 && response.statusCode === 304) {
body = null;
}
else if (response.statusCode < 200 || response.statusCode >= 300) {
runningTimeout.cancel();
logger.throwError("bad response", Logger.errors.SERVER_ERROR, {
status: response.statusCode,
headers: response.headers,
body: bodyify(body, ((response.headers) ? response.headers["content-type"] : null)),
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
});
}
if (processFunc) {
try {
const result = yield processFunc(body, response);
runningTimeout.cancel();
return result;
}
catch (error) {
// Allow the processFunc to trigger a throttle
if (error.throttleRetry && attempt < attemptLimit) {
let tryAgain = true;
if (throttleCallback) {
tryAgain = yield throttleCallback(attempt, url);
}
if (tryAgain) {
const timeout = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
//console.log("Stalling callback");
yield staller(timeout);
continue;
}
}
runningTimeout.cancel();
logger.throwError("processing response error", Logger.errors.SERVER_ERROR, {
body: bodyify(body, ((response.headers) ? response.headers["content-type"] : null)),
error: error,
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
});
}
}
runningTimeout.cancel();
// If we had a processFunc, it eitehr returned a T or threw above.
// The "body" is now a Uint8Array.
return body;
}
return logger.throwError("failed response", Logger.errors.SERVER_ERROR, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
});
});
})();
return Promise.race([runningTimeout.promise, runningFetch]);
}
export function fetchJson(connection, json, processFunc) {
let processJsonFunc = (value, response) => {
let result = null;
if (value != null) {
try {
result = JSON.parse(toUtf8String(value));
}
catch (error) {
logger.throwError("invalid JSON", Logger.errors.SERVER_ERROR, {
body: value,
error: error
});
}
}
if (processFunc) {
result = processFunc(result, response);
}
return result;
};
// If we have json to send, we must
// - add content-type of application/json (unless already overridden)
// - convert the json to bytes
let body = null;
if (json != null) {
body = toUtf8Bytes(json);
// Create a connection with the content-type set for JSON
const updated = (typeof (connection) === "string") ? ({ url: connection }) : shallowCopy(connection);
if (updated.headers) {
const hasContentType = (Object.keys(updated.headers).filter((k) => (k.toLowerCase() === "content-type")).length) !== 0;
if (!hasContentType) {
updated.headers = shallowCopy(updated.headers);
updated.headers["content-type"] = "application/json";
}
}
else {
updated.headers = { "content-type": "application/json" };
}
connection = updated;
}
return _fetchData(connection, body, processJsonFunc);
}
export function poll(func, options) {
if (!options) {
options = {};
}
options = shallowCopy(options);
if (options.floor == null) {
options.floor = 0;
}
if (options.ceiling == null) {
options.ceiling = 10000;
}
if (options.interval == null) {
options.interval = 250;
}
return new Promise(function (resolve, reject) {
let timer = null;
let done = false;
// Returns true if cancel was successful. Unsuccessful cancel means we're already done.
const cancel = () => {
if (done) {
return false;
}
done = true;
if (timer) {
clearTimeout(timer);
}
return true;
};
if (options.timeout) {
timer = setTimeout(() => {
if (cancel()) {
reject(new Error("timeout"));
}
}, options.timeout);
}
const retryLimit = options.retryLimit;
let attempt = 0;
function check() {
return func().then(function (result) {
// If we have a result, or are allowed null then we're done
if (result !== undefined) {
if (cancel()) {
resolve(result);
}
}
else if (options.oncePoll) {
options.oncePoll.once("poll", check);
}
else if (options.onceBlock) {
options.onceBlock.once("block", check);
// Otherwise, exponential back-off (up to 10s) our next request
}
else if (!done) {
attempt++;
if (attempt > retryLimit) {
if (cancel()) {
reject(new Error("retry limit reached"));
}
return;
}
let timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt)));
if (timeout < options.floor) {
timeout = options.floor;
}
if (timeout > options.ceiling) {
timeout = options.ceiling;
}
setTimeout(check, timeout);
}
return null;
}, function (error) {
if (cancel()) {
reject(error);
}
});
}
check();
});
}
//# sourceMappingURL=index.js.map
+2
View File
@@ -0,0 +1,2 @@
"use strict";
//# sourceMappingURL=types.js.map
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = "web/5.0.9";
//# sourceMappingURL=_version.js.map
+87
View File
@@ -0,0 +1,87 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var bytes_1 = require("@ethersproject/bytes");
function getUrl(href, options) {
return __awaiter(this, void 0, void 0, function () {
var request, response, body, headers;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (options == null) {
options = {};
}
request = {
method: (options.method || "GET"),
headers: (options.headers || {}),
body: (options.body || undefined),
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
redirect: "follow",
referrer: "client",
};
return [4 /*yield*/, fetch(href, request)];
case 1:
response = _a.sent();
return [4 /*yield*/, response.arrayBuffer()];
case 2:
body = _a.sent();
headers = {};
if (response.headers.forEach) {
response.headers.forEach(function (value, key) {
headers[key.toLowerCase()] = value;
});
}
else {
((response.headers).keys)().forEach(function (key) {
headers[key.toLowerCase()] = response.headers.get(key);
});
}
return [2 /*return*/, {
headers: headers,
statusCode: response.status,
statusMessage: response.statusText,
body: bytes_1.arrayify(new Uint8Array(body)),
}];
}
});
});
}
exports.getUrl = getUrl;
//# sourceMappingURL=browser-geturl.js.map
+147
View File
@@ -0,0 +1,147 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var http_1 = __importDefault(require("http"));
var https_1 = __importDefault(require("https"));
var zlib_1 = require("zlib");
var url_1 = require("url");
var bytes_1 = require("@ethersproject/bytes");
var properties_1 = require("@ethersproject/properties");
var logger_1 = require("@ethersproject/logger");
var _version_1 = require("./_version");
var logger = new logger_1.Logger(_version_1.version);
function getResponse(request) {
return new Promise(function (resolve, reject) {
request.once("response", function (resp) {
var response = {
statusCode: resp.statusCode,
statusMessage: resp.statusMessage,
headers: Object.keys(resp.headers).reduce(function (accum, name) {
var value = resp.headers[name];
if (Array.isArray(value)) {
value = value.join(", ");
}
accum[name] = value;
return accum;
}, {}),
body: null
};
//resp.setEncoding("utf8");
resp.on("data", function (chunk) {
if (response.body == null) {
response.body = new Uint8Array(0);
}
response.body = bytes_1.concat([response.body, chunk]);
});
resp.on("end", function () {
if (response.headers["content-encoding"] === "gzip") {
//const size = response.body.length;
response.body = bytes_1.arrayify(zlib_1.gunzipSync(response.body));
//console.log("Delta:", response.body.length - size, Buffer.from(response.body).toString());
}
resolve(response);
});
resp.on("error", function (error) {
/* istanbul ignore next */
error.response = response;
reject(error);
});
});
request.on("error", function (error) { reject(error); });
});
}
// The URL.parse uses null instead of the empty string
function nonnull(value) {
if (value == null) {
return "";
}
return value;
}
function getUrl(href, options) {
return __awaiter(this, void 0, void 0, function () {
var url, request, req, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (options == null) {
options = {};
}
url = url_1.parse(href);
request = {
protocol: nonnull(url.protocol),
hostname: nonnull(url.hostname),
port: nonnull(url.port),
path: (nonnull(url.pathname) + nonnull(url.search)),
method: (options.method || "GET"),
headers: properties_1.shallowCopy(options.headers || {}),
};
if (options.allowGzip) {
request.headers["accept-encoding"] = "gzip";
}
req = null;
switch (nonnull(url.protocol)) {
case "http:":
req = http_1.default.request(request);
break;
case "https:":
req = https_1.default.request(request);
break;
default:
/* istanbul ignore next */
logger.throwError("unsupported protocol " + url.protocol, logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
protocol: url.protocol,
operation: "request"
});
}
if (options.body) {
req.write(Buffer.from(options.body));
}
req.end();
return [4 /*yield*/, getResponse(req)];
case 1:
response = _a.sent();
return [2 /*return*/, response];
}
});
});
}
exports.getUrl = getUrl;
//# sourceMappingURL=geturl.js.map
+415
View File
@@ -0,0 +1,415 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var base64_1 = require("@ethersproject/base64");
var bytes_1 = require("@ethersproject/bytes");
var properties_1 = require("@ethersproject/properties");
var strings_1 = require("@ethersproject/strings");
var logger_1 = require("@ethersproject/logger");
var _version_1 = require("./_version");
var logger = new logger_1.Logger(_version_1.version);
var geturl_1 = require("./geturl");
function staller(duration) {
return new Promise(function (resolve) {
setTimeout(resolve, duration);
});
}
function bodyify(value, type) {
if (value == null) {
return null;
}
if (typeof (value) === "string") {
return value;
}
if (bytes_1.isBytesLike(value)) {
if (type && (type.split("/")[0] === "text" || type.split(";")[0].trim() === "application/json")) {
try {
return strings_1.toUtf8String(value);
}
catch (error) { }
;
}
return bytes_1.hexlify(value);
}
return value;
}
// This API is still a work in progress; the future changes will likely be:
// - ConnectionInfo => FetchDataRequest<T = any>
// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }
// - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified)
// - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T
// For this reason, it should be considered internal until the API is finalized
function _fetchData(connection, body, processFunc) {
// How many times to retry in the event of a throttle
var attemptLimit = (typeof (connection) === "object" && connection.throttleLimit != null) ? connection.throttleLimit : 12;
logger.assertArgument((attemptLimit > 0 && (attemptLimit % 1) === 0), "invalid connection throttle limit", "connection.throttleLimit", attemptLimit);
var throttleCallback = ((typeof (connection) === "object") ? connection.throttleCallback : null);
var throttleSlotInterval = ((typeof (connection) === "object" && typeof (connection.throttleSlotInterval) === "number") ? connection.throttleSlotInterval : 100);
logger.assertArgument((throttleSlotInterval > 0 && (throttleSlotInterval % 1) === 0), "invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval);
var headers = {};
var url = null;
// @TODO: Allow ConnectionInfo to override some of these values
var options = {
method: "GET",
};
var allow304 = false;
var timeout = 2 * 60 * 1000;
if (typeof (connection) === "string") {
url = connection;
}
else if (typeof (connection) === "object") {
if (connection == null || connection.url == null) {
logger.throwArgumentError("missing URL", "connection.url", connection);
}
url = connection.url;
if (typeof (connection.timeout) === "number" && connection.timeout > 0) {
timeout = connection.timeout;
}
if (connection.headers) {
for (var key in connection.headers) {
headers[key.toLowerCase()] = { key: key, value: String(connection.headers[key]) };
if (["if-none-match", "if-modified-since"].indexOf(key.toLowerCase()) >= 0) {
allow304 = true;
}
}
}
options.allowGzip = !!connection.allowGzip;
if (connection.user != null && connection.password != null) {
if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) {
logger.throwError("basic authentication requires a secure https url", logger_1.Logger.errors.INVALID_ARGUMENT, { argument: "url", url: url, user: connection.user, password: "[REDACTED]" });
}
var authorization = connection.user + ":" + connection.password;
headers["authorization"] = {
key: "Authorization",
value: "Basic " + base64_1.encode(strings_1.toUtf8Bytes(authorization))
};
}
}
if (body) {
options.method = "POST";
options.body = body;
if (headers["content-type"] == null) {
headers["content-type"] = { key: "Content-Type", value: "application/octet-stream" };
}
if (headers["content-length"] == null) {
headers["content-length"] = { key: "Content-Length", value: String(body.length) };
}
}
var flatHeaders = {};
Object.keys(headers).forEach(function (key) {
var header = headers[key];
flatHeaders[header.key] = header.value;
});
options.headers = flatHeaders;
var runningTimeout = (function () {
var timer = null;
var promise = new Promise(function (resolve, reject) {
if (timeout) {
timer = setTimeout(function () {
if (timer == null) {
return;
}
timer = null;
reject(logger.makeError("timeout", logger_1.Logger.errors.TIMEOUT, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
timeout: timeout,
url: url
}));
}, timeout);
}
});
var cancel = function () {
if (timer == null) {
return;
}
clearTimeout(timer);
timer = null;
};
return { promise: promise, cancel: cancel };
})();
var runningFetch = (function () {
return __awaiter(this, void 0, void 0, function () {
var attempt, response, tryAgain, stall, retryAfter, error_1, body_1, result, error_2, tryAgain, timeout_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
attempt = 0;
_a.label = 1;
case 1:
if (!(attempt < attemptLimit)) return [3 /*break*/, 19];
response = null;
_a.label = 2;
case 2:
_a.trys.push([2, 8, , 9]);
return [4 /*yield*/, geturl_1.getUrl(url, options)];
case 3:
response = _a.sent();
if (!(response.statusCode === 429 && attempt < attemptLimit)) return [3 /*break*/, 7];
tryAgain = true;
if (!throttleCallback) return [3 /*break*/, 5];
return [4 /*yield*/, throttleCallback(attempt, url)];
case 4:
tryAgain = _a.sent();
_a.label = 5;
case 5:
if (!tryAgain) return [3 /*break*/, 7];
stall = 0;
retryAfter = response.headers["retry-after"];
if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
stall = parseInt(retryAfter) * 1000;
}
else {
stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
}
//console.log("Stalling 429");
return [4 /*yield*/, staller(stall)];
case 6:
//console.log("Stalling 429");
_a.sent();
return [3 /*break*/, 18];
case 7: return [3 /*break*/, 9];
case 8:
error_1 = _a.sent();
response = error_1.response;
if (response == null) {
runningTimeout.cancel();
logger.throwError("missing response", logger_1.Logger.errors.SERVER_ERROR, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
serverError: error_1,
url: url
});
}
return [3 /*break*/, 9];
case 9:
body_1 = response.body;
if (allow304 && response.statusCode === 304) {
body_1 = null;
}
else if (response.statusCode < 200 || response.statusCode >= 300) {
runningTimeout.cancel();
logger.throwError("bad response", logger_1.Logger.errors.SERVER_ERROR, {
status: response.statusCode,
headers: response.headers,
body: bodyify(body_1, ((response.headers) ? response.headers["content-type"] : null)),
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
});
}
if (!processFunc) return [3 /*break*/, 17];
_a.label = 10;
case 10:
_a.trys.push([10, 12, , 17]);
return [4 /*yield*/, processFunc(body_1, response)];
case 11:
result = _a.sent();
runningTimeout.cancel();
return [2 /*return*/, result];
case 12:
error_2 = _a.sent();
if (!(error_2.throttleRetry && attempt < attemptLimit)) return [3 /*break*/, 16];
tryAgain = true;
if (!throttleCallback) return [3 /*break*/, 14];
return [4 /*yield*/, throttleCallback(attempt, url)];
case 13:
tryAgain = _a.sent();
_a.label = 14;
case 14:
if (!tryAgain) return [3 /*break*/, 16];
timeout_1 = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
//console.log("Stalling callback");
return [4 /*yield*/, staller(timeout_1)];
case 15:
//console.log("Stalling callback");
_a.sent();
return [3 /*break*/, 18];
case 16:
runningTimeout.cancel();
logger.throwError("processing response error", logger_1.Logger.errors.SERVER_ERROR, {
body: bodyify(body_1, ((response.headers) ? response.headers["content-type"] : null)),
error: error_2,
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
});
return [3 /*break*/, 17];
case 17:
runningTimeout.cancel();
// If we had a processFunc, it eitehr returned a T or threw above.
// The "body" is now a Uint8Array.
return [2 /*return*/, body_1];
case 18:
attempt++;
return [3 /*break*/, 1];
case 19: return [2 /*return*/, logger.throwError("failed response", logger_1.Logger.errors.SERVER_ERROR, {
requestBody: bodyify(options.body, flatHeaders["content-type"]),
requestMethod: options.method,
url: url
})];
}
});
});
})();
return Promise.race([runningTimeout.promise, runningFetch]);
}
exports._fetchData = _fetchData;
function fetchJson(connection, json, processFunc) {
var processJsonFunc = function (value, response) {
var result = null;
if (value != null) {
try {
result = JSON.parse(strings_1.toUtf8String(value));
}
catch (error) {
logger.throwError("invalid JSON", logger_1.Logger.errors.SERVER_ERROR, {
body: value,
error: error
});
}
}
if (processFunc) {
result = processFunc(result, response);
}
return result;
};
// If we have json to send, we must
// - add content-type of application/json (unless already overridden)
// - convert the json to bytes
var body = null;
if (json != null) {
body = strings_1.toUtf8Bytes(json);
// Create a connection with the content-type set for JSON
var updated = (typeof (connection) === "string") ? ({ url: connection }) : properties_1.shallowCopy(connection);
if (updated.headers) {
var hasContentType = (Object.keys(updated.headers).filter(function (k) { return (k.toLowerCase() === "content-type"); }).length) !== 0;
if (!hasContentType) {
updated.headers = properties_1.shallowCopy(updated.headers);
updated.headers["content-type"] = "application/json";
}
}
else {
updated.headers = { "content-type": "application/json" };
}
connection = updated;
}
return _fetchData(connection, body, processJsonFunc);
}
exports.fetchJson = fetchJson;
function poll(func, options) {
if (!options) {
options = {};
}
options = properties_1.shallowCopy(options);
if (options.floor == null) {
options.floor = 0;
}
if (options.ceiling == null) {
options.ceiling = 10000;
}
if (options.interval == null) {
options.interval = 250;
}
return new Promise(function (resolve, reject) {
var timer = null;
var done = false;
// Returns true if cancel was successful. Unsuccessful cancel means we're already done.
var cancel = function () {
if (done) {
return false;
}
done = true;
if (timer) {
clearTimeout(timer);
}
return true;
};
if (options.timeout) {
timer = setTimeout(function () {
if (cancel()) {
reject(new Error("timeout"));
}
}, options.timeout);
}
var retryLimit = options.retryLimit;
var attempt = 0;
function check() {
return func().then(function (result) {
// If we have a result, or are allowed null then we're done
if (result !== undefined) {
if (cancel()) {
resolve(result);
}
}
else if (options.oncePoll) {
options.oncePoll.once("poll", check);
}
else if (options.onceBlock) {
options.onceBlock.once("block", check);
// Otherwise, exponential back-off (up to 10s) our next request
}
else if (!done) {
attempt++;
if (attempt > retryLimit) {
if (cancel()) {
reject(new Error("retry limit reached"));
}
return;
}
var timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt)));
if (timeout < options.floor) {
timeout = options.floor;
}
if (timeout > options.ceiling) {
timeout = options.ceiling;
}
setTimeout(check, timeout);
}
return null;
}, function (error) {
if (cancel()) {
reject(error);
}
});
}
check();
});
}
exports.poll = poll;
//# sourceMappingURL=index.js.map
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
+76
View File
@@ -0,0 +1,76 @@
{
"_from": "@ethersproject/web@^5.0.6",
"_id": "@ethersproject/web@5.0.9",
"_inBundle": false,
"_integrity": "sha512-//QNlv1MSkOII1hv3+HQwWoiVFS+BMVGI0KYeUww4cyrEktnx1QIez5bTSab9s9fWTFaWKNmQNBwMbxAqPuYDw==",
"_location": "/@ethersproject/web",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@ethersproject/web@^5.0.6",
"name": "@ethersproject/web",
"escapedName": "@ethersproject%2fweb",
"scope": "@ethersproject",
"rawSpec": "^5.0.6",
"saveSpec": null,
"fetchSpec": "^5.0.6"
},
"_requiredBy": [
"/@ethersproject/abstract-provider"
],
"_resolved": "https://registry.npmjs.org/@ethersproject/web/-/web-5.0.9.tgz",
"_shasum": "b08f8295f4bfd4777c8723fe9572f5453b9f03cb",
"_spec": "@ethersproject/web@^5.0.6",
"_where": "C:\\Users\\Luis\\source\\repos\\AAMasters\\BackendServers\\node_modules\\@ethersproject\\abstract-provider",
"author": {
"name": "Richard Moore",
"email": "me@ricmoo.com"
},
"browser": {
"./lib/geturl": "./lib/browser-geturl.js"
},
"browser.esm": {
"./lib.esm/geturl": "./lib.esm/browser-geturl.js"
},
"browser.umd": {
"./lib/geturl": "./lib/browser-geturl.js"
},
"bugs": {
"url": "https://github.com/ethers-io/ethers.js/issues"
},
"bundleDependencies": false,
"dependencies": {
"@ethersproject/base64": "^5.0.3",
"@ethersproject/bytes": "^5.0.4",
"@ethersproject/logger": "^5.0.5",
"@ethersproject/properties": "^5.0.3",
"@ethersproject/strings": "^5.0.4"
},
"deprecated": false,
"description": "Utility fucntions for managing web requests for ethers.",
"ethereum": "donations.ethers.eth",
"gitHead": "d78b7a39983273a7758399fee33f1b33ec368144",
"homepage": "https://github.com/ethers-io/ethers.js#readme",
"keywords": [
"Ethereum",
"ethers"
],
"license": "MIT",
"main": "./lib/index.js",
"module": "./lib.esm/index.js",
"name": "@ethersproject/web",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git://github.com/ethers-io/ethers.js.git"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"tarballHash": "0xffb63ec25a04effef1c5201b55770f2636a338339be2a7b770cc5e8914a6d56b",
"types": "./lib/index.d.ts",
"version": "5.0.9"
}