UNPKG

coinley-checkout

Version:

A React SDK for Coinley cryptocurrency payment processing with multi-network support

1,535 lines 778 kB
var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __reflectGet = Reflect.get; var __pow = Math.pow; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b2) => { for (var prop in b2 || (b2 = {})) if (__hasOwnProp.call(b2, prop)) __defNormalProp(a, prop, b2[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b2)) { if (__propIsEnum.call(b2, prop)) __defNormalProp(a, prop, b2[prop]); } return a; }; var __spreadProps = (a, b2) => __defProps(a, __getOwnPropDescs(b2)); var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet = (obj, member, getter) => { __accessCheck(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet = (obj, member, value, setter) => { __accessCheck(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateWrapper = (obj, member, setter, getter) => ({ set _(value) { __privateSet(obj, member, value, setter); }, get _() { return __privateGet(obj, member, getter); } }); var __privateMethod = (obj, member, method) => { __accessCheck(obj, member, "access private method"); return method; }; var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; var _listener, _listeners, _cancelled, _allowInsecure, _gzip, _headers, _method, _timeout, _url, _body, _bodyType, _creds, _preflight, _process, _retry, _signal, _throttle, _getUrlFunc, _send, send_fn, _statusCode, _statusMessage, _headers2, _body2, _request, _error, _format, _val, _tens, _checkFormat, checkFormat_fn, _checkValue, checkValue_fn, _add, add_fn, _sub, sub_fn, _mul, mul_fn, _div, div_fn, _names, _data, _dataLength, _writeData, writeData_fn, _data2, _offset, _bytesRead, _parent, _maxInflation, _incrementBytesRead, incrementBytesRead_fn, _peekBytes, peekBytes_fn, _r, _s, _v, _networkV, _privateKey, _options, _type, _to, _data3, _nonce, _gasLimit, _gasPrice, _maxPriorityFeePerGas, _maxFeePerGas, _value, _chainId, _sig, _accessList, _maxFeePerBlobGas, _blobVersionedHashes, _kzg, _blobs, _auths, _getSerialized, getSerialized_fn, _types, _fullTypes, _encoderCache, _getEncoder, getEncoder_fn, _offset2, _tokens, _subTokenString, subTokenString_fn, _walkAsync, walkAsync_fn, _getCoder, getCoder_fn, _errors, _events, _functions, _abiCoder, _getFunction, getFunction_fn, _getEvent, getEvent_fn, _transactions, _logs, _startBlock, _iface, _iface2, _filter, _a, _supports2544, _resolver, _fetch, fetch_fn, _getResolver, getResolver_fn, _url2, _processFunc, _name, _chainId2, _plugins, _provider, _poller, _interval, _blockNumber, _poll, poll_fn, _provider2, _poll2, _running, _tag, _lastBlock, _filter2, _hash, _provider3, _filter3, _poller2, _running2, _blockNumber2, _poll3, poll_fn2, _subs, _plugins2, _pausedState, _destroyed, _networkPromise, _anyNetwork, _performCache, _lastBlockNumber, _nextTimer, _timers, _disableCcipRead, _options2, _perform, perform_fn, _call, call_fn, _checkNetwork, checkNetwork_fn, _getAccountValue, getAccountValue_fn, _getBlock, getBlock_fn, _hasSub, hasSub_fn, _getSub, getSub_fn, _provider4, _filterIdPromise, _poller3, _running3, _network, _hault, _poll4, poll_fn3, _teardown, teardown_fn, _event, _options3, _nextId, _payloads, _drainTimer, _notReady, _network2, _pendingDetectNetwork, _scheduleDrain, scheduleDrain_fn, _pollingInterval, _request2, _providerInfo; import React, { createContext, useContext, useState, useEffect, useRef, forwardRef, useImperativeHandle } from "react"; const styles = ""; const version = "6.14.3"; function checkType(value, type, name) { const types = type.split("|").map((t) => t.trim()); for (let i = 0; i < types.length; i++) { switch (type) { case "any": return; case "bigint": case "boolean": case "number": case "string": if (typeof value === type) { return; } } } const error = new Error(`invalid value for type ${type}`); error.code = "INVALID_ARGUMENT"; error.argument = `value.${name}`; error.value = value; throw error; } function resolveProperties(value) { return __async(this, null, function* () { const keys = Object.keys(value); const results = yield Promise.all(keys.map((k2) => Promise.resolve(value[k2]))); return results.reduce((accum, v, index) => { accum[keys[index]] = v; return accum; }, {}); }); } function defineProperties(target, values, types) { for (let key in values) { let value = values[key]; const type = types ? types[key] : null; if (type) { checkType(value, type, key); } Object.defineProperty(target, key, { enumerable: true, value, writable: false }); } } function stringify(value, seen) { if (value == null) { return "null"; } if (seen == null) { seen = /* @__PURE__ */ new Set(); } if (typeof value === "object") { if (seen.has(value)) { return "[Circular]"; } seen.add(value); } if (Array.isArray(value)) { return "[ " + value.map((v) => stringify(v, seen)).join(", ") + " ]"; } if (value instanceof Uint8Array) { const HEX = "0123456789abcdef"; let result = "0x"; for (let i = 0; i < value.length; i++) { result += HEX[value[i] >> 4]; result += HEX[value[i] & 15]; } return result; } if (typeof value === "object" && typeof value.toJSON === "function") { return stringify(value.toJSON(), seen); } switch (typeof value) { case "boolean": case "number": case "symbol": return value.toString(); case "bigint": return BigInt(value).toString(); case "string": return JSON.stringify(value); case "object": { const keys = Object.keys(value); keys.sort(); return "{ " + keys.map((k2) => `${stringify(k2, seen)}: ${stringify(value[k2], seen)}`).join(", ") + " }"; } } return `[ COULD NOT SERIALIZE ]`; } function isError(error, code) { return error && error.code === code; } function isCallException(error) { return isError(error, "CALL_EXCEPTION"); } function makeError(message, code, info) { let shortMessage = message; { const details = []; if (info) { if ("message" in info || "code" in info || "name" in info) { throw new Error(`value will overwrite populated values: ${stringify(info)}`); } for (const key in info) { if (key === "shortMessage") { continue; } const value = info[key]; details.push(key + "=" + stringify(value)); } } details.push(`code=${code}`); details.push(`version=${version}`); if (details.length) { message += " (" + details.join(", ") + ")"; } } let error; switch (code) { case "INVALID_ARGUMENT": error = new TypeError(message); break; case "NUMERIC_FAULT": case "BUFFER_OVERRUN": error = new RangeError(message); break; default: error = new Error(message); } defineProperties(error, { code }); if (info) { Object.assign(error, info); } if (error.shortMessage == null) { defineProperties(error, { shortMessage }); } return error; } function assert(check, message, code, info) { if (!check) { throw makeError(message, code, info); } } function assertArgument(check, message, name, value) { assert(check, message, "INVALID_ARGUMENT", { argument: name, value }); } function assertArgumentCount(count, expectedCount, message) { if (message == null) { message = ""; } if (message) { message = ": " + message; } assert(count >= expectedCount, "missing argument" + message, "MISSING_ARGUMENT", { count, expectedCount }); assert(count <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", { count, expectedCount }); } const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => { try { if ("test".normalize(form) !== "test") { throw new Error("bad"); } ; if (form === "NFD") { const check = String.fromCharCode(233).normalize("NFD"); const expected = String.fromCharCode(101, 769); if (check !== expected) { throw new Error("broken"); } } accum.push(form); } catch (error) { } return accum; }, []); function assertNormalize(form) { assert(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { operation: "String.prototype.normalize", info: { form } }); } function assertPrivate(givenGuard, guard, className) { if (className == null) { className = ""; } if (givenGuard !== guard) { let method = className, operation = "new"; if (className) { method += "."; operation += " " + className; } assert(false, `private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { operation }); } } function _getBytes(value, name, copy2) { if (value instanceof Uint8Array) { if (copy2) { return new Uint8Array(value); } return value; } if (typeof value === "string" && value.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) { const result = new Uint8Array((value.length - 2) / 2); let offset = 2; for (let i = 0; i < result.length; i++) { result[i] = parseInt(value.substring(offset, offset + 2), 16); offset += 2; } return result; } assertArgument(false, "invalid BytesLike value", name || "value", value); } function getBytes(value, name) { return _getBytes(value, name, false); } function getBytesCopy(value, name) { return _getBytes(value, name, true); } function isHexString(value, length) { if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { return false; } if (typeof length === "number" && value.length !== 2 + 2 * length) { return false; } if (length === true && value.length % 2 !== 0) { return false; } return true; } function isBytesLike(value) { return isHexString(value, true) || value instanceof Uint8Array; } const HexCharacters = "0123456789abcdef"; function hexlify(data) { const bytes2 = getBytes(data); let result = "0x"; for (let i = 0; i < bytes2.length; i++) { const v = bytes2[i]; result += HexCharacters[(v & 240) >> 4] + HexCharacters[v & 15]; } return result; } function concat(datas) { return "0x" + datas.map((d) => hexlify(d).substring(2)).join(""); } function dataLength(data) { if (isHexString(data, true)) { return (data.length - 2) / 2; } return getBytes(data).length; } function dataSlice(data, start, end) { const bytes2 = getBytes(data); if (end != null && end > bytes2.length) { assert(false, "cannot slice beyond data bounds", "BUFFER_OVERRUN", { buffer: bytes2, length: bytes2.length, offset: end }); } return hexlify(bytes2.slice(start == null ? 0 : start, end == null ? bytes2.length : end)); } function zeroPad(data, length, left) { const bytes2 = getBytes(data); assert(length >= bytes2.length, "padding exceeds data length", "BUFFER_OVERRUN", { buffer: new Uint8Array(bytes2), length, offset: length + 1 }); const result = new Uint8Array(length); result.fill(0); if (left) { result.set(bytes2, length - bytes2.length); } else { result.set(bytes2, 0); } return hexlify(result); } function zeroPadValue(data, length) { return zeroPad(data, length, true); } function zeroPadBytes(data, length) { return zeroPad(data, length, false); } const BN_0$9 = BigInt(0); const BN_1$4 = BigInt(1); const maxValue = 9007199254740991; function fromTwos(_value2, _width) { const value = getUint(_value2, "value"); const width = BigInt(getNumber(_width, "width")); assert(value >> width === BN_0$9, "overflow", "NUMERIC_FAULT", { operation: "fromTwos", fault: "overflow", value: _value2 }); if (value >> width - BN_1$4) { const mask2 = (BN_1$4 << width) - BN_1$4; return -((~value & mask2) + BN_1$4); } return value; } function toTwos(_value2, _width) { let value = getBigInt(_value2, "value"); const width = BigInt(getNumber(_width, "width")); const limit = BN_1$4 << width - BN_1$4; if (value < BN_0$9) { value = -value; assert(value <= limit, "too low", "NUMERIC_FAULT", { operation: "toTwos", fault: "overflow", value: _value2 }); const mask2 = (BN_1$4 << width) - BN_1$4; return (~value & mask2) + BN_1$4; } else { assert(value < limit, "too high", "NUMERIC_FAULT", { operation: "toTwos", fault: "overflow", value: _value2 }); } return value; } function mask(_value2, _bits) { const value = getUint(_value2, "value"); const bits = BigInt(getNumber(_bits, "bits")); return value & (BN_1$4 << bits) - BN_1$4; } function getBigInt(value, name) { switch (typeof value) { case "bigint": return value; case "number": assertArgument(Number.isInteger(value), "underflow", name || "value", value); assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value); return BigInt(value); case "string": try { if (value === "") { throw new Error("empty string"); } if (value[0] === "-" && value[1] !== "-") { return -BigInt(value.substring(1)); } return BigInt(value); } catch (e) { assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || "value", value); } } assertArgument(false, "invalid BigNumberish value", name || "value", value); } function getUint(value, name) { const result = getBigInt(value, name); assert(result >= BN_0$9, "unsigned value cannot be negative", "NUMERIC_FAULT", { fault: "overflow", operation: "getUint", value }); return result; } const Nibbles = "0123456789abcdef"; function toBigInt(value) { if (value instanceof Uint8Array) { let result = "0x0"; for (const v of value) { result += Nibbles[v >> 4]; result += Nibbles[v & 15]; } return BigInt(result); } return getBigInt(value); } function getNumber(value, name) { switch (typeof value) { case "bigint": assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value); return Number(value); case "number": assertArgument(Number.isInteger(value), "underflow", name || "value", value); assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value); return value; case "string": try { if (value === "") { throw new Error("empty string"); } return getNumber(BigInt(value), name); } catch (e) { assertArgument(false, `invalid numeric string: ${e.message}`, name || "value", value); } } assertArgument(false, "invalid numeric value", name || "value", value); } function toNumber(value) { return getNumber(toBigInt(value)); } function toBeHex(_value2, _width) { const value = getUint(_value2, "value"); let result = value.toString(16); if (_width == null) { if (result.length % 2) { result = "0" + result; } } else { const width = getNumber(_width, "width"); assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, "NUMERIC_FAULT", { operation: "toBeHex", fault: "overflow", value: _value2 }); while (result.length < width * 2) { result = "0" + result; } } return "0x" + result; } function toBeArray(_value2) { const value = getUint(_value2, "value"); if (value === BN_0$9) { return new Uint8Array([]); } let hex = value.toString(16); if (hex.length % 2) { hex = "0" + hex; } const result = new Uint8Array(hex.length / 2); for (let i = 0; i < result.length; i++) { const offset = i * 2; result[i] = parseInt(hex.substring(offset, offset + 2), 16); } return result; } function toQuantity(value) { let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2); while (result.startsWith("0")) { result = result.substring(1); } if (result === "") { result = "0"; } return "0x" + result; } const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; BigInt(0); const BN_58 = BigInt(58); function encodeBase58(_value2) { const bytes2 = getBytes(_value2); let value = toBigInt(bytes2); let result = ""; while (value) { result = Alphabet[Number(value % BN_58)] + result; value /= BN_58; } for (let i = 0; i < bytes2.length; i++) { if (bytes2[i]) { break; } result = Alphabet[0] + result; } return result; } function decodeBase64(textData) { textData = atob(textData); const data = new Uint8Array(textData.length); for (let i = 0; i < textData.length; i++) { data[i] = textData.charCodeAt(i); } return getBytes(data); } function encodeBase64(_data4) { const data = getBytes(_data4); let textData = ""; for (let i = 0; i < data.length; i++) { textData += String.fromCharCode(data[i]); } return btoa(textData); } class EventPayload { /** * Create a new **EventPayload** for %%emitter%% with * the %%listener%% and for %%filter%%. */ constructor(emitter, listener, filter) { /** * The event filter. */ __publicField(this, "filter"); /** * The **EventEmitterable**. */ __publicField(this, "emitter"); __privateAdd(this, _listener, void 0); __privateSet(this, _listener, listener); defineProperties(this, { emitter, filter }); } /** * Unregister the triggered listener for future events. */ removeListener() { return __async(this, null, function* () { if (__privateGet(this, _listener) == null) { return; } yield this.emitter.off(this.filter, __privateGet(this, _listener)); }); } } _listener = new WeakMap(); function errorFunc(reason, offset, bytes2, output2, badCodepoint) { assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes2); } function ignoreFunc(reason, offset, bytes2, output2, badCodepoint) { if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { let i = 0; for (let o = offset + 1; o < bytes2.length; o++) { if (bytes2[o] >> 6 !== 2) { break; } i++; } return i; } if (reason === "OVERRUN") { return bytes2.length - offset - 1; } return 0; } function replaceFunc(reason, offset, bytes2, output2, badCodepoint) { if (reason === "OVERLONG") { assertArgument(typeof badCodepoint === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint); output2.push(badCodepoint); return 0; } output2.push(65533); return ignoreFunc(reason, offset, bytes2); } const Utf8ErrorFuncs = Object.freeze({ error: errorFunc, ignore: ignoreFunc, replace: replaceFunc }); function getUtf8CodePoints(_bytes, onError) { if (onError == null) { onError = Utf8ErrorFuncs.error; } const bytes2 = getBytes(_bytes, "bytes"); const result = []; let i = 0; while (i < bytes2.length) { const c = bytes2[i++]; if (c >> 7 === 0) { result.push(c); continue; } let extraLength = null; let overlongMask = null; if ((c & 224) === 192) { extraLength = 1; overlongMask = 127; } else if ((c & 240) === 224) { extraLength = 2; overlongMask = 2047; } else if ((c & 248) === 240) { extraLength = 3; overlongMask = 65535; } else { if ((c & 192) === 128) { i += onError("UNEXPECTED_CONTINUE", i - 1, bytes2, result); } else { i += onError("BAD_PREFIX", i - 1, bytes2, result); } continue; } if (i - 1 + extraLength >= bytes2.length) { i += onError("OVERRUN", i - 1, bytes2, result); continue; } let res = c & (1 << 8 - extraLength - 1) - 1; for (let j = 0; j < extraLength; j++) { let nextChar = bytes2[i]; if ((nextChar & 192) != 128) { i += onError("MISSING_CONTINUE", i, bytes2, result); res = null; break; } res = res << 6 | nextChar & 63; i++; } if (res === null) { continue; } if (res > 1114111) { i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes2, result, res); continue; } if (res >= 55296 && res <= 57343) { i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes2, result, res); continue; } if (res <= overlongMask) { i += onError("OVERLONG", i - 1 - extraLength, bytes2, result, res); continue; } result.push(res); } return result; } function toUtf8Bytes(str, form) { assertArgument(typeof str === "string", "invalid string value", "str", str); if (form != null) { assertNormalize(form); str = str.normalize(form); } let result = []; for (let i = 0; i < str.length; i++) { const c = str.charCodeAt(i); if (c < 128) { result.push(c); } else if (c < 2048) { result.push(c >> 6 | 192); result.push(c & 63 | 128); } else if ((c & 64512) == 55296) { i++; const c2 = str.charCodeAt(i); assertArgument(i < str.length && (c2 & 64512) === 56320, "invalid surrogate pair", "str", str); const pair = 65536 + ((c & 1023) << 10) + (c2 & 1023); result.push(pair >> 18 | 240); result.push(pair >> 12 & 63 | 128); result.push(pair >> 6 & 63 | 128); result.push(pair & 63 | 128); } else { result.push(c >> 12 | 224); result.push(c >> 6 & 63 | 128); result.push(c & 63 | 128); } } return new Uint8Array(result); } function _toUtf8String(codePoints) { return codePoints.map((codePoint) => { if (codePoint <= 65535) { return String.fromCharCode(codePoint); } codePoint -= 65536; return String.fromCharCode((codePoint >> 10 & 1023) + 55296, (codePoint & 1023) + 56320); }).join(""); } function toUtf8String(bytes2, onError) { return _toUtf8String(getUtf8CodePoints(bytes2, onError)); } function createGetUrl(options) { function getUrl(req, _signal2) { return __async(this, null, function* () { assert(_signal2 == null || !_signal2.cancelled, "request cancelled before sending", "CANCELLED"); const protocol = req.url.split(":")[0].toLowerCase(); assert(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { info: { protocol }, operation: "request" }); assert(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { operation: "request" }); let error = null; const controller = new AbortController(); const timer = setTimeout(() => { error = makeError("request timeout", "TIMEOUT"); controller.abort(); }, req.timeout); if (_signal2) { _signal2.addListener(() => { error = makeError("request cancelled", "CANCELLED"); controller.abort(); }); } const init2 = Object.assign({}, options, { method: req.method, headers: new Headers(Array.from(req)), body: req.body || void 0, signal: controller.signal }); let resp; try { resp = yield fetch(req.url, init2); } catch (_error2) { clearTimeout(timer); if (error) { throw error; } throw _error2; } clearTimeout(timer); const headers = {}; resp.headers.forEach((value, key) => { headers[key.toLowerCase()] = value; }); const respBody = yield resp.arrayBuffer(); const body = respBody == null ? null : new Uint8Array(respBody); return { statusCode: resp.status, statusMessage: resp.statusText, headers, body }; }); } return getUrl; } const MAX_ATTEMPTS = 12; const SLOT_INTERVAL = 250; let defaultGetUrlFunc = createGetUrl(); const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); const reIpfs = new RegExp("^ipfs://(ipfs/)?(.*)$", "i"); let locked$1 = false; function dataGatewayFunc(url, signal) { return __async(this, null, function* () { try { const match = url.match(reData); if (!match) { throw new Error("invalid data"); } return new FetchResponse(200, "OK", { "content-type": match[1] || "text/plain" }, match[2] ? decodeBase64(match[3]) : unpercent(match[3])); } catch (error) { return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url)); } }); } function getIpfsGatewayFunc(baseUrl) { function gatewayIpfs(url, signal) { return __async(this, null, function* () { try { const match = url.match(reIpfs); if (!match) { throw new Error("invalid link"); } return new FetchRequest(`${baseUrl}${match[2]}`); } catch (error) { return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url)); } }); } return gatewayIpfs; } const Gateways = { "data": dataGatewayFunc, "ipfs": getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/") }; const fetchSignals = /* @__PURE__ */ new WeakMap(); class FetchCancelSignal { constructor(request) { __privateAdd(this, _listeners, void 0); __privateAdd(this, _cancelled, void 0); __privateSet(this, _listeners, []); __privateSet(this, _cancelled, false); fetchSignals.set(request, () => { if (__privateGet(this, _cancelled)) { return; } __privateSet(this, _cancelled, true); for (const listener of __privateGet(this, _listeners)) { setTimeout(() => { listener(); }, 0); } __privateSet(this, _listeners, []); }); } addListener(listener) { assert(!__privateGet(this, _cancelled), "singal already cancelled", "UNSUPPORTED_OPERATION", { operation: "fetchCancelSignal.addCancelListener" }); __privateGet(this, _listeners).push(listener); } get cancelled() { return __privateGet(this, _cancelled); } checkSignal() { assert(!this.cancelled, "cancelled", "CANCELLED", {}); } } _listeners = new WeakMap(); _cancelled = new WeakMap(); function checkSignal(signal) { if (signal == null) { throw new Error("missing signal; should not happen"); } signal.checkSignal(); return signal; } const _FetchRequest = class _FetchRequest { /** * Create a new FetchRequest instance with default values. * * Once created, each property may be set before issuing a * ``.send()`` to make the request. */ constructor(url) { __privateAdd(this, _send); __privateAdd(this, _allowInsecure, void 0); __privateAdd(this, _gzip, void 0); __privateAdd(this, _headers, void 0); __privateAdd(this, _method, void 0); __privateAdd(this, _timeout, void 0); __privateAdd(this, _url, void 0); __privateAdd(this, _body, void 0); __privateAdd(this, _bodyType, void 0); __privateAdd(this, _creds, void 0); // Hooks __privateAdd(this, _preflight, void 0); __privateAdd(this, _process, void 0); __privateAdd(this, _retry, void 0); __privateAdd(this, _signal, void 0); __privateAdd(this, _throttle, void 0); __privateAdd(this, _getUrlFunc, void 0); __privateSet(this, _url, String(url)); __privateSet(this, _allowInsecure, false); __privateSet(this, _gzip, true); __privateSet(this, _headers, {}); __privateSet(this, _method, ""); __privateSet(this, _timeout, 3e5); __privateSet(this, _throttle, { slotInterval: SLOT_INTERVAL, maxAttempts: MAX_ATTEMPTS }); __privateSet(this, _getUrlFunc, null); } /** * The fetch URL to request. */ get url() { return __privateGet(this, _url); } set url(url) { __privateSet(this, _url, String(url)); } /** * The fetch body, if any, to send as the request body. //(default: null)// * * When setting a body, the intrinsic ``Content-Type`` is automatically * set and will be used if **not overridden** by setting a custom * header. * * If %%body%% is null, the body is cleared (along with the * intrinsic ``Content-Type``). * * If %%body%% is a string, the intrinsic ``Content-Type`` is set to * ``text/plain``. * * If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to * ``application/octet-stream``. * * If %%body%% is any other object, the intrinsic ``Content-Type`` is * set to ``application/json``. */ get body() { if (__privateGet(this, _body) == null) { return null; } return new Uint8Array(__privateGet(this, _body)); } set body(body) { if (body == null) { __privateSet(this, _body, void 0); __privateSet(this, _bodyType, void 0); } else if (typeof body === "string") { __privateSet(this, _body, toUtf8Bytes(body)); __privateSet(this, _bodyType, "text/plain"); } else if (body instanceof Uint8Array) { __privateSet(this, _body, body); __privateSet(this, _bodyType, "application/octet-stream"); } else if (typeof body === "object") { __privateSet(this, _body, toUtf8Bytes(JSON.stringify(body))); __privateSet(this, _bodyType, "application/json"); } else { throw new Error("invalid body"); } } /** * Returns true if the request has a body. */ hasBody() { return __privateGet(this, _body) != null; } /** * The HTTP method to use when requesting the URI. If no method * has been explicitly set, then ``GET`` is used if the body is * null and ``POST`` otherwise. */ get method() { if (__privateGet(this, _method)) { return __privateGet(this, _method); } if (this.hasBody()) { return "POST"; } return "GET"; } set method(method) { if (method == null) { method = ""; } __privateSet(this, _method, String(method).toUpperCase()); } /** * The headers that will be used when requesting the URI. All * keys are lower-case. * * This object is a copy, so any changes will **NOT** be reflected * in the ``FetchRequest``. * * To set a header entry, use the ``setHeader`` method. */ get headers() { const headers = Object.assign({}, __privateGet(this, _headers)); if (__privateGet(this, _creds)) { headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(__privateGet(this, _creds)))}`; } if (this.allowGzip) { headers["accept-encoding"] = "gzip"; } if (headers["content-type"] == null && __privateGet(this, _bodyType)) { headers["content-type"] = __privateGet(this, _bodyType); } if (this.body) { headers["content-length"] = String(this.body.length); } return headers; } /** * Get the header for %%key%%, ignoring case. */ getHeader(key) { return this.headers[key.toLowerCase()]; } /** * Set the header for %%key%% to %%value%%. All values are coerced * to a string. */ setHeader(key, value) { __privateGet(this, _headers)[String(key).toLowerCase()] = String(value); } /** * Clear all headers, resetting all intrinsic headers. */ clearHeaders() { __privateSet(this, _headers, {}); } [Symbol.iterator]() { const headers = this.headers; const keys = Object.keys(headers); let index = 0; return { next: () => { if (index < keys.length) { const key = keys[index++]; return { value: [key, headers[key]], done: false }; } return { value: void 0, done: true }; } }; } /** * The value that will be sent for the ``Authorization`` header. * * To set the credentials, use the ``setCredentials`` method. */ get credentials() { return __privateGet(this, _creds) || null; } /** * Sets an ``Authorization`` for %%username%% with %%password%%. */ setCredentials(username, password) { assertArgument(!username.match(/:/), "invalid basic authentication username", "username", "[REDACTED]"); __privateSet(this, _creds, `${username}:${password}`); } /** * Enable and request gzip-encoded responses. The response will * automatically be decompressed. //(default: true)// */ get allowGzip() { return __privateGet(this, _gzip); } set allowGzip(value) { __privateSet(this, _gzip, !!value); } /** * Allow ``Authentication`` credentials to be sent over insecure * channels. //(default: false)// */ get allowInsecureAuthentication() { return !!__privateGet(this, _allowInsecure); } set allowInsecureAuthentication(value) { __privateSet(this, _allowInsecure, !!value); } /** * The timeout (in milliseconds) to wait for a complete response. * //(default: 5 minutes)// */ get timeout() { return __privateGet(this, _timeout); } set timeout(timeout) { assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout); __privateSet(this, _timeout, timeout); } /** * This function is called prior to each request, for example * during a redirection or retry in case of server throttling. * * This offers an opportunity to populate headers or update * content before sending a request. */ get preflightFunc() { return __privateGet(this, _preflight) || null; } set preflightFunc(preflight) { __privateSet(this, _preflight, preflight); } /** * This function is called after each response, offering an * opportunity to provide client-level throttling or updating * response data. * * Any error thrown in this causes the ``send()`` to throw. * * To schedule a retry attempt (assuming the maximum retry limit * has not been reached), use [[response.throwThrottleError]]. */ get processFunc() { return __privateGet(this, _process) || null; } set processFunc(process) { __privateSet(this, _process, process); } /** * This function is called on each retry attempt. */ get retryFunc() { return __privateGet(this, _retry) || null; } set retryFunc(retry) { __privateSet(this, _retry, retry); } /** * This function is called to fetch content from HTTP and * HTTPS URLs and is platform specific (e.g. nodejs vs * browsers). * * This is by default the currently registered global getUrl * function, which can be changed using [[registerGetUrl]]. * If this has been set, setting is to ``null`` will cause * this FetchRequest (and any future clones) to revert back to * using the currently registered global getUrl function. * * Setting this is generally not necessary, but may be useful * for developers that wish to intercept requests or to * configurege a proxy or other agent. */ get getUrlFunc() { return __privateGet(this, _getUrlFunc) || defaultGetUrlFunc; } set getUrlFunc(value) { __privateSet(this, _getUrlFunc, value); } toString() { return `<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${__privateGet(this, _body) ? hexlify(__privateGet(this, _body)) : "null"}>`; } /** * Update the throttle parameters used to determine maximum * attempts and exponential-backoff properties. */ setThrottleParams(params) { if (params.slotInterval != null) { __privateGet(this, _throttle).slotInterval = params.slotInterval; } if (params.maxAttempts != null) { __privateGet(this, _throttle).maxAttempts = params.maxAttempts; } } /** * Resolves to the response by sending the request. */ send() { assert(__privateGet(this, _signal) == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }); __privateSet(this, _signal, new FetchCancelSignal(this)); return __privateMethod(this, _send, send_fn).call(this, 0, getTime$1() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this)); } /** * Cancels the inflight response, causing a ``CANCELLED`` * error to be rejected from the [[send]]. */ cancel() { assert(__privateGet(this, _signal) != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" }); const signal = fetchSignals.get(this); if (!signal) { throw new Error("missing signal; should not happen"); } signal(); } /** * Returns a new [[FetchRequest]] that represents the redirection * to %%location%%. */ redirect(location) { const current = this.url.split(":")[0].toLowerCase(); const target = location.split(":")[0].toLowerCase(); assert(this.method === "GET" && (current !== "https" || target !== "http") && location.match(/^https?:/), `unsupported redirect`, "UNSUPPORTED_OPERATION", { operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})` }); const req = new _FetchRequest(location); req.method = "GET"; req.allowGzip = this.allowGzip; req.timeout = this.timeout; __privateSet(req, _headers, Object.assign({}, __privateGet(this, _headers))); if (__privateGet(this, _body)) { __privateSet(req, _body, new Uint8Array(__privateGet(this, _body))); } __privateSet(req, _bodyType, __privateGet(this, _bodyType)); return req; } /** * Create a new copy of this request. */ clone() { const clone = new _FetchRequest(this.url); __privateSet(clone, _method, __privateGet(this, _method)); if (__privateGet(this, _body)) { __privateSet(clone, _body, __privateGet(this, _body)); } __privateSet(clone, _bodyType, __privateGet(this, _bodyType)); __privateSet(clone, _headers, Object.assign({}, __privateGet(this, _headers))); __privateSet(clone, _creds, __privateGet(this, _creds)); if (this.allowGzip) { clone.allowGzip = true; } clone.timeout = this.timeout; if (this.allowInsecureAuthentication) { clone.allowInsecureAuthentication = true; } __privateSet(clone, _preflight, __privateGet(this, _preflight)); __privateSet(clone, _process, __privateGet(this, _process)); __privateSet(clone, _retry, __privateGet(this, _retry)); __privateSet(clone, _throttle, Object.assign({}, __privateGet(this, _throttle))); __privateSet(clone, _getUrlFunc, __privateGet(this, _getUrlFunc)); return clone; } /** * Locks all static configuration for gateways and FetchGetUrlFunc * registration. */ static lockConfig() { locked$1 = true; } /** * Get the current Gateway function for %%scheme%%. */ static getGateway(scheme) { return Gateways[scheme.toLowerCase()] || null; } /** * Use the %%func%% when fetching URIs using %%scheme%%. * * This method affects all requests globally. * * If [[lockConfig]] has been called, no change is made and this * throws. */ static registerGateway(scheme, func) { scheme = scheme.toLowerCase(); if (scheme === "http" || scheme === "https") { throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); } if (locked$1) { throw new Error("gateways locked"); } Gateways[scheme] = func; } /** * Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests. * * This method affects all requests globally. * * If [[lockConfig]] has been called, no change is made and this * throws. */ static registerGetUrl(getUrl) { if (locked$1) { throw new Error("gateways locked"); } defaultGetUrlFunc = getUrl; } /** * Creates a getUrl function that fetches content from HTTP and * HTTPS URLs. * * The available %%options%% are dependent on the platform * implementation of the default getUrl function. * * This is not generally something that is needed, but is useful * when trying to customize simple behaviour when fetching HTTP * content. */ static createGetUrlFunc(options) { return createGetUrl(options); } /** * Creates a function that can "fetch" data URIs. * * Note that this is automatically done internally to support * data URIs, so it is not necessary to register it. * * This is not generally something that is needed, but may * be useful in a wrapper to perfom custom data URI functionality. */ static createDataGateway() { return dataGatewayFunc; } /** * Creates a function that will fetch IPFS (unvalidated) from * a custom gateway baseUrl. * * The default IPFS gateway used internally is * ``"https:/\/gateway.ipfs.io/ipfs/"``. */ static createIpfsGatewayFunc(baseUrl) { return getIpfsGatewayFunc(baseUrl); } }; _allowInsecure = new WeakMap(); _gzip = new WeakMap(); _headers = new WeakMap(); _method = new WeakMap(); _timeout = new WeakMap(); _url = new WeakMap(); _body = new WeakMap(); _bodyType = new WeakMap(); _creds = new WeakMap(); _preflight = new WeakMap(); _process = new WeakMap(); _retry = new WeakMap(); _signal = new WeakMap(); _throttle = new WeakMap(); _getUrlFunc = new WeakMap(); _send = new WeakSet(); send_fn = function(attempt, expires, delay, _request3, _response) { return __async(this, null, function* () { var _a2, _b, _c; if (attempt >= __privateGet(this, _throttle).maxAttempts) { return _response.makeServerError("exceeded maximum retry limit"); } assert(getTime$1() <= expires, "timeout", "TIMEOUT", { operation: "request.send", reason: "timeout", request: _request3 }); if (delay > 0) { yield wait(delay); } let req = this.clone(); const scheme = (req.url.split(":")[0] || "").toLowerCase(); if (scheme in Gateways) { const result = yield Gateways[scheme](req.url, checkSignal(__privateGet(_request3, _signal))); if (result instanceof FetchResponse) { let response2 = result; if (this.processFunc) { checkSignal(__privateGet(_request3, _signal)); try { response2 = yield this.processFunc(req, response2); } catch (error) { if (error.throttle == null || typeof error.stall !== "number") { response2.makeServerError("error in post-processing function", error).assertOk(); } } } return response2; } req = result; } if (this.preflightFunc) { req = yield this.preflightFunc(req); } const resp = yield this.getUrlFunc(req, checkSignal(__privateGet(_request3, _signal))); let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request3); if (response.statusCode === 301 || response.statusCode === 302) { try { const location = response.headers.location || ""; return __privateMethod(_a2 = req.redirect(location), _send, send_fn).call(_a2, attempt + 1, expires, 0, _request3, response); } catch (error) { } return response; } else if (response.statusCode === 429) { if (this.retryFunc == null || (yield this.retryFunc(req, response, attempt))) { const retryAfter = response.headers["retry-after"]; let delay2 = __privateGet(this, _throttle).slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { delay2 = parseInt(retryAfter); } return __privateMethod(_b = req.clone(), _send, send_fn).call(_b, attempt + 1, expires, delay2, _request3, response); } } if (this.processFunc) { checkSignal(__privateGet(_request3, _signal)); try { response = yield this.processFunc(req, response); } catch (error) { if (error.throttle == null || typeof error.stall !== "number") { response.makeServerError("error in post-processing function", error).assertOk(); } let delay2 = __privateGet(this, _throttle).slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); if (error.stall >= 0) { delay2 = error.stall; } return __privateMethod(_c = req.clone(), _send, send_fn).call(_c, attempt + 1, expires, delay2, _request3, response); } } return response; }); }; let FetchRequest = _FetchRequest; const _FetchResponse = class _FetchResponse { constructor(statusCode, statusMessage, headers, body, request) { __privateAdd(this, _statusCode, void 0); __privateAdd(this, _statusMessage, void 0); __privateAdd(this, _headers2, void 0); __privateAdd(this, _body2, void 0); __privateAdd(this, _request, void 0); __privateAdd(this, _error, void 0); __privateSet(this, _statusCode, statusCode); __privateSet(this, _statusMessage, statusMessage); __privateSet(this, _headers2, Object.keys(headers).reduce((accum, k2) => { accum[k2.toLowerCase()] = String(headers[k2]); return accum; }, {})); __privateSet(this, _body2, body == null ? null : new Uint8Array(body)); __privateSet(this, _request, request || null); __privateSet(this, _error, { message: "" }); } toString() { return `<FetchResponse status=${this.statusCode} body=${__privateGet(this, _body2) ? hexlify(__privateGet(this, _body2)) : "null"}>`; } /** * The response status code. */ get statusCode() { return __privateGet(this, _statusCode); } /** * The response status message. */ get statusMessage() { return __privateGet(this, _statusMessage); } /** * The response headers. All keys are lower-case. */ get headers() { return Object.assign({}, __privateGet(this, _headers2)); } /** * The response body, or ``null`` if there was no body. */ get body() { return __privateGet(this, _body2) == null ? null : new Uint8Array(__privateGet(this, _body2)); } /** * The response body as a UTF-8 encoded string, or the empty * string (i.e. ``""``) if there was no body. * * An error is thrown if the body is invalid UTF-8 data. */ get bodyText() { try { return __privateGet(this, _body2) == null ? "" : toUtf8String(__privateGet(this, _body2)); } catch (error) { assert(false, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", { operation: "bodyText", info: { response: this } }); } } /** * The response body, decoded as JSON. * * An error is thrown if the body is invalid JSON-encoded data * or if there was no body. */ get bodyJson() { try { return JSON.parse(this.bodyText); } catch (error) { assert(false, "response body is not valid JSON", "UNSUPPORTED_OPERATION", { operation: "bodyJson", info: { response: this } }); } } [Symbol.iterator]() { const headers = this.headers; const keys = Object.keys(headers); let index = 0; return { next: () => { if (index < keys.length) { const key = keys[index++]; return { value: [key, headers[key]], done: false }; } return { value: void 0, done: true }; } }; } /** * Return a Response with matching headers and body, but with * an error status code (i.e. 599) and %%message%% with an * optional %%error%%. */ makeServerError(message, error) { let statusMessage; if (!message) { message = `${this.statusCode} ${this.statusMessage}`; statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; } else { statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; } const response = new _FetchResponse(599, statusMessage, this.headers, this.body, __privateGet(this, _request) || void 0); __privateSet(response, _error, { message, error }); return response; } /** * If called within a [request.processFunc](FetchRequest-processFunc) * call, causes the request to retry as if throttled for %%stall%% * milliseconds. */ throwThrottleError(message, stall2) { if (stall2 == null) { stall2 = -1; } else { assertArgument(Number.isInteger(stall2) && stall2 >= 0, "invalid stall timeout", "stall", stall2); } const error = new Error(message || "throttling requests"); defineProperties(error, { stall: stall2, throttl