UNPKG

contentful-management

Version:
1,504 lines (1,384 loc) 928 kB
var contentfulManagement = (function (exports) { 'use strict'; var toStringFunction = Function.prototype.toString; var create$G = Object.create; var toStringObject = Object.prototype.toString; /** * @classdesc Fallback cache for when WeakMap is not natively supported */ var LegacyCache = /** @class */ (function () { function LegacyCache() { this._keys = []; this._values = []; } LegacyCache.prototype.has = function (key) { return !!~this._keys.indexOf(key); }; LegacyCache.prototype.get = function (key) { return this._values[this._keys.indexOf(key)]; }; LegacyCache.prototype.set = function (key, value) { this._keys.push(key); this._values.push(value); }; return LegacyCache; }()); function createCacheLegacy() { return new LegacyCache(); } function createCacheModern() { return new WeakMap(); } /** * Get a new cache object to prevent circular references. */ var createCache = typeof WeakMap !== 'undefined' ? createCacheModern : createCacheLegacy; /** * Get an empty version of the object with the same prototype it has. */ function getCleanClone(prototype) { if (!prototype) { return create$G(null); } var Constructor = prototype.constructor; if (Constructor === Object) { return prototype === Object.prototype ? {} : create$G(prototype); } if (Constructor && ~toStringFunction.call(Constructor).indexOf('[native code]')) { try { return new Constructor(); } catch (_a) { } } return create$G(prototype); } function getRegExpFlagsLegacy(regExp) { var flags = ''; if (regExp.global) { flags += 'g'; } if (regExp.ignoreCase) { flags += 'i'; } if (regExp.multiline) { flags += 'm'; } if (regExp.unicode) { flags += 'u'; } if (regExp.sticky) { flags += 'y'; } return flags; } function getRegExpFlagsModern(regExp) { return regExp.flags; } /** * Get the flags to apply to the copied regexp. */ var getRegExpFlags = /test/g.flags === 'g' ? getRegExpFlagsModern : getRegExpFlagsLegacy; function getTagLegacy(value) { var type = toStringObject.call(value); return type.substring(8, type.length - 1); } function getTagModern(value) { return value[Symbol.toStringTag] || getTagLegacy(value); } /** * Get the tag of the value passed, so that the correct copier can be used. */ var getTag = typeof Symbol !== 'undefined' ? getTagModern : getTagLegacy; var defineProperty = Object.defineProperty, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getOwnPropertyNames = Object.getOwnPropertyNames, getOwnPropertySymbols = Object.getOwnPropertySymbols; var _a = Object.prototype, hasOwnProperty$1 = _a.hasOwnProperty, propertyIsEnumerable = _a.propertyIsEnumerable; var SUPPORTS_SYMBOL = typeof getOwnPropertySymbols === 'function'; function getStrictPropertiesModern(object) { return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object)); } /** * Get the properites used when copying objects strictly. This includes both keys and symbols. */ var getStrictProperties = SUPPORTS_SYMBOL ? getStrictPropertiesModern : getOwnPropertyNames; /** * Striclty copy all properties contained on the object. */ function copyOwnPropertiesStrict(value, clone, state) { var properties = getStrictProperties(value); for (var index = 0, length_1 = properties.length, property = void 0, descriptor = void 0; index < length_1; ++index) { property = properties[index]; if (property === 'callee' || property === 'caller') { continue; } descriptor = getOwnPropertyDescriptor(value, property); if (!descriptor) { // In extra edge cases where the property descriptor cannot be retrived, fall back to // the loose assignment. clone[property] = state.copier(value[property], state); continue; } // Only clone the value if actually a value, not a getter / setter. if (!descriptor.get && !descriptor.set) { descriptor.value = state.copier(descriptor.value, state); } try { defineProperty(clone, property, descriptor); } catch (error) { // Tee above can fail on node in edge cases, so fall back to the loose assignment. clone[property] = descriptor.value; } } return clone; } /** * Deeply copy the indexed values in the array. */ function copyArrayLoose(array, state) { var clone = new state.Constructor(); // set in the cache immediately to be able to reuse the object recursively state.cache.set(array, clone); for (var index = 0, length_2 = array.length; index < length_2; ++index) { clone[index] = state.copier(array[index], state); } return clone; } /** * Deeply copy the indexed values in the array, as well as any custom properties. */ function copyArrayStrict(array, state) { var clone = new state.Constructor(); // set in the cache immediately to be able to reuse the object recursively state.cache.set(array, clone); return copyOwnPropertiesStrict(array, clone, state); } /** * Copy the contents of the ArrayBuffer. */ function copyArrayBuffer(arrayBuffer, _state) { return arrayBuffer.slice(0); } /** * Create a new Blob with the contents of the original. */ function copyBlob(blob, _state) { return blob.slice(0, blob.size, blob.type); } /** * Create a new DataView with the contents of the original. */ function copyDataView(dataView, state) { return new state.Constructor(copyArrayBuffer(dataView.buffer)); } /** * Create a new Date based on the time of the original. */ function copyDate(date, state) { return new state.Constructor(date.getTime()); } /** * Deeply copy the keys and values of the original. */ function copyMapLoose(map, state) { var clone = new state.Constructor(); // set in the cache immediately to be able to reuse the object recursively state.cache.set(map, clone); map.forEach(function (value, key) { clone.set(key, state.copier(value, state)); }); return clone; } /** * Deeply copy the keys and values of the original, as well as any custom properties. */ function copyMapStrict(map, state) { return copyOwnPropertiesStrict(map, copyMapLoose(map, state), state); } function copyObjectLooseLegacy(object, state) { var clone = getCleanClone(state.prototype); // set in the cache immediately to be able to reuse the object recursively state.cache.set(object, clone); for (var key in object) { if (hasOwnProperty$1.call(object, key)) { clone[key] = state.copier(object[key], state); } } return clone; } function copyObjectLooseModern(object, state) { var clone = getCleanClone(state.prototype); // set in the cache immediately to be able to reuse the object recursively state.cache.set(object, clone); for (var key in object) { if (hasOwnProperty$1.call(object, key)) { clone[key] = state.copier(object[key], state); } } var symbols = getOwnPropertySymbols(object); for (var index = 0, length_3 = symbols.length, symbol = void 0; index < length_3; ++index) { symbol = symbols[index]; if (propertyIsEnumerable.call(object, symbol)) { clone[symbol] = state.copier(object[symbol], state); } } return clone; } /** * Deeply copy the properties (keys and symbols) and values of the original. */ var copyObjectLoose = SUPPORTS_SYMBOL ? copyObjectLooseModern : copyObjectLooseLegacy; /** * Deeply copy the properties (keys and symbols) and values of the original, as well * as any hidden or non-enumerable properties. */ function copyObjectStrict(object, state) { var clone = getCleanClone(state.prototype); // set in the cache immediately to be able to reuse the object recursively state.cache.set(object, clone); return copyOwnPropertiesStrict(object, clone, state); } /** * Create a new primitive wrapper from the value of the original. */ function copyPrimitiveWrapper(primitiveObject, state) { return new state.Constructor(primitiveObject.valueOf()); } /** * Create a new RegExp based on the value and flags of the original. */ function copyRegExp(regExp, state) { var clone = new state.Constructor(regExp.source, getRegExpFlags(regExp)); clone.lastIndex = regExp.lastIndex; return clone; } /** * Return the original value (an identity function). * * @note * THis is used for objects that cannot be copied, such as WeakMap. */ function copySelf(value, _state) { return value; } /** * Deeply copy the values of the original. */ function copySetLoose(set, state) { var clone = new state.Constructor(); // set in the cache immediately to be able to reuse the object recursively state.cache.set(set, clone); set.forEach(function (value) { clone.add(state.copier(value, state)); }); return clone; } /** * Deeply copy the values of the original, as well as any custom properties. */ function copySetStrict(set, state) { return copyOwnPropertiesStrict(set, copySetLoose(set, state), state); } var isArray$1 = Array.isArray; var assign = Object.assign; var getPrototypeOf = Object.getPrototypeOf || (function (obj) { return obj.__proto__; }); var DEFAULT_LOOSE_OPTIONS = { array: copyArrayLoose, arrayBuffer: copyArrayBuffer, blob: copyBlob, dataView: copyDataView, date: copyDate, error: copySelf, map: copyMapLoose, object: copyObjectLoose, regExp: copyRegExp, set: copySetLoose, }; var DEFAULT_STRICT_OPTIONS = assign({}, DEFAULT_LOOSE_OPTIONS, { array: copyArrayStrict, map: copyMapStrict, object: copyObjectStrict, set: copySetStrict, }); /** * Get the copiers used for each specific object tag. */ function getTagSpecificCopiers(options) { return { Arguments: options.object, Array: options.array, ArrayBuffer: options.arrayBuffer, Blob: options.blob, Boolean: copyPrimitiveWrapper, DataView: options.dataView, Date: options.date, Error: options.error, Float32Array: options.arrayBuffer, Float64Array: options.arrayBuffer, Int8Array: options.arrayBuffer, Int16Array: options.arrayBuffer, Int32Array: options.arrayBuffer, Map: options.map, Number: copyPrimitiveWrapper, Object: options.object, Promise: copySelf, RegExp: options.regExp, Set: options.set, String: copyPrimitiveWrapper, WeakMap: copySelf, WeakSet: copySelf, Uint8Array: options.arrayBuffer, Uint8ClampedArray: options.arrayBuffer, Uint16Array: options.arrayBuffer, Uint32Array: options.arrayBuffer, Uint64Array: options.arrayBuffer, }; } /** * Create a custom copier based on the object-specific copy methods passed. */ function createCopier(options) { var normalizedOptions = assign({}, DEFAULT_LOOSE_OPTIONS, options); var tagSpecificCopiers = getTagSpecificCopiers(normalizedOptions); var array = tagSpecificCopiers.Array, object = tagSpecificCopiers.Object; function copier(value, state) { state.prototype = state.Constructor = undefined; if (!value || typeof value !== 'object') { return value; } if (state.cache.has(value)) { return state.cache.get(value); } state.prototype = getPrototypeOf(value); state.Constructor = state.prototype && state.prototype.constructor; // plain objects if (!state.Constructor || state.Constructor === Object) { return object(value, state); } // arrays if (isArray$1(value)) { return array(value, state); } var tagSpecificCopier = tagSpecificCopiers[getTag(value)]; if (tagSpecificCopier) { return tagSpecificCopier(value, state); } return typeof value.then === 'function' ? value : object(value, state); } return function copy(value) { return copier(value, { Constructor: undefined, cache: createCache(), copier: copier, prototype: undefined, }); }; } /** * Create a custom copier based on the object-specific copy methods passed, defaulting to the * same internals as `copyStrict`. */ function createStrictCopier(options) { return createCopier(assign({}, DEFAULT_STRICT_OPTIONS, options)); } /** * Copy an value deeply as much as possible, where strict recreation of object properties * are maintained. All properties (including non-enumerable ones) are copied with their * original property descriptors on both objects and arrays. */ createStrictCopier({}); /** * Copy an value deeply as much as possible. */ var index$2 = createCopier({}); function asyncToken(instance, getToken) { instance.interceptors.request.use(function (config) { return getToken().then((accessToken) => { config.headers.set('Authorization', `Bearer ${accessToken}`); return config; }); }); } function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getDefaultExportFromNamespaceIfNotNamed (n) { return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; } var browser = {exports: {}}; var hasRequiredBrowser; function requireBrowser () { if (hasRequiredBrowser) return browser.exports; hasRequiredBrowser = 1; // shim for using process in browser var process = browser.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()); function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] }; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; return browser.exports; } var browserExports = requireBrowser(); var process$1 = /*@__PURE__*/getDefaultExportFromCjs(browserExports); function isNode() { /** * Polyfills of 'process' might set process.browser === true * * See: * https://github.com/webpack/node-libs-browser/blob/master/mock/process.js#L8 * https://github.com/defunctzombie/node-process/blob/master/browser.js#L156 **/ return typeof process$1 !== 'undefined' && !process$1.browser; } function isReactNative() { return (typeof window !== 'undefined' && 'navigator' in window && 'product' in window.navigator && window.navigator.product === 'ReactNative'); } function getNodeVersion() { return process$1.versions && process$1.versions.node ? `v${process$1.versions.node}` : process$1.version; } function getWindow() { return window; } function noop() { return undefined; } const delay = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }); const defaultWait = (attempts) => { return Math.pow(Math.SQRT2, attempts); }; function rateLimit(instance, maxRetry = 5) { const { responseLogger = noop, requestLogger = noop } = instance.defaults; instance.interceptors.request.use(function (config) { requestLogger(config); return config; }, function (error) { requestLogger(error); return Promise.reject(error); }); instance.interceptors.response.use(function (response) { // we don't need to do anything here responseLogger(response); return response; }, async function (error) { const { response } = error; const { config } = error; responseLogger(error); // Do not retry if it is disabled or no request config exists (not an axios error) if (!config || !instance.defaults.retryOnError) { return Promise.reject(error); } // Retried already for max attempts const doneAttempts = config.attempts || 1; if (doneAttempts > maxRetry) { error.attempts = config.attempts; return Promise.reject(error); } let retryErrorType = null; let wait = defaultWait(doneAttempts); // Errors without response did not receive anything from the server if (!response) { retryErrorType = 'Connection'; } else if (response.status >= 500 && response.status < 600) { // 5** errors are server related retryErrorType = `Server ${response.status}`; } else if (response.status === 429) { // 429 errors are exceeded rate limit exceptions retryErrorType = 'Rate limit'; // all headers are lowercased by axios https://github.com/mzabriskie/axios/issues/413 if (response.headers && error.response.headers['x-contentful-ratelimit-reset']) { wait = response.headers['x-contentful-ratelimit-reset']; } } if (retryErrorType) { // convert to ms and add jitter wait = Math.floor(wait * 1000 + Math.random() * 200 + 500); instance.defaults.logHandler('warning', `${retryErrorType} error occurred. Waiting for ${wait} ms before retrying...`); // increase attempts counter config.attempts = doneAttempts + 1; /* Somehow between the interceptor and retrying the request the httpAgent/httpsAgent gets transformed from an Agent-like object to a regular object, causing failures on retries after rate limits. Removing these properties here fixes the error, but retry requests still use the original http/httpsAgent property */ delete config.httpAgent; delete config.httpsAgent; return delay(wait).then(() => instance(config)); } return Promise.reject(error); }); } /** Detect free variable `global` from Node.js. */ var _freeGlobal; var hasRequired_freeGlobal; function require_freeGlobal () { if (hasRequired_freeGlobal) return _freeGlobal; hasRequired_freeGlobal = 1; var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; _freeGlobal = freeGlobal; return _freeGlobal; } var _root; var hasRequired_root; function require_root () { if (hasRequired_root) return _root; hasRequired_root = 1; var freeGlobal = require_freeGlobal(); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); _root = root; return _root; } var _Symbol; var hasRequired_Symbol; function require_Symbol () { if (hasRequired_Symbol) return _Symbol; hasRequired_Symbol = 1; var root = require_root(); /** Built-in value references. */ var Symbol = root.Symbol; _Symbol = Symbol; return _Symbol; } var _getRawTag; var hasRequired_getRawTag; function require_getRawTag () { if (hasRequired_getRawTag) return _getRawTag; hasRequired_getRawTag = 1; var Symbol = require_Symbol(); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } _getRawTag = getRawTag; return _getRawTag; } /** Used for built-in method references. */ var _objectToString; var hasRequired_objectToString; function require_objectToString () { if (hasRequired_objectToString) return _objectToString; hasRequired_objectToString = 1; var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } _objectToString = objectToString; return _objectToString; } var _baseGetTag; var hasRequired_baseGetTag; function require_baseGetTag () { if (hasRequired_baseGetTag) return _baseGetTag; hasRequired_baseGetTag = 1; var Symbol = require_Symbol(), getRawTag = require_getRawTag(), objectToString = require_objectToString(); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } _baseGetTag = baseGetTag; return _baseGetTag; } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray_1; var hasRequiredIsArray; function requireIsArray () { if (hasRequiredIsArray) return isArray_1; hasRequiredIsArray = 1; var isArray = Array.isArray; isArray_1 = isArray; return isArray_1; } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ var isObjectLike_1; var hasRequiredIsObjectLike; function requireIsObjectLike () { if (hasRequiredIsObjectLike) return isObjectLike_1; hasRequiredIsObjectLike = 1; function isObjectLike(value) { return value != null && typeof value == 'object'; } isObjectLike_1 = isObjectLike; return isObjectLike_1; } var isString_1; var hasRequiredIsString; function requireIsString () { if (hasRequiredIsString) return isString_1; hasRequiredIsString = 1; var baseGetTag = require_baseGetTag(), isArray = requireIsArray(), isObjectLike = requireIsObjectLike(); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } isString_1 = isString; return isString_1; } var isStringExports = requireIsString(); var isString$1 = /*@__PURE__*/getDefaultExportFromCjs(isStringExports); class AbortError extends Error { name = 'AbortError'; constructor() { super('Throttled function aborted'); } } /** * Throttle promise-returning/async/normal functions. * * It rate-limits function calls without discarding them, making it ideal for external API interactions where avoiding call loss is crucial. * * @returns A throttle function. * * Both the `limit` and `interval` options must be specified. * * @example * ``` * import pThrottle from './PThrottle'; * * const now = Date.now(); * * const throttle = pThrottle({ * limit: 2, * interval: 1000 * }); * * const throttled = throttle(async index => { * const secDiff = ((Date.now() - now) / 1000).toFixed(); * return `${index}: ${secDiff}s`; * }); * * for (let index = 1; index <= 6; index++) { * (async () => { * console.log(await throttled(index)); * })(); * } * //=> 1: 0s * //=> 2: 0s * //=> 3: 1s * //=> 4: 1s * //=> 5: 2s * //=> 6: 2s * ``` */ function pThrottle({ limit, interval, strict, onDelay }) { if (!Number.isFinite(limit)) { throw new TypeError('Expected `limit` to be a finite number'); } if (!Number.isFinite(interval)) { throw new TypeError('Expected `interval` to be a finite number'); } const queue = new Map(); let currentTick = 0; let activeCount = 0; function windowedDelay() { const now = Date.now(); if (now - currentTick > interval) { activeCount = 1; currentTick = now; return 0; } if (activeCount < limit) { activeCount++; } else { currentTick += interval; activeCount = 1; } return currentTick - now; } const getDelay = windowedDelay; return function (function_) { const throttled = function (...arguments_) { if (!throttled.isEnabled) { return (async () => function_.apply(this, arguments_))(); } let timeoutId; return new Promise((resolve, reject) => { const execute = () => { resolve(function_.apply(this, arguments_)); queue.delete(timeoutId); }; const delay = getDelay(); if (delay > 0) { timeoutId = setTimeout(execute, delay); queue.set(timeoutId, reject); onDelay?.(); } else { execute(); } }); }; throttled.abort = () => { for (const timeout of queue.keys()) { clearTimeout(timeout); queue.get(timeout)(new AbortError()); } queue.clear(); }; throttled.isEnabled = true; Object.defineProperty(throttled, 'queueSize', { get() { return queue.size; }, }); return throttled; }; } const PERCENTAGE_REGEX = /(?<value>\d+)(%)/; function calculateLimit(type, max = 7) { let limit = max; if (PERCENTAGE_REGEX.test(type)) { const groups = type.match(PERCENTAGE_REGEX)?.groups; if (groups && groups.value) { const percentage = parseInt(groups.value) / 100; limit = Math.round(max * percentage); } } return Math.min(30, Math.max(1, limit)); } function createThrottle(limit, logger) { logger('info', `Throttle request to ${limit}/s`); return pThrottle({ limit, interval: 1000, strict: false, }); } var rateLimitThrottle = (axiosInstance, type = 'auto') => { const { logHandler = noop } = axiosInstance.defaults; let limit = isString$1(type) ? calculateLimit(type) : calculateLimit('auto', type); let throttle = createThrottle(limit, logHandler); let isCalculated = false; let requestInterceptorId = axiosInstance.interceptors.request.use((config) => { return throttle(() => config)(); }, function (error) { return Promise.reject(error); }); const responseInterceptorId = axiosInstance.interceptors.response.use((response) => { if (!isCalculated && isString$1(type) && (type === 'auto' || PERCENTAGE_REGEX.test(type)) && response.headers && response.headers['x-contentful-ratelimit-second-limit']) { const rawLimit = parseInt(response.headers['x-contentful-ratelimit-second-limit']); const nextLimit = calculateLimit(type, rawLimit); if (nextLimit !== limit) { if (requestInterceptorId) { axiosInstance.interceptors.request.eject(requestInterceptorId); } limit = nextLimit; throttle = createThrottle(nextLimit, logHandler); requestInterceptorId = axiosInstance.interceptors.request.use((config) => { return throttle(() => config)(); }, function (error) { return Promise.reject(error); }); } isCalculated = true; } return response; }, function (error) { return Promise.reject(error); }); return () => { axiosInstance.interceptors.request.eject(requestInterceptorId); axiosInstance.interceptors.response.eject(responseInterceptorId); }; }; var type; var hasRequiredType; function requireType () { if (hasRequiredType) return type; hasRequiredType = 1; /** @type {import('./type')} */ type = TypeError; return type; } var inherits; if (typeof Object.create === 'function'){ inherits = function inherits(ctor, superCtor) { // implementation from standard node.js 'util' module ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { inherits = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(obj) { var keys = Object.keys(obj); var descriptors = {}; for (var i = 0; i < keys.length; i++) { descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); } return descriptors; }; var formatRegExp = /%[sdj%]/g; function format(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; } // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. function deprecate(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return deprecate(fn, msg).apply(this, arguments); }; } if (process$1.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process$1.throwDeprecation) { throw new Error(msg); } else if (process$1.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } var debugs = {}; var debugEnviron; function debuglog(set) { if (isUndefined(debugEnviron)) debugEnviron = process$1.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = 0; debugs[set] = function() { var msg = format.apply(null, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; } /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object _extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 &