UNPKG

mysql-user-and-database-cdk

Version:

[![docs](https://img.shields.io/badge/docs-!-brightgreen)](https://isotoma.github.io/mysql-user-and-database-cdk/) [![npm](https://img.shields.io/npm/v/mysql-user-and-database-cdk)](https://www.npmjs.com/package/mysql-user-and-database-cdk) [![NPM](https:

1,060 lines (1,056 loc) 2.17 MB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: !0 }); }, __copyProps = (to, from, except, desc) => { if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target, mod )), __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod); // node_modules/sqlstring/lib/SqlString.js var require_SqlString = __commonJS({ "node_modules/sqlstring/lib/SqlString.js"(exports2) { var SqlString = exports2, ID_GLOBAL_REGEXP = /`/g, QUAL_GLOBAL_REGEXP = /\./g, CHARS_GLOBAL_REGEXP = /[\0\b\t\n\r\x1a\"\'\\]/g, CHARS_ESCAPE_MAP = { "\0": "\\0", "\b": "\\b", " ": "\\t", "\n": "\\n", "\r": "\\r", "": "\\Z", '"': '\\"', "'": "\\'", "\\": "\\\\" }; SqlString.escapeId = function(val2, forbidQualified) { if (Array.isArray(val2)) { for (var sql = "", i = 0; i < val2.length; i++) sql += (i === 0 ? "" : ", ") + SqlString.escapeId(val2[i], forbidQualified); return sql; } else return forbidQualified ? "`" + String(val2).replace(ID_GLOBAL_REGEXP, "``") + "`" : "`" + String(val2).replace(ID_GLOBAL_REGEXP, "``").replace(QUAL_GLOBAL_REGEXP, "`.`") + "`"; }; SqlString.escape = function(val2, stringifyObjects, timeZone) { if (val2 == null) return "NULL"; switch (typeof val2) { case "boolean": return val2 ? "true" : "false"; case "number": return val2 + ""; case "object": return Object.prototype.toString.call(val2) === "[object Date]" ? SqlString.dateToString(val2, timeZone || "local") : Array.isArray(val2) ? SqlString.arrayToList(val2, timeZone) : Buffer.isBuffer(val2) ? SqlString.bufferToString(val2) : typeof val2.toSqlString == "function" ? String(val2.toSqlString()) : stringifyObjects ? escapeString(val2.toString()) : SqlString.objectToValues(val2, timeZone); default: return escapeString(val2); } }; SqlString.arrayToList = function(array, timeZone) { for (var sql = "", i = 0; i < array.length; i++) { var val2 = array[i]; Array.isArray(val2) ? sql += (i === 0 ? "" : ", ") + "(" + SqlString.arrayToList(val2, timeZone) + ")" : sql += (i === 0 ? "" : ", ") + SqlString.escape(val2, !0, timeZone); } return sql; }; SqlString.format = function(sql, values, stringifyObjects, timeZone) { if (values == null) return sql; Array.isArray(values) || (values = [values]); for (var chunkIndex = 0, placeholdersRegex = /\?+/g, result = "", valuesIndex = 0, match; valuesIndex < values.length && (match = placeholdersRegex.exec(sql)); ) { var len = match[0].length; if (!(len > 2)) { var value = len === 2 ? SqlString.escapeId(values[valuesIndex]) : SqlString.escape(values[valuesIndex], stringifyObjects, timeZone); result += sql.slice(chunkIndex, match.index) + value, chunkIndex = placeholdersRegex.lastIndex, valuesIndex++; } } return chunkIndex === 0 ? sql : chunkIndex < sql.length ? result + sql.slice(chunkIndex) : result; }; SqlString.dateToString = function(date, timeZone) { var dt = new Date(date); if (isNaN(dt.getTime())) return "NULL"; var year, month, day, hour, minute, second, millisecond; if (timeZone === "local") year = dt.getFullYear(), month = dt.getMonth() + 1, day = dt.getDate(), hour = dt.getHours(), minute = dt.getMinutes(), second = dt.getSeconds(), millisecond = dt.getMilliseconds(); else { var tz = convertTimezone(timeZone); tz !== !1 && tz !== 0 && dt.setTime(dt.getTime() + tz * 6e4), year = dt.getUTCFullYear(), month = dt.getUTCMonth() + 1, day = dt.getUTCDate(), hour = dt.getUTCHours(), minute = dt.getUTCMinutes(), second = dt.getUTCSeconds(), millisecond = dt.getUTCMilliseconds(); } var str = zeroPad(year, 4) + "-" + zeroPad(month, 2) + "-" + zeroPad(day, 2) + " " + zeroPad(hour, 2) + ":" + zeroPad(minute, 2) + ":" + zeroPad(second, 2) + "." + zeroPad(millisecond, 3); return escapeString(str); }; SqlString.bufferToString = function(buffer) { return "X" + escapeString(buffer.toString("hex")); }; SqlString.objectToValues = function(object, timeZone) { var sql = ""; for (var key in object) { var val2 = object[key]; typeof val2 != "function" && (sql += (sql.length === 0 ? "" : ", ") + SqlString.escapeId(key) + " = " + SqlString.escape(val2, !0, timeZone)); } return sql; }; SqlString.raw = function(sql) { if (typeof sql != "string") throw new TypeError("argument sql must be a string"); return { toSqlString: function() { return sql; } }; }; function escapeString(val2) { for (var chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex = 0, escapedVal = "", match; match = CHARS_GLOBAL_REGEXP.exec(val2); ) escapedVal += val2.slice(chunkIndex, match.index) + CHARS_ESCAPE_MAP[match[0]], chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex; return chunkIndex === 0 ? "'" + val2 + "'" : chunkIndex < val2.length ? "'" + escapedVal + val2.slice(chunkIndex) + "'" : "'" + escapedVal + "'"; } function zeroPad(number, length) { for (number = number.toString(); number.length < length; ) number = "0" + number; return number; } function convertTimezone(tz) { if (tz === "Z") return 0; var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/); return m ? (m[1] === "-" ? -1 : 1) * (parseInt(m[2], 10) + (m[3] ? parseInt(m[3], 10) : 0) / 60) * 60 : !1; } } }); // node_modules/sqlstring/index.js var require_sqlstring = __commonJS({ "node_modules/sqlstring/index.js"(exports2, module2) { module2.exports = require_SqlString(); } }); // node_modules/denque/index.js var require_denque = __commonJS({ "node_modules/denque/index.js"(exports2, module2) { "use strict"; function Denque(array, options) { var options = options || {}; this._capacity = options.capacity, this._head = 0, this._tail = 0, Array.isArray(array) ? this._fromArray(array) : (this._capacityMask = 3, this._list = new Array(4)); } Denque.prototype.peekAt = function(index) { var i = index; if (i === (i | 0)) { var len = this.size(); if (!(i >= len || i < -len)) return i < 0 && (i += len), i = this._head + i & this._capacityMask, this._list[i]; } }; Denque.prototype.get = function(i) { return this.peekAt(i); }; Denque.prototype.peek = function() { if (this._head !== this._tail) return this._list[this._head]; }; Denque.prototype.peekFront = function() { return this.peek(); }; Denque.prototype.peekBack = function() { return this.peekAt(-1); }; Object.defineProperty(Denque.prototype, "length", { get: function() { return this.size(); } }); Denque.prototype.size = function() { return this._head === this._tail ? 0 : this._head < this._tail ? this._tail - this._head : this._capacityMask + 1 - (this._head - this._tail); }; Denque.prototype.unshift = function(item) { if (arguments.length === 0) return this.size(); var len = this._list.length; return this._head = this._head - 1 + len & this._capacityMask, this._list[this._head] = item, this._tail === this._head && this._growArray(), this._capacity && this.size() > this._capacity && this.pop(), this._head < this._tail ? this._tail - this._head : this._capacityMask + 1 - (this._head - this._tail); }; Denque.prototype.shift = function() { var head = this._head; if (head !== this._tail) { var item = this._list[head]; return this._list[head] = void 0, this._head = head + 1 & this._capacityMask, head < 2 && this._tail > 1e4 && this._tail <= this._list.length >>> 2 && this._shrinkArray(), item; } }; Denque.prototype.push = function(item) { if (arguments.length === 0) return this.size(); var tail = this._tail; return this._list[tail] = item, this._tail = tail + 1 & this._capacityMask, this._tail === this._head && this._growArray(), this._capacity && this.size() > this._capacity && this.shift(), this._head < this._tail ? this._tail - this._head : this._capacityMask + 1 - (this._head - this._tail); }; Denque.prototype.pop = function() { var tail = this._tail; if (tail !== this._head) { var len = this._list.length; this._tail = tail - 1 + len & this._capacityMask; var item = this._list[this._tail]; return this._list[this._tail] = void 0, this._head < 2 && tail > 1e4 && tail <= len >>> 2 && this._shrinkArray(), item; } }; Denque.prototype.removeOne = function(index) { var i = index; if (i === (i | 0) && this._head !== this._tail) { var size = this.size(), len = this._list.length; if (!(i >= size || i < -size)) { i < 0 && (i += size), i = this._head + i & this._capacityMask; var item = this._list[i], k; if (index < size / 2) { for (k = index; k > 0; k--) this._list[i] = this._list[i = i - 1 + len & this._capacityMask]; this._list[i] = void 0, this._head = this._head + 1 + len & this._capacityMask; } else { for (k = size - 1 - index; k > 0; k--) this._list[i] = this._list[i = i + 1 + len & this._capacityMask]; this._list[i] = void 0, this._tail = this._tail - 1 + len & this._capacityMask; } return item; } } }; Denque.prototype.remove = function(index, count) { var i = index, removed, del_count = count; if (i === (i | 0) && this._head !== this._tail) { var size = this.size(), len = this._list.length; if (!(i >= size || i < -size || count < 1)) { if (i < 0 && (i += size), count === 1 || !count) return removed = new Array(1), removed[0] = this.removeOne(i), removed; if (i === 0 && i + count >= size) return removed = this.toArray(), this.clear(), removed; i + count > size && (count = size - i); var k; for (removed = new Array(count), k = 0; k < count; k++) removed[k] = this._list[this._head + i + k & this._capacityMask]; if (i = this._head + i & this._capacityMask, index + count === size) { for (this._tail = this._tail - count + len & this._capacityMask, k = count; k > 0; k--) this._list[i = i + 1 + len & this._capacityMask] = void 0; return removed; } if (index === 0) { for (this._head = this._head + count + len & this._capacityMask, k = count - 1; k > 0; k--) this._list[i = i + 1 + len & this._capacityMask] = void 0; return removed; } if (i < size / 2) { for (this._head = this._head + index + count + len & this._capacityMask, k = index; k > 0; k--) this.unshift(this._list[i = i - 1 + len & this._capacityMask]); for (i = this._head - 1 + len & this._capacityMask; del_count > 0; ) this._list[i = i - 1 + len & this._capacityMask] = void 0, del_count--; index < 0 && (this._tail = i); } else { for (this._tail = i, i = i + count + len & this._capacityMask, k = size - (count + index); k > 0; k--) this.push(this._list[i++]); for (i = this._tail; del_count > 0; ) this._list[i = i + 1 + len & this._capacityMask] = void 0, del_count--; } return this._head < 2 && this._tail > 1e4 && this._tail <= len >>> 2 && this._shrinkArray(), removed; } } }; Denque.prototype.splice = function(index, count) { var i = index; if (i === (i | 0)) { var size = this.size(); if (i < 0 && (i += size), !(i > size)) if (arguments.length > 2) { var k, temp, removed, arg_len = arguments.length, len = this._list.length, arguments_index = 2; if (!size || i < size / 2) { for (temp = new Array(i), k = 0; k < i; k++) temp[k] = this._list[this._head + k & this._capacityMask]; for (count === 0 ? (removed = [], i > 0 && (this._head = this._head + i + len & this._capacityMask)) : (removed = this.remove(i, count), this._head = this._head + i + len & this._capacityMask); arg_len > arguments_index; ) this.unshift(arguments[--arg_len]); for (k = i; k > 0; k--) this.unshift(temp[k - 1]); } else { temp = new Array(size - (i + count)); var leng = temp.length; for (k = 0; k < leng; k++) temp[k] = this._list[this._head + i + count + k & this._capacityMask]; for (count === 0 ? (removed = [], i != size && (this._tail = this._head + i + len & this._capacityMask)) : (removed = this.remove(i, count), this._tail = this._tail - leng + len & this._capacityMask); arguments_index < arg_len; ) this.push(arguments[arguments_index++]); for (k = 0; k < leng; k++) this.push(temp[k]); } return removed; } else return this.remove(i, count); } }; Denque.prototype.clear = function() { this._list = new Array(this._list.length), this._head = 0, this._tail = 0; }; Denque.prototype.isEmpty = function() { return this._head === this._tail; }; Denque.prototype.toArray = function() { return this._copyArray(!1); }; Denque.prototype._fromArray = function(array) { var length = array.length, capacity = this._nextPowerOf2(length); this._list = new Array(capacity), this._capacityMask = capacity - 1, this._tail = length; for (var i = 0; i < length; i++) this._list[i] = array[i]; }; Denque.prototype._copyArray = function(fullCopy, size) { var src = this._list, capacity = src.length, length = this.length; if (size = size | length, size == length && this._head < this._tail) return this._list.slice(this._head, this._tail); var dest = new Array(size), k = 0, i; if (fullCopy || this._head > this._tail) { for (i = this._head; i < capacity; i++) dest[k++] = src[i]; for (i = 0; i < this._tail; i++) dest[k++] = src[i]; } else for (i = this._head; i < this._tail; i++) dest[k++] = src[i]; return dest; }; Denque.prototype._growArray = function() { if (this._head != 0) { var newList = this._copyArray(!0, this._list.length << 1); this._tail = this._list.length, this._head = 0, this._list = newList; } else this._tail = this._list.length, this._list.length <<= 1; this._capacityMask = this._capacityMask << 1 | 1; }; Denque.prototype._shrinkArray = function() { this._list.length >>>= 1, this._capacityMask >>>= 1; }; Denque.prototype._nextPowerOf2 = function(num) { var log2 = Math.log(num) / Math.log(2), nextPow2 = 1 << log2 + 1; return Math.max(nextPow2, 4); }; module2.exports = Denque; } }); // node_modules/mysql2/node_modules/lru-cache/dist/cjs/index.js var require_cjs = __commonJS({ "node_modules/mysql2/node_modules/lru-cache/dist/cjs/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: !0 }); exports2.LRUCache = void 0; var perf = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date, warned = /* @__PURE__ */ new Set(), emitWarning = (msg, type, code, fn) => { typeof process == "object" && process && typeof process.emitWarning == "function" ? process.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`); }, shouldWarn = (code) => !warned.has(code), TYPE = Symbol("type"), isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n), getUintArray = (max) => isPosInt(max) ? max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null : null, ZeroArray = class extends Array { constructor(size) { super(size), this.fill(0); } }, Stack = class _Stack { heap; length; // private constructor static #constructing = !1; static create(max) { let HeapCls = getUintArray(max); if (!HeapCls) return []; _Stack.#constructing = !0; let s = new _Stack(max, HeapCls); return _Stack.#constructing = !1, s; } constructor(max, HeapCls) { if (!_Stack.#constructing) throw new TypeError("instantiate Stack using Stack.create(n)"); this.heap = new HeapCls(max), this.length = 0; } push(n) { this.heap[this.length++] = n; } pop() { return this.heap[--this.length]; } }, LRUCache = class _LRUCache { // properties coming in from the options of these, only max and maxSize // really *need* to be protected. The rest can be modified, as they just // set defaults for various methods. #max; #maxSize; #dispose; #disposeAfter; #fetchMethod; /** * {@link LRUCache.OptionsBase.ttl} */ ttl; /** * {@link LRUCache.OptionsBase.ttlResolution} */ ttlResolution; /** * {@link LRUCache.OptionsBase.ttlAutopurge} */ ttlAutopurge; /** * {@link LRUCache.OptionsBase.updateAgeOnGet} */ updateAgeOnGet; /** * {@link LRUCache.OptionsBase.updateAgeOnHas} */ updateAgeOnHas; /** * {@link LRUCache.OptionsBase.allowStale} */ allowStale; /** * {@link LRUCache.OptionsBase.noDisposeOnSet} */ noDisposeOnSet; /** * {@link LRUCache.OptionsBase.noUpdateTTL} */ noUpdateTTL; /** * {@link LRUCache.OptionsBase.maxEntrySize} */ maxEntrySize; /** * {@link LRUCache.OptionsBase.sizeCalculation} */ sizeCalculation; /** * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} */ noDeleteOnFetchRejection; /** * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} */ noDeleteOnStaleGet; /** * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} */ allowStaleOnFetchAbort; /** * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} */ allowStaleOnFetchRejection; /** * {@link LRUCache.OptionsBase.ignoreFetchAbort} */ ignoreFetchAbort; // computed properties #size; #calculatedSize; #keyMap; #keyList; #valList; #next; #prev; #head; #tail; #free; #disposed; #sizes; #starts; #ttls; #hasDispose; #hasFetchMethod; #hasDisposeAfter; /** * Do not call this method unless you need to inspect the * inner workings of the cache. If anything returned by this * object is modified in any way, strange breakage may occur. * * These fields are private for a reason! * * @internal */ static unsafeExposeInternals(c) { return { // properties starts: c.#starts, ttls: c.#ttls, sizes: c.#sizes, keyMap: c.#keyMap, keyList: c.#keyList, valList: c.#valList, next: c.#next, prev: c.#prev, get head() { return c.#head; }, get tail() { return c.#tail; }, free: c.#free, // methods isBackgroundFetch: (p) => c.#isBackgroundFetch(p), backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), moveToTail: (index) => c.#moveToTail(index), indexes: (options) => c.#indexes(options), rindexes: (options) => c.#rindexes(options), isStale: (index) => c.#isStale(index) }; } // Protected read-only members /** * {@link LRUCache.OptionsBase.max} (read-only) */ get max() { return this.#max; } /** * {@link LRUCache.OptionsBase.maxSize} (read-only) */ get maxSize() { return this.#maxSize; } /** * The total computed size of items in the cache (read-only) */ get calculatedSize() { return this.#calculatedSize; } /** * The number of items stored in the cache (read-only) */ get size() { return this.#size; } /** * {@link LRUCache.OptionsBase.fetchMethod} (read-only) */ get fetchMethod() { return this.#fetchMethod; } /** * {@link LRUCache.OptionsBase.dispose} (read-only) */ get dispose() { return this.#dispose; } /** * {@link LRUCache.OptionsBase.disposeAfter} (read-only) */ get disposeAfter() { return this.#disposeAfter; } constructor(options) { let { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options; if (max !== 0 && !isPosInt(max)) throw new TypeError("max option must be a nonnegative integer"); let UintArray = max ? getUintArray(max) : Array; if (!UintArray) throw new Error("invalid max value: " + max); if (this.#max = max, this.#maxSize = maxSize, this.maxEntrySize = maxEntrySize || this.#maxSize, this.sizeCalculation = sizeCalculation, this.sizeCalculation) { if (!this.#maxSize && !this.maxEntrySize) throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize"); if (typeof this.sizeCalculation != "function") throw new TypeError("sizeCalculation set to non-function"); } if (fetchMethod !== void 0 && typeof fetchMethod != "function") throw new TypeError("fetchMethod must be a function if specified"); if (this.#fetchMethod = fetchMethod, this.#hasFetchMethod = !!fetchMethod, this.#keyMap = /* @__PURE__ */ new Map(), this.#keyList = new Array(max).fill(void 0), this.#valList = new Array(max).fill(void 0), this.#next = new UintArray(max), this.#prev = new UintArray(max), this.#head = 0, this.#tail = 0, this.#free = Stack.create(max), this.#size = 0, this.#calculatedSize = 0, typeof dispose == "function" && (this.#dispose = dispose), typeof disposeAfter == "function" ? (this.#disposeAfter = disposeAfter, this.#disposed = []) : (this.#disposeAfter = void 0, this.#disposed = void 0), this.#hasDispose = !!this.#dispose, this.#hasDisposeAfter = !!this.#disposeAfter, this.noDisposeOnSet = !!noDisposeOnSet, this.noUpdateTTL = !!noUpdateTTL, this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection, this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection, this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort, this.ignoreFetchAbort = !!ignoreFetchAbort, this.maxEntrySize !== 0) { if (this.#maxSize !== 0 && !isPosInt(this.#maxSize)) throw new TypeError("maxSize must be a positive integer if specified"); if (!isPosInt(this.maxEntrySize)) throw new TypeError("maxEntrySize must be a positive integer if specified"); this.#initializeSizeTracking(); } if (this.allowStale = !!allowStale, this.noDeleteOnStaleGet = !!noDeleteOnStaleGet, this.updateAgeOnGet = !!updateAgeOnGet, this.updateAgeOnHas = !!updateAgeOnHas, this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1, this.ttlAutopurge = !!ttlAutopurge, this.ttl = ttl || 0, this.ttl) { if (!isPosInt(this.ttl)) throw new TypeError("ttl must be a positive integer if specified"); this.#initializeTTLTracking(); } if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) throw new TypeError("At least one of max, maxSize, or ttl is required"); if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { let code = "LRU_CACHE_UNBOUNDED"; shouldWarn(code) && (warned.add(code), emitWarning("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", code, _LRUCache)); } } /** * Return the remaining TTL time for a given entry key */ getRemainingTTL(key) { return this.#keyMap.has(key) ? 1 / 0 : 0; } #initializeTTLTracking() { let ttls = new ZeroArray(this.#max), starts = new ZeroArray(this.#max); this.#ttls = ttls, this.#starts = starts, this.#setItemTTL = (index, ttl, start = perf.now()) => { if (starts[index] = ttl !== 0 ? start : 0, ttls[index] = ttl, ttl !== 0 && this.ttlAutopurge) { let t = setTimeout(() => { this.#isStale(index) && this.delete(this.#keyList[index]); }, ttl + 1); t.unref && t.unref(); } }, this.#updateItemAge = (index) => { starts[index] = ttls[index] !== 0 ? perf.now() : 0; }, this.#statusTTL = (status, index) => { if (ttls[index]) { let ttl = ttls[index], start = starts[index]; status.ttl = ttl, status.start = start, status.now = cachedNow || getNow(), status.remainingTTL = status.now + ttl - start; } }; let cachedNow = 0, getNow = () => { let n = perf.now(); if (this.ttlResolution > 0) { cachedNow = n; let t = setTimeout(() => cachedNow = 0, this.ttlResolution); t.unref && t.unref(); } return n; }; this.getRemainingTTL = (key) => { let index = this.#keyMap.get(key); return index === void 0 ? 0 : ttls[index] === 0 || starts[index] === 0 ? 1 / 0 : starts[index] + ttls[index] - (cachedNow || getNow()); }, this.#isStale = (index) => ttls[index] !== 0 && starts[index] !== 0 && (cachedNow || getNow()) - starts[index] > ttls[index]; } // conditionally set private methods related to TTL #updateItemAge = () => { }; #statusTTL = () => { }; #setItemTTL = () => { }; /* c8 ignore stop */ #isStale = () => !1; #initializeSizeTracking() { let sizes = new ZeroArray(this.#max); this.#calculatedSize = 0, this.#sizes = sizes, this.#removeItemSize = (index) => { this.#calculatedSize -= sizes[index], sizes[index] = 0; }, this.#requireSize = (k, v, size, sizeCalculation) => { if (this.#isBackgroundFetch(v)) return 0; if (!isPosInt(size)) if (sizeCalculation) { if (typeof sizeCalculation != "function") throw new TypeError("sizeCalculation must be a function"); if (size = sizeCalculation(v, k), !isPosInt(size)) throw new TypeError("sizeCalculation return invalid (expect positive integer)"); } else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set."); return size; }, this.#addItemSize = (index, size, status) => { if (sizes[index] = size, this.#maxSize) { let maxSize = this.#maxSize - sizes[index]; for (; this.#calculatedSize > maxSize; ) this.#evict(!0); } this.#calculatedSize += sizes[index], status && (status.entrySize = size, status.totalCalculatedSize = this.#calculatedSize); }; } #removeItemSize = (_i) => { }; #addItemSize = (_i, _s, _st) => { }; #requireSize = (_k, _v, size, sizeCalculation) => { if (size || sizeCalculation) throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache"); return 0; }; *#indexes({ allowStale = this.allowStale } = {}) { if (this.#size) for (let i = this.#tail; !(!this.#isValidIndex(i) || ((allowStale || !this.#isStale(i)) && (yield i), i === this.#head)); ) i = this.#prev[i]; } *#rindexes({ allowStale = this.allowStale } = {}) { if (this.#size) for (let i = this.#head; !(!this.#isValidIndex(i) || ((allowStale || !this.#isStale(i)) && (yield i), i === this.#tail)); ) i = this.#next[i]; } #isValidIndex(index) { return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index; } /** * Return a generator yielding `[key, value]` pairs, * in order from most recently used to least recently used. */ *entries() { for (let i of this.#indexes()) this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i]) && (yield [this.#keyList[i], this.#valList[i]]); } /** * Inverse order version of {@link LRUCache.entries} * * Return a generator yielding `[key, value]` pairs, * in order from least recently used to most recently used. */ *rentries() { for (let i of this.#rindexes()) this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i]) && (yield [this.#keyList[i], this.#valList[i]]); } /** * Return a generator yielding the keys in the cache, * in order from most recently used to least recently used. */ *keys() { for (let i of this.#indexes()) { let k = this.#keyList[i]; k !== void 0 && !this.#isBackgroundFetch(this.#valList[i]) && (yield k); } } /** * Inverse order version of {@link LRUCache.keys} * * Return a generator yielding the keys in the cache, * in order from least recently used to most recently used. */ *rkeys() { for (let i of this.#rindexes()) { let k = this.#keyList[i]; k !== void 0 && !this.#isBackgroundFetch(this.#valList[i]) && (yield k); } } /** * Return a generator yielding the values in the cache, * in order from most recently used to least recently used. */ *values() { for (let i of this.#indexes()) this.#valList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i]) && (yield this.#valList[i]); } /** * Inverse order version of {@link LRUCache.values} * * Return a generator yielding the values in the cache, * in order from least recently used to most recently used. */ *rvalues() { for (let i of this.#rindexes()) this.#valList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i]) && (yield this.#valList[i]); } /** * Iterating over the cache itself yields the same results as * {@link LRUCache.entries} */ [Symbol.iterator]() { return this.entries(); } /** * Find a value for which the supplied fn method returns a truthy value, * similar to Array.find(). fn is called as fn(value, key, cache). */ find(fn, getOptions = {}) { for (let i of this.#indexes()) { let v = this.#valList[i], value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value !== void 0 && fn(value, this.#keyList[i], this)) return this.get(this.#keyList[i], getOptions); } } /** * Call the supplied function on each item in the cache, in order from * most recently used to least recently used. fn is called as * fn(value, key, cache). Does not update age or recenty of use. * Does not iterate over stale values. */ forEach(fn, thisp = this) { for (let i of this.#indexes()) { let v = this.#valList[i], value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; value !== void 0 && fn.call(thisp, value, this.#keyList[i], this); } } /** * The same as {@link LRUCache.forEach} but items are iterated over in * reverse order. (ie, less recently used items are iterated over first.) */ rforEach(fn, thisp = this) { for (let i of this.#rindexes()) { let v = this.#valList[i], value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; value !== void 0 && fn.call(thisp, value, this.#keyList[i], this); } } /** * Delete any stale entries. Returns true if anything was removed, * false otherwise. */ purgeStale() { let deleted = !1; for (let i of this.#rindexes({ allowStale: !0 })) this.#isStale(i) && (this.delete(this.#keyList[i]), deleted = !0); return deleted; } /** * Return an array of [key, {@link LRUCache.Entry}] tuples which can be * passed to cache.load() */ dump() { let arr = []; for (let i of this.#indexes({ allowStale: !0 })) { let key = this.#keyList[i], v = this.#valList[i], value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === void 0 || key === void 0) continue; let entry = { value }; if (this.#ttls && this.#starts) { entry.ttl = this.#ttls[i]; let age = perf.now() - this.#starts[i]; entry.start = Math.floor(Date.now() - age); } this.#sizes && (entry.size = this.#sizes[i]), arr.unshift([key, entry]); } return arr; } /** * Reset the cache and load in the items in entries in the order listed. * Note that the shape of the resulting cache may be different if the * same options are not used in both caches. */ load(arr) { this.clear(); for (let [key, entry] of arr) { if (entry.start) { let age = Date.now() - entry.start; entry.start = perf.now() - age; } this.set(key, entry.value, entry); } } /** * Add a value to the cache. */ set(k, v, setOptions = {}) { var _a, _b, _c; let { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions, { noUpdateTTL = this.noUpdateTTL } = setOptions, size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); if (this.maxEntrySize && size > this.maxEntrySize) return status && (status.set = "miss", status.maxEntrySizeExceeded = !0), this.delete(k), this; let index = this.#size === 0 ? void 0 : this.#keyMap.get(k); if (index === void 0) index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(!1) : this.#size, this.#keyList[index] = k, this.#valList[index] = v, this.#keyMap.set(k, index), this.#next[this.#tail] = index, this.#prev[index] = this.#tail, this.#tail = index, this.#size++, this.#addItemSize(index, size, status), status && (status.set = "add"), noUpdateTTL = !1; else { this.#moveToTail(index); let oldVal = this.#valList[index]; if (v !== oldVal) { if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal) ? oldVal.__abortController.abort(new Error("replaced")) : noDisposeOnSet || (this.#hasDispose && ((_a = this.#dispose) == null || _a.call(this, oldVal, k, "set")), this.#hasDisposeAfter && ((_b = this.#disposed) == null || _b.push([oldVal, k, "set"]))), this.#removeItemSize(index), this.#addItemSize(index, size, status), this.#valList[index] = v, status) { status.set = "replace"; let oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal; oldValue !== void 0 && (status.oldValue = oldValue); } } else status && (status.set = "update"); } if (ttl !== 0 && !this.#ttls && this.#initializeTTLTracking(), this.#ttls && (noUpdateTTL || this.#setItemTTL(index, ttl, start), status && this.#statusTTL(status, index)), !noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { let dt = this.#disposed, task; for (; task = dt == null ? void 0 : dt.shift(); ) (_c = this.#disposeAfter) == null || _c.call(this, ...task); } return this; } /** * Evict the least recently used item, returning its value or * `undefined` if cache is empty. */ pop() { var _a; try { for (; this.#size; ) { let val2 = this.#valList[this.#head]; if (this.#evict(!0), this.#isBackgroundFetch(val2)) { if (val2.__staleWhileFetching) return val2.__staleWhileFetching; } else if (val2 !== void 0) return val2; } } finally { if (this.#hasDisposeAfter && this.#disposed) { let dt = this.#disposed, task; for (; task = dt == null ? void 0 : dt.shift(); ) (_a = this.#disposeAfter) == null || _a.call(this, ...task); } } } #evict(free) { var _a, _b; let head = this.#head, k = this.#keyList[head], v = this.#valList[head]; return this.#hasFetchMethod && this.#isBackgroundFetch(v) ? v.__abortController.abort(new Error("evicted")) : (this.#hasDispose || this.#hasDisposeAfter) && (this.#hasDispose && ((_a = this.#dispose) == null || _a.call(this, v, k, "evict")), this.#hasDisposeAfter && ((_b = this.#disposed) == null || _b.push([v, k, "evict"]))), this.#removeItemSize(head), free && (this.#keyList[head] = void 0, this.#valList[head] = void 0, this.#free.push(head)), this.#size === 1 ? (this.#head = this.#tail = 0, this.#free.length = 0) : this.#head = this.#next[head], this.#keyMap.delete(k), this.#size--, head; } /** * Check if a key is in the cache, without updating the recency of use. * Will return false if the item is stale, even though it is technically * in the cache. * * Will not update item age unless * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. */ has(k, hasOptions = {}) { let { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions, index = this.#keyMap.get(k); if (index !== void 0) { let v = this.#valList[index]; if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) return !1; if (this.#isStale(index)) status && (status.has = "stale", this.#statusTTL(status, index)); else return updateAgeOnHas && this.#updateItemAge(index), status && (status.has = "hit", this.#statusTTL(status, index)), !0; } else status && (status.has = "miss"); return !1; } /** * Like {@link LRUCache#get} but doesn't update recency or delete stale * items. * * Returns `undefined` if the item is stale, unless * {@link LRUCache.OptionsBase.allowStale} is set. */ peek(k, peekOptions = {}) { let { allowStale = this.allowStale } = peekOptions, index = this.#keyMap.get(k); if (index !== void 0 && (allowStale || !this.#isStale(index))) { let v = this.#valList[index]; return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; } } #backgroundFetch(k, index, options, context) { let v = index === void 0 ? void 0 : this.#valList[index]; if (this.#isBackgroundFetch(v)) return v; let ac = new AbortController(), { signal } = options; signal == null || signal.addEventListener("abort", () => ac.abort(signal.reason), { signal: ac.signal }); let fetchOpts = { signal: ac.signal, options, context }, cb = (v2, updateCache = !1) => { let { aborted } = ac.signal, ignoreAbort = options.ignoreFetchAbort && v2 !== void 0; if (options.status && (aborted && !updateCache ? (options.status.fetchAborted = !0, options.status.fetchError = ac.signal.reason, ignoreAbort && (options.status.fetchAbortIgnored = !0)) : options.status.fetchResolved = !0), aborted && !ignoreAbort && !updateCache) return fetchFail(ac.signal.reason); let bf2 = p; return this.#valList[index] === p && (v2 === void 0 ? bf2.__staleWhileFetching ? this.#valList[index] = bf2.__staleWhileFetching : this.delete(k) : (options.status && (options.status.fetchUpdated = !0), this.set(k, v2, fetchOpts.options))), v2; }, eb = (er) => (options.status && (options.status.fetchRejected = !0, options.status.fetchError = er), fetchFail(er)), fetchFail = (er) => { let { aborted } = ac.signal, allowStaleAborted = aborted && options.allowStaleOnFetchAbort, allowStale = allowStaleAborted || options.allowStaleOnFetchRejection, noDelete = allowStale || options.noDeleteOnFetchRejection, bf2 = p; if (this.#valList[index] === p && (!noDelete || bf2.__staleWhileFetching === void 0 ? this.delete(k) : allowStaleAborted || (this.#valList[index] = bf2.__staleWhileFetching)), allowStale) return options.status && bf2.__staleWhileFetching !== void 0 && (options.status.returnedStale = !0), bf2.__staleWhileFetching; if (bf2.__returned === bf2) throw er; }, pcall = (res, rej) => { var _a; let fmp = (_a = this.#fetchMethod) == null ? void 0 : _a.call(this, k, v, fetchOpts); fmp && fmp instanceof Promise && fmp.then((v2) => res(v2), rej), ac.signal.addEventListener("abort", () => { (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) && (res(), options.allowStaleOnFetchAbort && (res = (v2) => cb(v2, !0))); }); }; options.status && (options.status.fetchDispatched = !0); let p = new Promise(pcall).then(cb, eb), bf = Object.assign(p, { __abortController: ac, __staleWhileFetching: v, __returned: void 0 }); return index === void 0 ? (this.set(k, bf, { ...fetchOpts.options, status: void 0 }), index = this.#keyMap.get(k)) : this.#valList[index] = bf, bf; } #isBackgroundFetch(p) { if (!this.#hasFetchMethod) return !1; let b = p; return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AbortController; } async fetch(k, fetchOptions = {}) { let { // get options allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, // set options ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, // fetch exclusive options noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = !1, status, signal } = fetchOptions; if (!this.#hasFetchMethod) return status && (status.fetch = "get"), this.get(k, { allowStale, updateAgeOnGet, noDeleteOnStaleGet, status }); let options = { allowStale, updateAgeOnGet, noDeleteOnStaleGet, ttl, noDisposeOnSet, size, sizeCalculation, noUpdateTTL, noDeleteOnFetchRejection, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, status, signal }, index = this.#keyMap.get(k); if (index === void 0) { status && (status.fetch = "miss"); let p = this.#backgroundFetch(k, index, options, context); return p.__returned = p; } else { let v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { let stale = allowStale && v.__staleWhileFetching !== void 0; return status && (status.fetch = "inflight", stale && (status.returnedStale = !0)), stale ? v.__staleWhileFetching : v.__returned = v; } let isStale = this.#isStale(index); if (!forceRefresh && !isStale) return status && (status.fetch = "hit"), this.#moveToTail(index), updateAgeOnGet && this.#updateItemAge(index), status && this.#statusTTL(status, index), v; let p = this.#backgroundFetch(k, index, options, context), staleVal = p.__staleWhileFetching !== void 0 && allowStale; return status && (status.fetch = isStale ? "stale" : "refresh", staleVal && isStale && (status.returnedStale = !0)), staleVal ? p.__staleWhileFetching : p.__returned = p; } } /** * Return a value from the cache. Will update the recency of the cache * entry found. * * If the key is not found, get() will return `undefined`. */ get(k, getOptions = {}) { let { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions, index = this.#keyMap.get(k); if (index !== void 0) { let value = this.#valList[index], fetching = this.#isBackgroundFetch(value); return status && this.#statusTTL(status, index), this.#isStale(index) ? (status && (status.get = "stale"), fetching ? (status && allowStale && value.__staleWhileFetching !== void 0 && (status.returnedStale = !0), allowStale ? value.__staleWhileFetching : void 0) : (noDeleteOnStaleGet || this.delete(k), status && allowStale && (status.returnedStale = !0), allowStale ? value : void 0)) : (status && (status.get = "hit"), fetching ? value.__staleWhileFetching : (this.#moveToTail(index), updateAgeOnGet && this.#updateItemAge(index), value)); } else status && (status.get = "miss"); } #connect(p, n) { this.#prev[n] = p, this.#next[p] = n; } #moveToTail(index) { index !== this.#tail && (index === this.#head ? this.#head = this.#next[index] : this.#connect(this.#prev[index], this.#next[index]), this.#connect(this.#tail, index), this.#tail = index); } /** * Deletes a key out of the cache. * Returns true if the key was deleted, false otherwise. */ delete(k) { var _a, _b, _c, _d; let deleted = !1; if (this.#size !== 0) { let index = this.#keyMap.get(k); if (index !== void 0) if (deleted = !0, this.#size === 1) this.clear(); else { this.#removeItemSize(index); let v = this.#valList[index]; this.#isBackgroundFetch(v) ? v.__abortController.abort(new Error("deleted")) : (this.#hasDispose || this.#hasDisposeAfter) && (this.#hasDispose && ((_a = this.#dispose) == null || _a.call(this, v, k, "delete")), this.#hasDisposeAfter && ((_b = this.#disposed) == null || _b.push([v, k, "delete"]))), this.#keyMap.delete(k), this.#keyList[index] = void 0, this.#valList[index] = void 0, index === this.#tail ? this.#tail = this.#prev[index] : index === this.#head ? this.#head = this.#next[index] : (this.#next[this.#prev[index]] = this.#next[index], this.#prev[this.#next[index]] = this.#prev[index]), this.#size--, this.#free.push(index); } } if (this.#hasDisposeAfter && ((